feat(KAN-37): rebuild security and application key settings

This commit is contained in:
2026-09-15 14:01:23 +00:00
parent bc6a113acf
commit 196623bb67
13 changed files with 1814 additions and 824 deletions
+147 -101
View File
@@ -1,123 +1,169 @@
<script setup lang="ts"> <script setup lang="ts">
import { Form } from '@inertiajs/vue3'; import { useForm } from '@inertiajs/vue3';
import { Eye, EyeOff, LockKeyhole, RefreshCw } from 'lucide-vue-next'; import { Eye, EyeOff, LockKeyhole, RefreshCw } from 'lucide-vue-next';
import { nextTick, onMounted, ref, useTemplateRef } from 'vue'; import { ref } from 'vue';
import AlertError from '@/components/AlertError.vue'; import AlertError from '@/components/AlertError.vue';
import AuthFormFeedback from '@/components/AuthFormFeedback.vue';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Card, Dialog,
CardContent, DialogContent,
CardDescription, DialogDescription,
CardHeader, DialogFooter,
CardTitle, DialogHeader,
} from '@/components/ui/card'; DialogTitle,
} from '@/components/ui/dialog';
import { useFormProtection } from '@/composables/useFormProtection';
import { useLocalization } from '@/composables/useLocalization';
import { useTwoFactorAuth } from '@/composables/useTwoFactorAuth'; import { useTwoFactorAuth } from '@/composables/useTwoFactorAuth';
import { regenerateRecoveryCodes } from '@/routes/two-factor'; import { regenerateRecoveryCodes } from '@/routes/two-factor';
const { recoveryCodesList, fetchRecoveryCodes, errors } = useTwoFactorAuth(); const { t } = useLocalization();
const isRecoveryCodesVisible = ref<boolean>(false); const {
const recoveryCodeSectionRef = useTemplateRef('recoveryCodeSectionRef'); recoveryCodesList,
fetchRecoveryCodes,
clearRecoveryCodes,
errors,
loading,
} = useTwoFactorAuth();
const visible = ref(false);
const showRegenerate = ref(false);
const form = useForm({});
const protection = useFormProtection(form);
const toggleRecoveryCodesVisibility = async () => { function hide(): void {
if (!isRecoveryCodesVisible.value && !recoveryCodesList.value.length) { visible.value = false;
await fetchRecoveryCodes(); clearRecoveryCodes();
} }
function toggle(): void {
isRecoveryCodesVisible.value = !isRecoveryCodesVisible.value; if (visible.value) {
hide();
if (isRecoveryCodesVisible.value) { } else {
await nextTick(); visible.value = true;
recoveryCodeSectionRef.value?.scrollIntoView({ behavior: 'smooth' }); void fetchRecoveryCodes();
} }
};
onMounted(async () => {
if (!recoveryCodesList.value.length) {
await fetchRecoveryCodes();
} }
function closeRegenerate(open: boolean): void {
if (!form.processing) {
showRegenerate.value = open;
protection.clearFeedback();
}
}
function regenerate(): void {
protection.submit(regenerateRecoveryCodes(), {
preserveScroll: true,
onBefore: hide,
onSuccess: () => {
showRegenerate.value = false;
visible.value = true;
return fetchRecoveryCodes();
},
}); });
}
</script> </script>
<template> <template>
<Card class="w-full"> <section
<CardHeader> class="gap-column grid min-w-0 rounded-lg border p-4"
<CardTitle class="flex gap-3"> aria-labelledby="recovery-title"
<LockKeyhole class="size-4" />2FA recovery codes
</CardTitle>
<CardDescription>
Recovery codes let you regain access if you lose your 2FA
device. Store them in a secure password manager.
</CardDescription>
</CardHeader>
<CardContent>
<div
class="flex select-none flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
> >
<Button @click="toggleRecoveryCodesVisibility" class="w-fit"> <div class="gap-stack grid">
<component <h3
:is="isRecoveryCodesVisible ? EyeOff : Eye" id="recovery-title"
class="size-4" class="flex items-center gap-2 font-semibold"
/>
{{ isRecoveryCodesVisible ? 'Hide' : 'View' }} recovery
codes
</Button>
<Form
v-if="isRecoveryCodesVisible && recoveryCodesList.length"
v-bind="regenerateRecoveryCodes.form()"
method="post"
:options="{ preserveScroll: true }"
@success="fetchRecoveryCodes"
#default="{ processing }"
> >
<Button <LockKeyhole class="text-primary size-4" />{{
variant="secondary" t('security.recoveryTitle')
type="submit" }}
:disabled="processing" </h3>
> <p class="text-body text-muted-foreground">
<RefreshCw /> Regenerate codes {{ t('security.recoveryDescription') }}
</Button>
</Form>
</div>
<div
:class="[
'relative overflow-hidden transition-all duration-300',
isRecoveryCodesVisible
? 'h-auto opacity-100'
: 'h-0 opacity-0',
]"
>
<div v-if="errors?.length" class="mt-6">
<AlertError :errors="errors" />
</div>
<div v-else class="mt-3 space-y-3">
<div
ref="recoveryCodeSectionRef"
class="bg-muted grid gap-1 rounded-lg p-4 font-mono text-sm"
>
<div v-if="!recoveryCodesList.length" class="space-y-2">
<div
v-for="n in 8"
:key="n"
class="bg-muted-foreground/20 h-4 animate-pulse rounded"
></div>
</div>
<div
v-else
v-for="(code, index) in recoveryCodesList"
:key="index"
>
{{ code }}
</div>
</div>
<p class="text-muted-foreground select-none text-xs">
Each recovery code can be used once to access your
account and will be removed after use. If you need more,
click
<span class="font-bold">Regenerate codes</span> above.
</p> </p>
</div> </div>
<div class="flex flex-wrap gap-3">
<Button
variant="outline"
:aria-expanded="visible"
aria-controls="recovery-codes"
:disabled="form.processing"
@click="toggle"
><component :is="visible ? EyeOff : Eye" />{{
t(
visible
? 'security.hideRecovery'
: 'security.viewRecovery',
)
}}</Button
>
<Button
v-if="visible && recoveryCodesList.length"
variant="secondary"
@click="showRegenerate = true"
><RefreshCw />{{ t('security.regenerate') }}</Button
>
</div> </div>
</CardContent> <div v-if="visible" id="recovery-codes" class="gap-stack grid">
</Card> <p
v-if="loading"
role="status"
class="bg-muted animate-pulse rounded-lg p-4"
>
{{ t('security.loadingRecovery') }}
</p>
<template v-else-if="errors.length">
<AlertError :errors="errors" />
<Button
class="justify-self-start"
variant="outline"
@click="fetchRecoveryCodes"
>{{ t('common.retry') }}</Button
>
</template>
<template v-else>
<ul
class="bg-muted grid gap-2 rounded-lg p-4 font-mono text-sm sm:grid-cols-2"
:aria-label="t('security.recoveryTitle')"
>
<li v-for="code in recoveryCodesList" :key="code">
{{ code }}
</li>
</ul>
<p class="text-caption text-muted-foreground">
{{ t('security.recoveryOnce') }}
</p>
</template>
</div>
<Dialog :open="showRegenerate" @update:open="closeRegenerate">
<DialogContent
:show-close-button="!form.processing"
@escape-key-down="form.processing && $event.preventDefault()"
@interact-outside="form.processing && $event.preventDefault()"
>
<DialogHeader>
<DialogTitle>{{
t('security.regenerateTitle')
}}</DialogTitle>
<DialogDescription>{{
t('security.regenerateDescription')
}}</DialogDescription>
</DialogHeader>
<AuthFormFeedback
:state="protection.state.value"
:response-status="protection.responseStatus.value"
@retry="regenerate"
/>
<DialogFooter>
<Button
variant="outline"
:disabled="form.processing"
@click="closeRegenerate(false)"
>{{ t('common.cancel') }}</Button
>
<Button :loading="form.processing" @click="regenerate">{{
t('security.regenerate')
}}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</section>
</template> </template>
+212 -248
View File
@@ -1,297 +1,261 @@
<script setup lang="ts"> <script setup lang="ts">
import { Form } from '@inertiajs/vue3'; import { useForm } from '@inertiajs/vue3';
import { useClipboard } from '@vueuse/core';
import { Check, Copy, ScanLine } from 'lucide-vue-next'; import { Check, Copy, ScanLine } from 'lucide-vue-next';
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue'; import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';
import AlertError from '@/components/AlertError.vue'; import AlertError from '@/components/AlertError.vue';
import AuthFormFeedback from '@/components/AuthFormFeedback.vue';
import InputError from '@/components/InputError.vue'; import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription, DialogDescription,
DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { import { Input } from '@/components/ui/input';
InputOTP, import { Label } from '@/components/ui/label';
InputOTPGroup, import { useFormProtection } from '@/composables/useFormProtection';
InputOTPSlot, import { useLocalization } from '@/composables/useLocalization';
} from '@/components/ui/input-otp';
import { Spinner } from '@/components/ui/spinner';
import { useAppearance } from '@/composables/useAppearance';
import { useTwoFactorAuth } from '@/composables/useTwoFactorAuth'; import { useTwoFactorAuth } from '@/composables/useTwoFactorAuth';
import { confirm } from '@/routes/two-factor'; import { confirm } from '@/routes/two-factor';
import type { TwoFactorConfigContent } from '@/types';
type Props = { const props = defineProps<{
requiresConfirmation: boolean; requiresConfirmation: boolean;
twoFactorEnabled: boolean; twoFactorEnabled: boolean;
}; }>();
const { resolvedAppearance } = useAppearance();
const props = defineProps<Props>();
const isOpen = defineModel<boolean>('isOpen'); const isOpen = defineModel<boolean>('isOpen');
const { t } = useLocalization();
const { copy, copied } = useClipboard(); const {
const { qrCodeSvg, manualSetupKey, clearSetupData, fetchSetupData, errors } = qrCodeSvg,
useTwoFactorAuth(); manualSetupKey,
hasSetupData,
const showVerificationStep = ref(false); clearSetupData,
const code = ref<string>(''); fetchSetupData,
errors,
const pinInputContainerRef = useTemplateRef('pinInputContainerRef'); loading,
} = useTwoFactorAuth();
const modalConfig = computed<TwoFactorConfigContent>(() => { const form = useForm({ code: '' }).dontRemember('code');
if (props.twoFactorEnabled) { const protection = useFormProtection(form, { isDirty: () => false });
return { const verification = ref(false);
title: 'Two-factor authentication enabled', const copied = ref(false);
description: const copyError = ref(false);
'Two-factor authentication is now enabled. Scan the QR code or enter the setup key in your authenticator app.', const codeInput = useTemplateRef('codeInput');
buttonText: 'Close', const title = computed(() =>
}; t(
} props.twoFactorEnabled
? 'security.setupEnabled'
if (showVerificationStep.value) { : verification.value
return { ? 'security.verifyTitle'
title: 'Verify authentication code', : 'security.setupTitle',
description: 'Enter the 6-digit code from your authenticator app', ),
buttonText: 'Continue',
};
}
return {
title: 'Enable two-factor authentication',
description:
'To finish enabling two-factor authentication, scan the QR code or enter the setup key in your authenticator app',
buttonText: 'Continue',
};
});
const handleModalNextStep = () => {
if (props.requiresConfirmation) {
showVerificationStep.value = true;
nextTick(() => {
pinInputContainerRef.value?.querySelector('input')?.focus();
});
return;
}
clearSetupData();
isOpen.value = false;
};
const resetModalState = () => {
if (props.twoFactorEnabled) {
clearSetupData();
}
showVerificationStep.value = false;
code.value = '';
};
watch(
() => isOpen.value,
async (isOpen) => {
if (!isOpen) {
resetModalState();
return;
}
if (!qrCodeSvg.value) {
await fetchSetupData();
}
},
); );
const description = computed(() =>
t(
props.twoFactorEnabled
? 'security.setupEnabledDescription'
: verification.value
? 'security.verifyDescription'
: 'security.setupDescription',
),
);
function close(open: boolean): void {
if (!form.processing) {
isOpen.value = open;
}
}
async function next(): Promise<void> {
if (props.twoFactorEnabled || !props.requiresConfirmation) {
close(false);
return;
}
verification.value = true;
await nextTick();
codeInput.value?.$el?.focus();
}
function submit(): void {
protection.submit(confirm(), {
preserveScroll: true,
errorBag: 'confirmTwoFactorAuthentication',
onSuccess: () => {
isOpen.value = false;
},
onFinish: () => {
form.reset();
},
});
}
async function copyKey(): Promise<void> {
const key = manualSetupKey.value;
if (!key) {
return;
}
copyError.value = false;
try {
await navigator.clipboard.writeText(key);
if (isOpen.value && manualSetupKey.value === key) {
copied.value = true;
}
} catch {
if (isOpen.value) {
copyError.value = true;
}
}
}
watch(isOpen, (open) => {
verification.value = false;
copied.value = false;
copyError.value = false;
form.resetAndClearErrors();
protection.clearFeedback();
clearSetupData();
if (open) {
void fetchSetupData();
}
});
</script> </script>
<template> <template>
<Dialog :open="isOpen" @update:open="isOpen = $event"> <Dialog :open="isOpen" @update:open="close">
<DialogContent class="sm:max-w-md"> <DialogContent
<DialogHeader class="flex items-center justify-center"> class="sm:max-w-md"
<div :show-close-button="!form.processing"
class="border-border bg-card mb-3 w-auto rounded-full border p-0.5 shadow-sm" @escape-key-down="form.processing && $event.preventDefault()"
@interact-outside="form.processing && $event.preventDefault()"
> >
<div <DialogHeader>
class="border-border bg-muted relative overflow-hidden rounded-full border p-2.5" <ScanLine class="text-primary size-8" />
> <DialogTitle>{{ title }}</DialogTitle>
<div <DialogDescription>{{ description }}</DialogDescription>
class="absolute inset-0 grid grid-cols-5 opacity-50"
>
<div
v-for="i in 5"
:key="`col-${i}`"
class="border-border border-r last:border-r-0"
/>
</div>
<div
class="absolute inset-0 grid grid-rows-5 opacity-50"
>
<div
v-for="i in 5"
:key="`row-${i}`"
class="border-border border-b last:border-b-0"
/>
</div>
<ScanLine
class="text-foreground relative z-20 size-6"
/>
</div>
</div>
<DialogTitle>{{ modalConfig.title }}</DialogTitle>
<DialogDescription class="text-center">
{{ modalConfig.description }}
</DialogDescription>
</DialogHeader> </DialogHeader>
<template v-if="!verification">
<div <p
class="relative flex w-auto flex-col items-center justify-center space-y-5" v-if="loading"
role="status"
class="bg-muted animate-pulse rounded-lg p-6 text-center"
> >
<template v-if="!showVerificationStep"> {{ t('security.loadingSetup') }}
<AlertError v-if="errors?.length" :errors="errors" /> </p>
<template v-else> <div v-else-if="errors.length" class="gap-stack grid">
<div <AlertError :errors="errors" />
class="relative mx-auto flex max-w-md items-center overflow-hidden" <Button variant="outline" @click="fetchSetupData">{{
> t('common.retry')
<div }}</Button>
class="border-border relative mx-auto aspect-square w-64 overflow-hidden rounded-lg border"
>
<div
v-if="!qrCodeSvg"
class="bg-background absolute inset-0 z-10 flex aspect-square h-auto w-full animate-pulse items-center justify-center"
>
<Spinner class="size-6" />
</div> </div>
<div v-else-if="hasSetupData" class="gap-column grid min-w-0">
<div <div
v-else class="mx-auto aspect-square w-full max-w-56 rounded-lg border bg-white p-4 text-black"
class="relative z-10 overflow-hidden border p-5"
>
<div
v-html="qrCodeSvg" v-html="qrCodeSvg"
class="flex aspect-square size-full items-center justify-center"
:style="{
filter:
resolvedAppearance === 'dark'
? 'invert(1) brightness(1.5)'
: undefined,
}"
/> />
</div> <div class="grid min-w-0 gap-2">
</div> <Label for="setup-key">{{
</div> t('security.manualKey')
}}</Label>
<div class="flex w-full items-center space-x-5"> <div class="flex min-w-0 gap-2">
<Button class="w-full" @click="handleModalNextStep"> <Input
{{ modalConfig.buttonText }} id="setup-key"
</Button> :model-value="manualSetupKey"
</div>
<div
class="relative flex w-full items-center justify-center"
>
<div
class="bg-border absolute inset-0 top-1/2 h-px w-full"
/>
<span class="bg-card relative px-2 py-1"
>or, enter the code manually</span
>
</div>
<div
class="flex w-full items-center justify-center space-x-2"
>
<div
class="border-border flex w-full items-stretch overflow-hidden rounded-xl border"
>
<div
v-if="!manualSetupKey"
class="bg-muted flex h-full w-full items-center justify-center p-3"
>
<Spinner />
</div>
<template v-else>
<input
type="text"
readonly readonly
:value="manualSetupKey" class="min-w-0 font-mono text-xs"
class="bg-background text-foreground h-full w-full p-3"
/> />
<button <Button
@click="copy(manualSetupKey || '')" variant="outline"
class="border-border hover:bg-muted relative block h-auto border-l px-3" :aria-label="
> t(
<Check copied
? 'security.copied'
: 'security.copyKey',
)
"
@click="copyKey"
><Check v-if="copied" /><Copy v-else
/></Button>
</div>
<p
v-if="copied" v-if="copied"
class="w-4 text-green-500" role="status"
class="text-caption text-success-foreground"
>
{{ t('security.copied') }}
</p>
<InputError
v-if="copyError"
:message="t('security.copyError')"
/> />
<Copy v-else class="w-4" />
</button>
</template>
</div> </div>
</div> </div>
<p
v-if="requiresConfirmation && !twoFactorEnabled"
class="text-caption text-muted-foreground"
>
{{ t('security.setupPendingDescription') }}
</p>
<DialogFooter>
<Button variant="outline" @click="close(false)">{{
t('common.close')
}}</Button>
<Button v-if="hasSetupData" @click="next">{{
t(
twoFactorEnabled || !requiresConfirmation
? 'common.done'
: 'security.continue',
)
}}</Button>
</DialogFooter>
</template> </template>
</template> <form v-else class="gap-column grid" @submit.prevent="submit">
<AuthFormFeedback
<template v-else> :state="protection.state.value"
<Form :response-status="protection.responseStatus.value"
v-bind="confirm.form()" @retry="submit"
error-bag="confirmTwoFactorAuthentication" />
reset-on-error <div class="grid gap-2">
@finish="code = ''" <Label for="authentication-code">{{
@success="isOpen = false" t('security.authenticationCode')
v-slot="{ errors, processing }" }}</Label>
> <Input
<input type="hidden" name="code" :value="code" /> id="authentication-code"
<div ref="codeInput"
ref="pinInputContainerRef" v-model="form.code"
class="relative w-full space-y-3" name="code"
> type="text"
<div inputmode="numeric"
class="flex w-full flex-col items-center justify-center space-y-3 py-2" autocomplete="one-time-code"
> pattern="[0-9]{6}"
<InputOTP maxlength="6"
id="otp" required
v-model="code" :disabled="form.processing"
:maxlength="6" :aria-invalid="!!form.errors.code"
:disabled="processing" aria-describedby="authentication-code-error"
> class="font-mono text-lg tracking-widest"
<InputOTPGroup> />
<InputOTPSlot <InputError
v-for="index in 6" id="authentication-code-error"
:key="index" :message="form.errors.code"
:index="index - 1"
/> />
</InputOTPGroup>
</InputOTP>
<InputError :message="errors?.code" />
</div> </div>
<DialogFooter>
<div class="flex w-full items-center space-x-5">
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
class="w-auto flex-1" :disabled="form.processing"
@click="showVerificationStep = false" @click="
:disabled="processing" verification = false;
form.resetAndClearErrors();
protection.clearFeedback();
"
>{{ t('common.back') }}</Button
> >
Back
</Button>
<Button <Button
type="submit" type="submit"
class="w-auto flex-1" :disabled="form.code.length !== 6"
:disabled="processing || code.length < 6" :loading="form.processing"
>{{ t('security.confirm') }}</Button
> >
Confirm </DialogFooter>
</Button> </form>
</div>
</div>
</Form>
</template>
</div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</template> </template>
+84 -97
View File
@@ -1,120 +1,107 @@
import type { ComputedRef, Ref } from 'vue'; import { computed, onScopeDispose, ref } from 'vue';
import { computed, ref } from 'vue'; import { useLocalization } from '@/composables/useLocalization';
import { qrCode, recoveryCodes, secretKey } from '@/routes/two-factor'; import { qrCode, recoveryCodes, secretKey } from '@/routes/two-factor';
export type UseTwoFactorAuthReturn = { /** Keep secrets within the consuming component and discard late responses after hiding them. */
qrCodeSvg: Ref<string | null>; export function useTwoFactorAuth() {
manualSetupKey: Ref<string | null>; const { t } = useLocalization();
recoveryCodesList: Ref<string[]>;
errors: Ref<string[]>;
hasSetupData: ComputedRef<boolean>;
clearSetupData: () => void;
clearErrors: () => void;
clearTwoFactorAuthData: () => void;
fetchQrCode: () => Promise<void>;
fetchSetupKey: () => Promise<void>;
fetchSetupData: () => Promise<void>;
fetchRecoveryCodes: () => Promise<void>;
};
const fetchJson = async <T>(url: string): Promise<T> => {
const response = await fetch(url, {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`Failed to fetch: ${response.status}`);
}
return response.json();
};
const errors = ref<string[]>([]); const errors = ref<string[]>([]);
const manualSetupKey = ref<string | null>(null); const manualSetupKey = ref<string | null>(null);
const qrCodeSvg = ref<string | null>(null); const qrCodeSvg = ref<string | null>(null);
const recoveryCodesList = ref<string[]>([]); const recoveryCodesList = ref<string[]>([]);
const loading = ref(false);
let pending: AbortController | null = null;
const hasSetupData = computed<boolean>( async function fetchJson<T>(url: string, signal: AbortSignal): Promise<T> {
() => qrCodeSvg.value !== null && manualSetupKey.value !== null, const response = await fetch(url, {
); headers: { Accept: 'application/json' },
credentials: 'same-origin',
export const useTwoFactorAuth = (): UseTwoFactorAuthReturn => { signal,
const fetchQrCode = async (): Promise<void> => { });
try { if (!response.ok || response.redirected) {
const { svg } = await fetchJson<{ svg: string; url: string }>( throw new Error(String(response.status));
qrCode.url(),
);
qrCodeSvg.value = svg;
} catch {
errors.value.push('Failed to fetch QR code');
qrCodeSvg.value = null;
} }
}; return response.json();
const fetchSetupKey = async (): Promise<void> => {
try {
const { secretKey: key } = await fetchJson<{ secretKey: string }>(
secretKey.url(),
);
manualSetupKey.value = key;
} catch {
errors.value.push('Failed to fetch a setup key');
manualSetupKey.value = null;
} }
};
const clearSetupData = (): void => { function clearErrors(): void {
manualSetupKey.value = null;
qrCodeSvg.value = null;
clearErrors();
};
const clearErrors = (): void => {
errors.value = []; errors.value = [];
};
const clearTwoFactorAuthData = (): void => {
clearSetupData();
clearErrors();
recoveryCodesList.value = [];
};
const fetchRecoveryCodes = async (): Promise<void> => {
try {
clearErrors();
recoveryCodesList.value = await fetchJson<string[]>(
recoveryCodes.url(),
);
} catch {
errors.value.push('Failed to fetch recovery codes');
recoveryCodesList.value = [];
} }
};
const fetchSetupData = async (): Promise<void> => { function clearTwoFactorAuthData(): void {
try { pending?.abort();
clearErrors(); pending = null;
await Promise.all([fetchQrCode(), fetchSetupKey()]); loading.value = false;
} catch {
qrCodeSvg.value = null;
manualSetupKey.value = null; manualSetupKey.value = null;
qrCodeSvg.value = null;
recoveryCodesList.value = [];
clearErrors();
} }
};
async function load(kind: 'setup' | 'recovery'): Promise<void> {
clearTwoFactorAuthData();
const request = new AbortController();
pending = request;
loading.value = true;
try {
if (kind === 'setup') {
const [qr, key] = await Promise.all([
fetchJson<{ svg: string }>(qrCode.url(), request.signal),
fetchJson<{ secretKey: string }>(
secretKey.url(),
request.signal,
),
]);
if (pending !== request) {
return;
}
qrCodeSvg.value = qr.svg;
manualSetupKey.value = key.secretKey;
} else {
const codes = await fetchJson<string[]>(
recoveryCodes.url(),
request.signal,
);
if (pending === request) {
recoveryCodesList.value = codes;
}
}
} catch (error) {
if (pending === request && !request.signal.aborted) {
const status = error instanceof Error ? error.message : '';
errors.value = [
t(
status === '423' || status === '401' || status === '419'
? 'security.confirmAgain'
: kind === 'setup'
? 'security.setupError'
: 'security.recoveryError',
),
];
}
} finally {
if (pending === request) {
pending = null;
loading.value = false;
}
}
}
onScopeDispose(clearTwoFactorAuthData);
return { return {
qrCodeSvg, qrCodeSvg,
manualSetupKey, manualSetupKey,
recoveryCodesList, recoveryCodesList,
errors, errors,
hasSetupData, loading,
clearSetupData, hasSetupData: computed(() =>
clearErrors, Boolean(qrCodeSvg.value && manualSetupKey.value),
),
clearSetupData: clearTwoFactorAuthData,
clearRecoveryCodes: clearTwoFactorAuthData,
clearTwoFactorAuthData, clearTwoFactorAuthData,
fetchQrCode, clearErrors,
fetchSetupKey, fetchSetupData: () => load('setup'),
fetchSetupData, fetchRecoveryCodes: () => load('recovery'),
fetchRecoveryCodes,
};
}; };
}
+2 -2
View File
@@ -71,7 +71,7 @@ const { isCurrentOrParentUrl } = useCurrentUrl();
</header> </header>
<div <div
class="bg-card grid min-w-0 overflow-hidden rounded-xl border shadow-sm lg:grid-cols-[15rem_minmax(0,1fr)]" class="bg-card grid min-w-0 grid-cols-1 overflow-hidden rounded-xl border shadow-sm lg:grid-cols-[15rem_minmax(0,1fr)]"
> >
<aside <aside
class="bg-muted/35 border-b p-3 lg:border-b-0 lg:border-r lg:p-4" class="bg-muted/35 border-b p-3 lg:border-b-0 lg:border-r lg:p-4"
@@ -105,7 +105,7 @@ const { isCurrentOrParentUrl } = useCurrentUrl();
</aside> </aside>
<div class="min-w-0 p-4 sm:p-6 lg:p-8"> <div class="min-w-0 p-4 sm:p-6 lg:p-8">
<section class="mx-auto grid max-w-3xl gap-8"> <section class="mx-auto grid w-full min-w-0 max-w-3xl gap-8">
<slot /> <slot />
</section> </section>
</div> </div>
+90
View File
@@ -1,4 +1,94 @@
export const en = { export const en = {
'security.title': 'Security settings',
'security.passwordTitle': 'Update password',
'security.passwordDescription':
'Use a long, unique password to keep your account secure.',
'security.currentPassword': 'Current password',
'security.newPassword': 'New password',
'security.confirmPassword': 'Confirm password',
'security.savePassword': 'Save password',
'security.savingPassword': 'Saving password…',
'security.passwordSaved': 'Password saved.',
'security.twoFactorTitle': 'Two-factor authentication',
'security.twoFactorDescription':
'Add a second layer of protection with a code from your authenticator app.',
'security.enabledDescription':
'Your authenticator app provides a six-digit code when you sign in. Keep your recovery codes somewhere safe.',
'security.enabled': 'Enabled',
'security.disabled': 'Disabled',
'security.pending': 'Awaiting confirmation',
'security.enable': 'Enable 2FA',
'security.disable': 'Disable 2FA',
'security.continueSetup': 'Continue setup',
'security.disableTitle': 'Disable two-factor authentication?',
'security.disableDescription':
'You will no longer need an authenticator code to sign in. Your existing recovery codes will be removed.',
'security.setupTitle': 'Set up your authenticator',
'security.setupDescription':
'Scan this QR code with a TOTP authenticator app, or enter the setup key manually.',
'security.setupEnabled': 'Two-factor authentication enabled',
'security.setupEnabledDescription':
'Finish adding this account to your authenticator app and save your recovery codes.',
'security.verifyTitle': 'Verify authentication code',
'security.verifyDescription':
'Enter the six-digit code from your authenticator app to finish enabling two-factor authentication.',
'security.authenticationCode': 'Authentication code',
'security.manualKey': 'Manual setup key',
'security.copyKey': 'Copy key',
'security.copied': 'Copied',
'security.copyError':
'Copying failed. Select the key and copy it manually.',
'security.confirm': 'Confirm',
'security.continue': 'Continue',
'security.loadingSetup': 'Loading authenticator setup…',
'security.setupPendingDescription':
'Protection starts after you confirm a code. Closing this dialog keeps setup unfinished; you can continue from this page.',
'security.confirmAgain':
'Your session or password confirmation has expired. Reload this page and confirm your password to continue.',
'security.setupError':
'Authenticator setup could not be loaded. Please try again.',
'security.recoveryError':
'Recovery codes could not be loaded. Please try again.',
'security.recoveryTitle': '2FA recovery codes',
'security.recoveryDescription':
'Recovery codes let you regain access if you lose your authenticator. Store them in a secure password manager.',
'security.hideRecovery': 'Hide recovery codes',
'security.viewRecovery': 'View recovery codes',
'security.loadingRecovery': 'Loading recovery codes…',
'security.regenerate': 'Regenerate codes',
'security.recoveryOnce':
'Each recovery code can be used once. Hiding this section removes the codes from this page.',
'security.regenerateTitle': 'Regenerate recovery codes?',
'security.regenerateDescription':
'All previous recovery codes will stop working. Save the new codes in a secure place.',
'applications.title': 'Applications',
'applications.description':
'Create API keys for tools that use KanbanGit with your account permissions. Delete an application to revoke its access.',
'applications.saveKey': 'Save this API key now.',
'applications.keyOnce':
'This key is shown only after creation. It will not be shown again after you leave this page.',
'applications.apiKey': 'API key',
'applications.create': 'Create application',
'applications.nameDescription':
'Name the tool that will receive an API key.',
'applications.name': 'Application name',
'applications.namePlaceholder': 'For example, Claude Desktop',
'applications.creating': 'Creating application…',
'applications.saved': 'Saved applications',
'applications.hiddenKeys':
'Existing keys stay hidden. Create a new application when another key is needed.',
'applications.empty': 'No applications have been created yet.',
'applications.created': 'Created:',
'applications.lastUsed': 'Last used:',
'applications.never': 'Never',
'applications.delete': 'Delete',
'applications.deleteNamed': 'Delete {name}',
'applications.deleteTitle': 'Delete application?',
'applications.deleteDescription':
'{name} will lose access immediately. This cannot be undone.',
'common.back': 'Back',
'common.done': 'Done',
'criteria.title': 'Acceptance criteria', 'criteria.title': 'Acceptance criteria',
'criteria.progress': '{completed} of {total} complete', 'criteria.progress': '{completed} of {total} complete',
'criteria.empty': 'No acceptance criteria yet.', 'criteria.empty': 'No acceptance criteria yet.',
+274 -154
View File
@@ -1,198 +1,318 @@
<script setup lang="ts"> <script setup lang="ts">
import { Form, Head } from '@inertiajs/vue3'; import { Head, useForm } from '@inertiajs/vue3';
import UserApplicationController from '@/actions/App/Http/Controllers/Settings/UserApplicationController'; import { Check, Copy, KeyRound, Trash2 } from 'lucide-vue-next';
import Heading from '@/components/Heading.vue'; import { computed, ref, watch } from 'vue';
import InputError from '@/components/InputError.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { import {
Card, destroy,
CardContent, store,
CardDescription, } from '@/actions/App/Http/Controllers/Settings/UserApplicationController';
CardHeader, import AuthFormFeedback from '@/components/AuthFormFeedback.vue';
CardTitle, import InputError from '@/components/InputError.vue';
} from '@/components/ui/card'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { useFormProtection } from '@/composables/useFormProtection';
import { useLocalization } from '@/composables/useLocalization';
import AppLayout from '@/layouts/AppLayout.vue'; import AppLayout from '@/layouts/AppLayout.vue';
import SettingsLayout from '@/layouts/settings/Layout.vue'; import SettingsLayout from '@/layouts/settings/Layout.vue';
import { edit as editApplications } from '@/routes/applications/index'; import { edit } from '@/routes/applications/index';
import type { BreadcrumbItem, SettingsApplicationsPageProps } from '@/types'; import type { BreadcrumbItem, SettingsApplicationsPageProps } from '@/types';
defineProps<SettingsApplicationsPageProps>(); const props = defineProps<SettingsApplicationsPageProps>();
const { t, locale } = useLocalization();
const breadcrumbs = computed<BreadcrumbItem[]>(() => [
{ title: t('navigation.applications'), href: edit() },
]);
const form = useForm({ name: '' });
const protection = useFormProtection(form);
const deleteForm = useForm({});
const deleteProtection = useFormProtection(deleteForm);
const selected = ref<
SettingsApplicationsPageProps['applications'][number] | null
>(null);
const copied = ref(false);
const copyError = ref(false);
const breadcrumbItems: BreadcrumbItem[] = [ function formatDate(value: string | null): string {
{ if (!value) {
title: 'Applications', return t('applications.never');
href: editApplications(),
},
];
const formatDate = (value: string | null): string => {
if (value === null) {
return 'Never';
} }
return new Intl.DateTimeFormat(locale.value, {
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'medium', dateStyle: 'medium',
timeStyle: 'short', timeStyle: 'short',
}).format(new Date(value)); }).format(new Date(value));
}; }
function createApplication(): void {
protection.submit(store(), {
preserveScroll: true,
onSuccess: () => {
form.reset();
},
});
}
function closeDelete(open: boolean): void {
if (!open && !deleteForm.processing) {
selected.value = null;
deleteProtection.clearFeedback();
}
}
function deleteApplication(): void {
if (!selected.value) {
return;
}
deleteProtection.submit(destroy(selected.value.id), {
preserveScroll: true,
onSuccess: () => {
selected.value = null;
},
});
}
async function copyKey(): Promise<void> {
const key = props.applicationKey;
if (!key) {
return;
}
copyError.value = false;
try {
await navigator.clipboard.writeText(key);
if (props.applicationKey === key) {
copied.value = true;
}
} catch {
if (props.applicationKey === key) {
copyError.value = true;
}
}
}
watch(
() => props.applicationKey,
() => {
copied.value = false;
copyError.value = false;
},
);
</script> </script>
<template> <template>
<AppLayout :breadcrumbs="breadcrumbItems"> <AppLayout :breadcrumbs="breadcrumbs">
<Head title="Applications" /> <Head :title="t('applications.title')" />
<SettingsLayout> <SettingsLayout>
<div class="flex flex-col gap-6"> <div class="gap-stack grid">
<div class="space-y-2"> <h2 class="text-title">{{ t('applications.title') }}</h2>
<Heading <p class="text-muted-foreground">
variant="small" {{ t('applications.description') }}
title="Applications"
description="Create API keys for tools that should use KanbanGit with your account permissions."
/>
<p class="text-muted-foreground text-sm">
Keys are shown once. Delete an application when a tool
should lose access.
</p> </p>
</div> </div>
<p
<div
v-if="status" v-if="status"
class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-900 dark:border-emerald-900/70 dark:bg-emerald-950/40 dark:text-emerald-100" role="status"
class="bg-success/10 text-success-foreground rounded-lg border p-4 text-sm"
> >
{{ status }} {{ status }}
</div>
<div
v-if="applicationKey"
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900/70 dark:bg-amber-950/30 dark:text-amber-100"
>
<p class="font-medium">Save this API key now.</p>
<p class="mt-1">
It will not be shown again after you leave this page.
</p> </p>
<section
v-if="applicationKey"
class="bg-warning/10 gap-stack grid min-w-0 rounded-xl border p-5"
aria-labelledby="application-key-title"
>
<h3 id="application-key-title" class="font-semibold">
{{ t('applications.saveKey') }}
</h3>
<p class="text-body text-muted-foreground">
{{ t('applications.keyOnce') }}
</p>
<Label for="application-key" class="sr-only">{{
t('applications.apiKey')
}}</Label>
<div class="flex min-w-0 flex-wrap gap-2">
<Input <Input
class="mt-3 font-mono text-xs" id="application-key"
:model-value="applicationKey" :model-value="applicationKey"
readonly readonly
class="min-w-0 basis-full font-mono text-xs sm:flex-1 sm:basis-0"
/> />
</div> <Button variant="outline" @click="copyKey"
><Check v-if="copied" /><Copy v-else />{{
<div class="grid gap-6 xl:grid-cols-[24rem_minmax(0,1fr)]"> t(copied ? 'security.copied' : 'security.copyKey')
<Card> }}</Button
<CardHeader>
<CardTitle>Create application</CardTitle>
<CardDescription>
Name the tool that will receive an API key.
</CardDescription>
</CardHeader>
<CardContent>
<Form
v-bind="UserApplicationController.store.form()"
class="space-y-4"
v-slot="{ errors, processing }"
> >
</div>
<p
v-if="copied"
role="status"
class="text-caption text-success-foreground"
>
{{ t('security.copied') }}
</p>
<InputError
v-if="copyError"
:message="t('security.copyError')"
/>
</section>
<Card class="gap-0 overflow-hidden rounded-xl py-0 shadow-none">
<CardHeader class="gap-stack border-b p-5 sm:p-6">
<h3 class="flex items-center gap-2 font-semibold">
<KeyRound class="text-primary size-5" />{{
t('applications.create')
}}
</h3>
<p class="text-muted-foreground">
{{ t('applications.nameDescription') }}
</p>
</CardHeader>
<CardContent class="p-5 sm:p-6">
<form
class="gap-column grid"
:aria-busy="form.processing"
@submit.prevent="createApplication"
>
<AuthFormFeedback
:state="protection.state.value"
:response-status="protection.responseStatus.value"
:loading-title="t('applications.creating')"
@retry="createApplication"
/>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="name">Application name</Label> <Label for="application-name">{{
t('applications.name')
}}</Label>
<Input <Input
id="name" id="application-name"
v-model="form.name"
name="name" name="name"
type="text"
required required
autofocus maxlength="255"
placeholder="Claude Desktop" autocomplete="off"
:placeholder="t('applications.namePlaceholder')"
:disabled="form.processing"
:aria-invalid="!!form.errors.name"
aria-describedby="application-name-error"
/>
<InputError
id="application-name-error"
:message="form.errors.name"
/> />
<InputError :message="errors.name" />
</div> </div>
<Button type="submit" :disabled="processing">
Create application
</Button>
</Form>
</CardContent>
</Card>
<Card class="gap-0 overflow-hidden">
<CardHeader class="border-b">
<CardTitle>Saved applications</CardTitle>
<CardDescription>
Existing keys stay hidden. Create a new
application when another key is needed.
</CardDescription>
</CardHeader>
<CardContent class="space-y-4 p-6">
<div
v-if="applications.length === 0"
class="border-border text-muted-foreground rounded-xl border border-dashed px-4 py-6 text-sm"
>
No applications have been created yet.
</div>
<div
v-for="application in applications"
:key="application.id"
class="border-border rounded-xl border p-4"
>
<div
class="flex flex-wrap items-start justify-between gap-4"
>
<div class="space-y-2">
<div
class="flex flex-wrap items-center gap-2"
>
<Badge>API key</Badge>
<span class="text-sm font-medium">
{{ application.name }}
</span>
</div>
<p
class="text-muted-foreground text-xs"
>
Created:
{{
formatDate(
application.created_at,
)
}}
</p>
<p
class="text-muted-foreground text-xs"
>
Last used:
{{
formatDate(
application.last_used_at,
)
}}
</p>
</div>
<Form
v-bind="
UserApplicationController.destroy.form(
application.id,
)
"
v-slot="{ processing }"
>
<Button <Button
type="submit" type="submit"
variant="destructive" class="justify-self-start"
:disabled="processing" :loading="form.processing"
:loading-label="t('applications.creating')"
>{{ t('applications.create') }}</Button
> >
Delete </form>
</Button>
</Form>
</div>
</div>
</CardContent> </CardContent>
</Card> </Card>
<Card class="gap-0 overflow-hidden rounded-xl py-0 shadow-none">
<CardHeader class="gap-stack border-b p-5 sm:p-6">
<h3 class="font-semibold">{{ t('applications.saved') }}</h3>
<p class="text-muted-foreground">
{{ t('applications.hiddenKeys') }}
</p>
</CardHeader>
<CardContent class="gap-stack grid p-5 sm:p-6">
<p
v-if="!applications.length"
class="text-body text-muted-foreground rounded-lg border border-dashed p-6 text-center"
>
{{ t('applications.empty') }}
</p>
<article
v-for="application in applications"
:key="application.id"
class="flex min-w-0 flex-wrap items-start justify-between gap-4 rounded-lg border p-4"
>
<div class="gap-stack grid min-w-0 flex-1 basis-40">
<h4 class="break-words font-semibold">
{{ application.name }}
</h4>
<dl
class="gap-stack text-caption text-muted-foreground grid"
>
<div>
<dt class="inline font-medium">
{{ t('applications.created') }}
</dt>
<dd class="inline">
{{ formatDate(application.created_at) }}
</dd>
</div> </div>
<div>
<dt class="inline font-medium">
{{ t('applications.lastUsed') }}
</dt>
<dd class="inline">
{{
formatDate(application.last_used_at)
}}
</dd>
</div> </div>
</dl>
</div>
<Button
variant="outline"
class="text-destructive"
:aria-label="
t('applications.deleteNamed', {
name: application.name,
})
"
@click="selected = application"
><Trash2 />{{ t('applications.delete') }}</Button
>
</article>
</CardContent>
</Card>
<Dialog :open="!!selected" @update:open="closeDelete">
<DialogContent
:show-close-button="!deleteForm.processing"
@escape-key-down="
deleteForm.processing && $event.preventDefault()
"
@interact-outside="
deleteForm.processing && $event.preventDefault()
"
>
<DialogHeader>
<DialogTitle>{{
t('applications.deleteTitle')
}}</DialogTitle>
<DialogDescription>{{
t('applications.deleteDescription', {
name: selected?.name ?? '',
})
}}</DialogDescription>
</DialogHeader>
<AuthFormFeedback
:state="deleteProtection.state.value"
:response-status="deleteProtection.responseStatus.value"
@retry="deleteApplication"
/>
<DialogFooter>
<Button
variant="outline"
:disabled="deleteForm.processing"
@click="closeDelete(false)"
>{{ t('common.cancel') }}</Button
>
<Button
variant="destructive"
:loading="deleteForm.processing"
@click="deleteApplication"
>{{ t('applications.delete') }}</Button
>
</DialogFooter>
</DialogContent>
</Dialog>
</SettingsLayout> </SettingsLayout>
</AppLayout> </AppLayout>
</template> </template>
+273 -155
View File
@@ -1,222 +1,340 @@
<script setup lang="ts"> <script setup lang="ts">
import { Form, Head } from '@inertiajs/vue3'; import { Head, useForm } from '@inertiajs/vue3';
import { ShieldCheck } from 'lucide-vue-next'; import { ShieldCheck } from 'lucide-vue-next';
import { onUnmounted, ref } from 'vue'; import { computed, onUnmounted, ref } from 'vue';
import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController'; import { update } from '@/actions/App/Http/Controllers/Settings/SecurityController';
import Heading from '@/components/Heading.vue'; import AuthFormFeedback from '@/components/AuthFormFeedback.vue';
import InputError from '@/components/InputError.vue'; import InputError from '@/components/InputError.vue';
import PasswordInput from '@/components/PasswordInput.vue'; import PasswordInput from '@/components/PasswordInput.vue';
import TwoFactorRecoveryCodes from '@/components/TwoFactorRecoveryCodes.vue'; import TwoFactorRecoveryCodes from '@/components/TwoFactorRecoveryCodes.vue';
import TwoFactorSetupModal from '@/components/TwoFactorSetupModal.vue'; import TwoFactorSetupModal from '@/components/TwoFactorSetupModal.vue';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { useTwoFactorAuth } from '@/composables/useTwoFactorAuth'; import { useFormProtection } from '@/composables/useFormProtection';
import { useLocalization } from '@/composables/useLocalization';
import AppLayout from '@/layouts/AppLayout.vue'; import AppLayout from '@/layouts/AppLayout.vue';
import SettingsLayout from '@/layouts/settings/Layout.vue'; import SettingsLayout from '@/layouts/settings/Layout.vue';
import { edit } from '@/routes/security/index'; import { edit } from '@/routes/security/index';
import { disable, enable } from '@/routes/two-factor'; import { disable, enable } from '@/routes/two-factor';
import type { BreadcrumbItem } from '@/types'; import type { BreadcrumbItem } from '@/types';
type Props = { const props = withDefaults(
defineProps<{
canManageTwoFactor?: boolean; canManageTwoFactor?: boolean;
mustChangePassword?: boolean;
requiresConfirmation?: boolean; requiresConfirmation?: boolean;
status?: string | null;
twoFactorEnabled?: boolean; twoFactorEnabled?: boolean;
}; }>(),
withDefaults(defineProps<Props>(), {
canManageTwoFactor: false,
mustChangePassword: false,
requiresConfirmation: false,
status: null,
twoFactorEnabled: false,
});
const breadcrumbs: BreadcrumbItem[] = [
{ {
title: 'Security settings', canManageTwoFactor: false,
href: edit(), requiresConfirmation: false,
twoFactorEnabled: false,
}, },
]; );
const { t } = useLocalization();
const breadcrumbs = computed<BreadcrumbItem[]>(() => [
{ title: t('navigation.security'), href: edit() },
]);
const passwordForm = useForm({
current_password: '',
password: '',
password_confirmation: '',
}).dontRemember('current_password', 'password', 'password_confirmation');
const passwordProtection = useFormProtection(passwordForm, {
isDirty: () => false,
});
const twoFactorForm = useForm({});
const twoFactorProtection = useFormProtection(twoFactorForm);
const showSetupModal = ref(false);
const showDisableDialog = ref(false);
const setupStarted = ref(false);
const { hasSetupData, clearTwoFactorAuthData } = useTwoFactorAuth(); function savePassword(): void {
const showSetupModal = ref<boolean>(false); passwordProtection.submit(update(), {
preserveScroll: true,
onUnmounted(() => clearTwoFactorAuthData()); onFinish: () => passwordForm.reset(),
});
}
function startSetup(): void {
if (setupStarted.value) {
showSetupModal.value = true;
return;
}
twoFactorProtection.submit(enable(), {
preserveScroll: true,
onSuccess: () => {
setupStarted.value = true;
showSetupModal.value = true;
},
});
}
function disableTwoFactor(): void {
twoFactorProtection.submit(disable(), {
preserveScroll: true,
onSuccess: () => {
showDisableDialog.value = false;
setupStarted.value = false;
},
});
}
function updateDisableDialog(open: boolean): void {
if (!twoFactorForm.processing) {
showDisableDialog.value = open;
twoFactorProtection.clearFeedback();
}
}
onUnmounted(() => passwordForm.reset());
</script> </script>
<template> <template>
<AppLayout :breadcrumbs="breadcrumbs"> <AppLayout :breadcrumbs="breadcrumbs">
<Head title="Security settings" /> <Head :title="t('security.title')" />
<h1 class="sr-only">Security settings</h1>
<SettingsLayout> <SettingsLayout>
<div <Card class="gap-0 overflow-hidden rounded-xl py-0 shadow-none">
v-if="mustChangePassword || status" <CardHeader class="gap-stack border-b p-5 sm:p-6">
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/70 dark:bg-amber-950/40 dark:text-amber-100" <h2 class="text-title">
{{ t('security.passwordTitle') }}
</h2>
<p class="text-muted-foreground">
{{ t('security.passwordDescription') }}
</p>
</CardHeader>
<CardContent class="p-5 sm:p-6">
<form
class="gap-column grid"
:aria-busy="passwordForm.processing"
@submit.prevent="savePassword"
> >
{{ <AuthFormFeedback
mustChangePassword :state="passwordProtection.state.value"
? 'You must change your password before continuing anywhere else in the app.' :response-status="
: status passwordProtection.responseStatus.value
}} "
</div> :loading-title="t('security.savingPassword')"
:success-title="t('security.passwordSaved')"
<div class="space-y-6"> @retry="savePassword"
<Heading
variant="small"
title="Update password"
description="Ensure your account is using a long, random password to stay secure"
/> />
<fieldset
<Form class="gap-column grid min-w-0"
v-bind="SecurityController.update.form()" :disabled="passwordForm.processing"
:options="{
preserveScroll: true,
}"
reset-on-success
:reset-on-error="[
'password',
'password_confirmation',
'current_password',
]"
class="space-y-6"
v-slot="{ errors, processing, recentlySuccessful }"
> >
<legend class="sr-only">
{{ t('security.passwordTitle') }}
</legend>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="current_password">Current password</Label> <Label for="current_password">{{
t('security.currentPassword')
}}</Label>
<PasswordInput <PasswordInput
id="current_password" id="current_password"
v-model="passwordForm.current_password"
name="current_password" name="current_password"
class="mt-1 block w-full" required
autocomplete="current-password" autocomplete="current-password"
placeholder="Current password" :disabled="passwordForm.processing"
:aria-invalid="
!!passwordForm.errors.current_password
"
aria-describedby="current-password-error"
/>
<InputError
id="current-password-error"
:message="
passwordForm.errors.current_password
"
/> />
<InputError :message="errors.current_password" />
</div> </div>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="password">New password</Label> <Label for="password">{{
t('security.newPassword')
}}</Label>
<PasswordInput <PasswordInput
id="password" id="password"
v-model="passwordForm.password"
name="password" name="password"
class="mt-1 block w-full" required
autocomplete="new-password" autocomplete="new-password"
placeholder="New password" :disabled="passwordForm.processing"
:aria-invalid="
!!passwordForm.errors.password
"
aria-describedby="new-password-error"
/>
<InputError
id="new-password-error"
:message="passwordForm.errors.password"
/> />
<InputError :message="errors.password" />
</div> </div>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="password_confirmation" <Label for="password_confirmation">{{
>Confirm password</Label t('security.confirmPassword')
> }}</Label>
<PasswordInput <PasswordInput
id="password_confirmation" id="password_confirmation"
v-model="passwordForm.password_confirmation"
name="password_confirmation" name="password_confirmation"
class="mt-1 block w-full" required
autocomplete="new-password" autocomplete="new-password"
placeholder="Confirm password" :disabled="passwordForm.processing"
:aria-invalid="
!!passwordForm.errors
.password_confirmation
"
aria-describedby="password-confirmation-error"
/>
<InputError
id="password-confirmation-error"
:message="
passwordForm.errors
.password_confirmation
"
/> />
<InputError :message="errors.password_confirmation" />
</div> </div>
<div class="flex items-center gap-4">
<Button <Button
:disabled="processing" type="submit"
class="justify-self-start"
:loading="passwordForm.processing"
:loading-label="t('security.savingPassword')"
data-test="update-password-button" data-test="update-password-button"
>{{ t('security.savePassword') }}</Button
> >
Save password </fieldset>
</Button> </form>
</CardContent>
</Card>
<Transition <Card
enter-active-class="transition ease-in-out" v-if="canManageTwoFactor"
enter-from-class="opacity-0" class="gap-0 overflow-hidden rounded-xl py-0 shadow-none"
leave-active-class="transition ease-in-out"
leave-to-class="opacity-0"
> >
<p <CardHeader class="gap-stack border-b p-5 sm:p-6">
v-show="recentlySuccessful" <div
class="text-sm text-neutral-600" class="flex flex-wrap items-center justify-between gap-3"
> >
Saved. <h2 class="text-title flex items-center gap-2">
<ShieldCheck class="text-primary size-5" />{{
t('security.twoFactorTitle')
}}
</h2>
<span
class="bg-muted rounded-full px-3 py-1 text-xs font-semibold"
role="status"
>{{
t(
props.twoFactorEnabled
? 'security.enabled'
: setupStarted
? 'security.pending'
: 'security.disabled',
)
}}</span
>
</div>
<p class="text-muted-foreground">
{{
t(
props.twoFactorEnabled
? 'security.enabledDescription'
: 'security.twoFactorDescription',
)
}}
</p> </p>
</Transition> </CardHeader>
</div> <CardContent class="gap-column grid p-5 sm:p-6">
</Form> <AuthFormFeedback
</div> v-if="!showDisableDialog"
:state="twoFactorProtection.state.value"
<div v-if="canManageTwoFactor" class="space-y-6"> :response-status="
<Heading twoFactorProtection.responseStatus.value
variant="small" "
title="Two-factor authentication" @retry="
description="Manage your two-factor authentication settings" props.twoFactorEnabled
? (showDisableDialog = true)
: startSetup()
"
/> />
<div
v-if="!twoFactorEnabled"
class="flex flex-col items-start justify-start space-y-4"
>
<p class="text-muted-foreground text-sm">
When you enable two-factor authentication, you will be
prompted for a secure pin during login. This pin can be
retrieved from a TOTP-supported application on your
phone.
</p>
<div>
<Button <Button
v-if="hasSetupData" v-if="!twoFactorEnabled"
@click="showSetupModal = true" class="justify-self-start"
:loading="twoFactorForm.processing"
@click="startSetup"
>{{
t(
setupStarted
? 'security.continueSetup'
: 'security.enable',
)
}}</Button
> >
<ShieldCheck />Continue setup <template v-else>
</Button> <Button
<Form variant="outline"
v-else class="text-destructive justify-self-start"
v-bind="enable.form()" @click="showDisableDialog = true"
@success="showSetupModal = true" >{{ t('security.disable') }}</Button
#default="{ processing }"
> >
<Button type="submit" :disabled="processing"> <TwoFactorRecoveryCodes />
Enable 2FA </template>
</Button> </CardContent>
</Form> </Card>
</div> <TwoFactorSetupModal
</div> v-if="canManageTwoFactor"
v-model:is-open="showSetupModal"
<div :requires-confirmation="requiresConfirmation"
v-else :two-factor-enabled="twoFactorEnabled"
class="flex flex-col items-start justify-start space-y-4" />
<Dialog
:open="showDisableDialog"
@update:open="updateDisableDialog"
>
<DialogContent
:show-close-button="!twoFactorForm.processing"
@escape-key-down="
twoFactorForm.processing && $event.preventDefault()
"
@interact-outside="
twoFactorForm.processing && $event.preventDefault()
"
>
<DialogHeader>
<DialogTitle>{{
t('security.disableTitle')
}}</DialogTitle>
<DialogDescription>{{
t('security.disableDescription')
}}</DialogDescription>
</DialogHeader>
<AuthFormFeedback
:state="twoFactorProtection.state.value"
:response-status="
twoFactorProtection.responseStatus.value
"
@retry="disableTwoFactor"
/>
<DialogFooter>
<Button
variant="outline"
:disabled="twoFactorForm.processing"
@click="updateDisableDialog(false)"
>{{ t('common.cancel') }}</Button
> >
<p class="text-muted-foreground text-sm">
You will be prompted for a secure, random pin during
login, which you can retrieve from the TOTP-supported
application on your phone.
</p>
<div class="relative inline">
<Form v-bind="disable.form()" #default="{ processing }">
<Button <Button
variant="destructive" variant="destructive"
type="submit" :loading="twoFactorForm.processing"
:disabled="processing" @click="disableTwoFactor"
>{{ t('security.disable') }}</Button
> >
Disable 2FA </DialogFooter>
</Button> </DialogContent>
</Form> </Dialog>
</div>
<TwoFactorRecoveryCodes />
</div>
<TwoFactorSetupModal
v-model:isOpen="showSetupModal"
:requiresConfirmation="requiresConfirmation"
:twoFactorEnabled="twoFactorEnabled"
/>
</div>
</SettingsLayout> </SettingsLayout>
</AppLayout> </AppLayout>
</template> </template>
+52
View File
@@ -6,6 +6,7 @@ use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Inertia\Testing\AssertableInertia as Assert; use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
use Laravel\Fortify\Features; use Laravel\Fortify\Features;
use Tests\TestCase; use Tests\TestCase;
@@ -249,4 +250,55 @@ class SecurityTest extends TestCase
$this->assertTrue(Hash::check('password', $user->fresh()->password)); $this->assertTrue(Hash::check('password', $user->fresh()->password));
} }
public function test_two_factor_setup_requires_a_valid_code_before_protection_is_enabled(): void
{
$user = User::factory()->create();
$this->actingAs($user)->withSession(['auth.password_confirmed_at' => time()])
->from(route('security.edit'))
->post(route('two-factor.enable'))->assertSessionHasNoErrors();
$this->assertNotNull($user->refresh()->two_factor_secret);
$this->assertFalse($user->hasEnabledTwoFactorAuthentication());
$this->getJson(route('two-factor.secret-key'))->assertOk()->assertJsonStructure(['secretKey']);
$this->getJson(route('two-factor.qr-code'))->assertOk()->assertJsonStructure(['svg']);
$this->mock(TwoFactorAuthenticationProvider::class, function ($mock): void {
$mock->shouldReceive('verify')->withArgs(fn ($secret, $code) => $code === '000000')->once()->andReturn(false);
$mock->shouldReceive('verify')->withArgs(fn ($secret, $code) => $code === '123456')->once()->andReturn(true);
});
$this->post(route('two-factor.confirm'), ['code' => '000000'])
->assertSessionHasErrors('code', errorBag: 'confirmTwoFactorAuthentication');
$this->assertFalse($user->refresh()->hasEnabledTwoFactorAuthentication());
$this->post(route('two-factor.confirm'), ['code' => '123456'])->assertSessionHasNoErrors();
$this->assertTrue($user->refresh()->hasEnabledTwoFactorAuthentication());
}
public function test_recovery_codes_can_be_retrieved_regenerated_and_removed_with_two_factor(): void
{
$user = User::factory()->withTwoFactor()->create();
$this->actingAs($user)->withSession(['auth.password_confirmed_at' => time()]);
$oldCodes = $this->getJson(route('two-factor.recovery-codes'))->assertOk()->json();
$this->assertSame($user->recoveryCodes(), $oldCodes);
$this->post(route('two-factor.regenerate-recovery-codes'))->assertSessionHasNoErrors();
$newCodes = $this->getJson(route('two-factor.recovery-codes'))->assertOk()->json();
$this->assertCount(8, $newCodes);
$this->assertEmpty(array_intersect($oldCodes, $newCodes));
$this->delete(route('two-factor.disable'))->assertSessionHasNoErrors();
$this->assertNull($user->refresh()->two_factor_secret);
$this->assertNull($user->two_factor_recovery_codes);
$this->assertFalse($user->hasEnabledTwoFactorAuthentication());
}
public function test_sensitive_two_factor_endpoints_reject_expired_password_confirmation(): void
{
$user = User::factory()->withTwoFactor()->create();
$this->actingAs($user);
foreach (['two-factor.qr-code', 'two-factor.secret-key', 'two-factor.recovery-codes'] as $route) {
$this->getJson(route($route))->assertStatus(423);
}
$this->deleteJson(route('two-factor.disable'))->assertStatus(423);
$this->postJson(route('two-factor.regenerate-recovery-codes'))->assertStatus(423);
$this->assertTrue($user->refresh()->hasEnabledTwoFactorAuthentication());
}
} }
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Tests\Feature\Settings;
use Symfony\Component\Process\Process;
use Tests\TestCase;
class SecurityUiTest extends TestCase
{
public function test_security_and_application_key_rendering(): void
{
$process = new Process(['node', 'tests/Fixtures/security.mjs'], base_path());
$process->setTimeout(60);
$process->run();
$this->assertTrue($process->isSuccessful(), $process->getOutput().$process->getErrorOutput());
$this->assertStringContainsString('Security UI rendering checks passed.', $process->getOutput());
}
}
+25 -1
View File
@@ -25,7 +25,9 @@ class UserApplicationTest extends TestCase
->assertInertia(fn (Assert $page) => $page ->assertInertia(fn (Assert $page) => $page
->component('settings/Applications') ->component('settings/Applications')
->where('applications.0.name', 'Claude Desktop') ->where('applications.0.name', 'Claude Desktop')
->where('applicationKey', null), ->where('applicationKey', null)
->missing('applications.0.key_hash')
->missing('applications.0.plain_text_key'),
); );
} }
@@ -100,4 +102,26 @@ class UserApplicationTest extends TestCase
'id' => $application->id, 'id' => $application->id,
]); ]);
} }
public function test_application_list_only_contains_the_current_users_keys(): void
{
$user = User::factory()->create();
UserApplication::factory()->for($user)->create(['name' => 'Own tool']);
UserApplication::factory()->create(['name' => 'Foreign tool']);
$this->actingAs($user)->get(route('applications.edit'))
->assertInertia(fn (Assert $page) => $page
->has('applications', 1)
->where('applications.0.name', 'Own tool')
->where('applicationKey', null));
}
public function test_invalid_application_name_does_not_issue_a_key(): void
{
$user = User::factory()->create();
$this->actingAs($user)->from(route('applications.edit'))
->post(route('applications.store'), ['name' => ''])
->assertSessionHasErrors('name')
->assertSessionMissing('applicationKey');
$this->assertDatabaseCount('user_applications', 0);
}
} }
+316
View File
@@ -0,0 +1,316 @@
import assert from 'node:assert/strict';
import process from 'node:process';
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? 'playwright'
);
const browser = await chromium.launch({ channel: 'chrome', headless: true });
const base = 'http://127.0.0.1:4185';
const context = await browser.newContext({
viewport: { width: 1440, height: 1000 },
permissions: ['clipboard-read', 'clipboard-write'],
});
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
page.on('dialog', (dialog) => dialog.accept());
const result = (value) =>
context.addCookies([{ name: 'security_test_result', value, url: base }]);
const enabled = (value) =>
context.addCookies([
{ name: 'security_enabled', value: String(value), url: base },
]);
const button = (name) => page.getByRole('button', { name, exact: true });
const dialog = () => page.getByRole('dialog');
let recoveryFetches = 0;
page.on('request', (request) => {
if (
request.url().endsWith('/user/two-factor-recovery-codes') &&
request.method() === 'GET'
) {
recoveryFetches++;
}
});
try {
for (const width of [1440, 390, 320]) {
await page.setViewportSize({ width, height: 1000 });
for (const theme of ['light', 'dark']) {
await page.emulateMedia({ colorScheme: theme });
for (const path of ['security', 'applications']) {
await page.goto(`${base}/settings/${path}`);
await page
.getByRole('heading', {
name:
path === 'security'
? 'Update password'
: 'Applications',
exact: true,
})
.waitFor();
assert.equal(
await page.evaluate(
() =>
document.documentElement.scrollWidth <=
window.innerWidth,
),
true,
`${path} overflow at ${width}/${theme}`,
);
assert.equal(
await page
.locator('html')
.evaluate((el) => el.classList.contains('dark')),
theme === 'dark',
);
assert.ok(
(await page.locator('section').first().boundingBox())
.width <= width,
`${path} content is clipped at ${width}/${theme}`,
);
}
await page.goto(`${base}/settings/security`);
await button('Enable 2FA').click();
await page.getByLabel('Manual setup key').waitFor();
assert.equal(
await page.getByLabel('Manual setup key').inputValue(),
'MANUALSETUPTESTKEY',
);
assert.equal(
await dialog().evaluate(
(el) => el.scrollWidth <= el.clientWidth,
),
true,
);
await button('Continue').click();
const code = page.getByLabel('Authentication code', {
exact: true,
});
await code.waitFor();
assert.equal(await code.getAttribute('inputmode'), 'numeric');
assert.equal(
await code.getAttribute('autocomplete'),
'one-time-code',
);
await code.focus();
await page.keyboard.press('Tab');
assert.equal(
await button('Back').evaluate(
(el) => el === document.activeElement,
),
true,
);
await page.keyboard.press('Escape');
await dialog().waitFor({ state: 'hidden' });
assert.equal(await page.getByLabel('Manual setup key').count(), 0);
assert.match(
await page.locator('body').innerText(),
/Awaiting confirmation/,
);
}
}
await page.setViewportSize({ width: 390, height: 1000 });
await button('Continue setup').click();
await button('Continue').click();
await result('validation');
await page
.getByLabel('Authentication code', { exact: true })
.fill('000000');
await button('Confirm').click();
await page
.getByText('The provided two factor authentication code was invalid.', {
exact: true,
})
.waitFor();
assert.equal(
await page
.getByLabel('Authentication code', { exact: true })
.getAttribute('aria-invalid'),
'true',
);
assert.equal(
await page
.getByLabel('Authentication code', { exact: true })
.inputValue(),
'',
);
await result('success');
await page
.getByLabel('Authentication code', { exact: true })
.fill('123456');
await button('Confirm').click();
await dialog().waitFor({ state: 'hidden' });
await button('Disable 2FA').waitFor();
assert.equal(
recoveryFetches,
0,
'Recovery codes are fetched only on request',
);
await button('View recovery codes').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
await button('Hide recovery codes').click();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
0,
);
await button('View recovery codes').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
assert.equal(recoveryFetches, 2);
await button('Regenerate codes').click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
1,
);
await button('Regenerate codes').click();
await dialog()
.getByRole('button', { name: 'Regenerate codes', exact: true })
.click();
await dialog().waitFor({ state: 'hidden' });
await page.getByText('old-code-0001', { exact: true }).waitFor();
assert.equal(recoveryFetches, 3);
await button('Hide recovery codes').click();
await page.route('**/user/two-factor-recovery-codes', async (route) => {
if (route.request().method() === 'GET') {
await new Promise((resolve) => setTimeout(resolve, 350));
await route.fulfill({ json: ['late-secret-code'] });
} else {
await route.continue();
}
});
await button('View recovery codes').click();
await button('Hide recovery codes').click();
await page.waitForTimeout(450);
assert.equal(
await page.getByText('late-secret-code', { exact: true }).count(),
0,
);
await page.unroute('**/user/two-factor-recovery-codes');
await page.route('**/user/two-factor-recovery-codes', (route) =>
route.fulfill({ status: 423, json: {} }),
);
await button('View recovery codes').click();
await page
.getByText(
'Your session or password confirmation has expired. Reload this page and confirm your password to continue.',
{ exact: true },
)
.waitFor();
await page.unroute('**/user/two-factor-recovery-codes');
await button('Try again').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
await button('Disable 2FA').click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await button('Disable 2FA').click();
await dialog()
.getByRole('button', { name: 'Disable 2FA', exact: true })
.click();
await dialog().waitFor({ state: 'hidden' });
await button('Enable 2FA').waitFor();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
0,
);
await page.route('**/user/two-factor-secret-key', (route) => route.abort());
await button('Enable 2FA').click();
await page
.getByText(
'Authenticator setup could not be loaded. Please try again.',
{ exact: true },
)
.waitFor();
assert.equal(await button('Continue').count(), 0);
await page.unroute('**/user/two-factor-secret-key');
await button('Try again').click();
await page.getByLabel('Manual setup key').waitFor();
await page.locator('[data-slot="dialog-close"]').click();
await dialog().waitFor({ state: 'hidden' });
await page.getByLabel('Current password', { exact: true }).fill('wrong');
await page.getByLabel('New password', { exact: true }).fill('new-password');
await page
.getByLabel('Confirm password', { exact: true })
.fill('new-password');
await result('validation');
await button('Save password').click();
await page
.getByText('The password is incorrect.', { exact: true })
.waitFor();
assert.equal(
await page.getByLabel('Current password', { exact: true }).inputValue(),
'',
);
assert.equal(
await page.getByLabel('New password', { exact: true }).inputValue(),
'',
);
assert.equal(
await page
.getByLabel('Current password', { exact: true })
.getAttribute('aria-invalid'),
'true',
);
assert.doesNotMatch(
await page.evaluate(() => JSON.stringify(history.state)),
/MANUALSETUPTESTKEY|123456|new-password/,
);
await result('success');
await page.goto(`${base}/settings/applications`);
assert.equal(await button('Copy key').count(), 0);
await page.getByLabel('Application name').fill('My tool');
await page.route('**/settings/applications', (route) =>
route.request().method() === 'POST' ? route.abort() : route.continue(),
);
await button('Create application').click();
await page.locator('[data-form-state="network"]').waitFor();
assert.equal(
await page.getByLabel('Application name').inputValue(),
'My tool',
);
await page.unroute('**/settings/applications');
await button('Try again').click();
await page.getByLabel('API key', { exact: true }).waitFor();
assert.ok(
(await page.locator('section').first().boundingBox()).width <= 390,
'One-time key content is clipped on mobile',
);
await button('Copy key').click();
assert.equal(
await page.evaluate(() => navigator.clipboard.readText()),
'kg_app_one_time_test_key',
);
await page.reload();
assert.equal(await button('Copy key').count(), 0);
assert.equal(await page.getByLabel('API key', { exact: true }).count(), 0);
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await result('expired');
await dialog().getByRole('button', { name: 'Delete', exact: true }).click();
await dialog()
.getByText('Your session has expired', { exact: true })
.waitFor();
assert.equal(
await page.locator('button[aria-label="Delete Desktop tool"]').count(),
1,
);
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await result('success');
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await dialog().getByRole('button', { name: 'Delete', exact: true }).click();
await page
.getByText('No applications have been created yet.', { exact: true })
.waitFor();
assert.deepEqual(errors, []);
console.log(
'Security browser behavior checks passed: 2FA setup, confirmation, cancellation, recovery hiding and regeneration, late responses, errors, password reset, one-time key copy, deletion, keyboard, mobile and both themes.',
);
} finally {
await browser.close();
}
+17
View File
@@ -0,0 +1,17 @@
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import '../../resources/css/app.css';
import Security from '../../resources/js/pages/settings/Security.vue';
import Applications from '../../resources/js/pages/settings/Applications.vue';
import { createAppearance } from '../../resources/js/composables/useAppearance';
import { createLocalization } from '../../resources/js/lib/localization';
createInertiaApp({
resolve: (name) => (name === 'Security' ? Security : Applications),
setup: ({ el, App, props, plugin }) =>
createApp({ render: () => h(App, props) })
.use(plugin)
.use(createLocalization())
.use(createAppearance())
.mount(el),
});
+238
View File
@@ -0,0 +1,238 @@
import assert from 'node:assert/strict';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import vue from '@vitejs/plugin-vue';
import tailwind from '@tailwindcss/vite';
import { createServer } from 'vite';
import { createSSRApp, h } from 'vue';
import { renderToString } from 'vue/server-renderer';
import { createInertiaApp } from '@inertiajs/vue3';
const serve = process.argv.includes('--serve');
const server = await createServer({
configFile: false,
cacheDir: 'node_modules/.vite/security-fixture',
plugins: [vue(), ...(serve ? [tailwind()] : [])],
resolve: {
alias: {
'@': fileURLToPath(new URL('../../resources/js', import.meta.url)),
},
},
server: serve
? { host: '127.0.0.1', port: 4185, strictPort: true, hmr: false }
: { middlewareMode: true, hmr: false, watch: null },
appType: 'custom',
});
const application = {
id: 1,
name: 'Desktop tool',
created_at: '2026-09-14T00:00:00Z',
last_used_at: null,
};
const key = 'kg_app_one_time_test_key';
function makePage(url, extra = {}) {
return {
component: url.startsWith('/settings/security')
? 'Security'
: 'Applications',
url,
version: null,
clearHistory: false,
encryptHistory: false,
props: {
name: 'KanbanGit',
errors: {},
sidebarOpen: true,
appearance: 'system',
canManageTwoFactor: true,
requiresConfirmation: true,
twoFactorEnabled: false,
applications: [application],
applicationKey: null,
auth: {
user: {
id: 1,
name: 'Alex Morgan',
email: 'alex@example.test',
avatar: null,
avatar_color: '#10B981',
avatar_is_generated: true,
},
permissions: {
globalAdmin: false,
projectCreate: false,
canManageTeams: false,
},
},
navigation: { project: null },
...extra,
},
};
}
if (serve) {
server.middlewares.use(async (request, response, next) => {
const path = new URL(request.url, 'http://localhost').pathname;
if (!path.startsWith('/settings') && !path.startsWith('/user/')) {
return next();
}
const result =
request.headers.cookie?.match(/security_test_result=(\w+)/)?.[1] ??
'success';
const mutation = request.method !== 'GET';
if (mutation && ['server', 'expired'].includes(result)) {
response.statusCode = result === 'expired' ? 419 : 503;
response.end('Simulated failure');
return;
}
let body = '';
if (mutation) {
for await (const chunk of request) {
body += chunk;
}
}
const submitted = body ? JSON.parse(body) : {};
const cookies = request.headers.cookie ?? '';
let enabled = cookies.includes('security_enabled=true');
let extra = { twoFactorEnabled: enabled };
let url = path;
if (path.startsWith('/user/two-factor-') && !mutation) {
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify(
path.endsWith('qr-code')
? {
svg: '<svg viewBox="0 0 100 100"><rect width="100" height="100" fill="black"/></svg>',
}
: path.endsWith('secret-key')
? { secretKey: 'MANUALSETUPTESTKEY' }
: ['old-code-0001', 'old-code-0002'],
),
);
return;
}
if (mutation) {
url = path.startsWith('/settings/applications')
? '/settings/applications'
: '/settings/security';
if (result === 'validation') {
extra.errors = path.includes('confirmed-two-factor')
? {
confirmTwoFactorAuthentication: {
code: 'The provided two factor authentication code was invalid.',
},
}
: path.includes('applications')
? { name: 'The name field is required.' }
: { current_password: 'The password is incorrect.' };
} else if (path.includes('confirmed-two-factor')) {
enabled = true;
response.setHeader(
'Set-Cookie',
'security_enabled=true; Path=/',
);
} else if (
path === '/user/two-factor-authentication' &&
request.method === 'DELETE'
) {
enabled = false;
response.setHeader(
'Set-Cookie',
'security_enabled=false; Path=/',
);
} else if (
path === '/settings/applications' &&
request.method === 'POST'
) {
extra.applicationKey = key;
extra.applications = [{ ...application, name: submitted.name }];
} else if (
path.startsWith('/settings/applications/') &&
request.method === 'DELETE'
) {
extra.applications = [];
}
extra.twoFactorEnabled = enabled;
}
const page = makePage(url, extra);
response.setHeader('Vary', 'X-Inertia');
if (request.headers['x-inertia']) {
response.setHeader('X-Inertia', 'true');
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(page));
return;
}
const escaped = JSON.stringify(page)
.replaceAll('&', '&amp;')
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;');
response.setHeader('Content-Type', 'text/html');
response.end(
await server.transformIndexHtml(
request.url,
'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div id="app" data-page="' +
escaped +
'"></div><script type="module" src="/tests/Fixtures/security-preview.mjs"></script></body></html>',
),
);
});
await server.listen();
console.log('Security fixture ready.');
} else {
try {
const { createLocalization } = await server.ssrLoadModule(
'/resources/js/lib/localization.ts',
);
const { createAppearance } = await server.ssrLoadModule(
'/resources/js/composables/useAppearance.ts',
);
const Security = (
await server.ssrLoadModule(
'/resources/js/pages/settings/Security.vue',
)
).default;
const Applications = (
await server.ssrLoadModule(
'/resources/js/pages/settings/Applications.vue',
)
).default;
const render = async (url, component, extra = {}) =>
(
await createInertiaApp({
page: makePage(url, extra),
resolve: () => component,
render: renderToString,
setup: ({ App, props, plugin }) =>
createSSRApp({ render: () => h(App, props) })
.use(plugin)
.use(createLocalization())
.use(createAppearance()),
})
).body;
const security = await render('/settings/security', Security);
assert.match(security, /autocomplete="current-password"/);
assert.match(security, /Enable 2FA/);
assert.doesNotMatch(
await render('/settings/security', Security, {
canManageTwoFactor: false,
}),
/Enable 2FA/,
);
const enabled = await render('/settings/security', Security, {
twoFactorEnabled: true,
});
assert.match(enabled, /View recovery codes/);
assert.doesNotMatch(enabled, /old-code/);
const hidden = await render('/settings/applications', Applications);
assert.doesNotMatch(hidden, /id="application-key"/);
assert.doesNotMatch(hidden, /Copy key/);
const shown = await render('/settings/applications', Applications, {
applicationKey: key,
});
assert.match(shown, /id="application-key"/);
assert.match(shown, /Copy key/);
assert.match(shown, /kg_app_one_time_test_key/);
console.log('Security UI rendering checks passed.');
} finally {
await server.close();
}
}