- {{
- mustChangePassword
- ? 'You must change your password before continuing anywhere else in the app.'
- : status
- }}
-
-
-
-
-
-
-
- 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.
+
+
+
+ {{ t('security.passwordTitle') }}
+
+
+ {{ t('security.passwordDescription') }}
-
-
-
-
-
-
- You will be prompted for a secure, random pin during
- login, which you can retrieve from the TOTP-supported
- application on your phone.
-
-
-
-
+
+
+
+
+
+
+
+
+
+ {{
+ t('security.twoFactorTitle')
+ }}
+
+ {{
+ t(
+ props.twoFactorEnabled
+ ? 'security.enabled'
+ : setupStarted
+ ? 'security.pending'
+ : 'security.disabled',
+ )
+ }}
-
-
-
-
-
-
+
+ {{
+ t(
+ props.twoFactorEnabled
+ ? 'security.enabledDescription'
+ : 'security.twoFactorDescription',
+ )
+ }}
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Feature/Settings/GitConnectionTest.php b/tests/Feature/Settings/GitConnectionTest.php
index c1c051d..34af7c9 100644
--- a/tests/Feature/Settings/GitConnectionTest.php
+++ b/tests/Feature/Settings/GitConnectionTest.php
@@ -25,11 +25,15 @@ class GitConnectionTest extends TestCase
'base_url' => 'https://git.example.test',
]);
+ UserGitConnection::factory()->create();
+
$this->actingAs($user)
->get(route('git-connections.edit'))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('settings/GitConnections')
+ ->has('gitConnections', 1)
+ ->missing('gitConnections.0.api_token')
->where('gitConnections.0.account_login', 'nico')
->where('gitConnections.0.base_url', 'https://git.example.test')
->where('gitConnections.0.provider', GitProviderKey::Gitea->value),
@@ -93,7 +97,8 @@ class GitConnectionTest extends TestCase
'api_token' => 'wrong-token',
])
->assertRedirect(route('git-connections.edit'))
- ->assertSessionHasErrors('api_token');
+ ->assertSessionHasErrors('api_token')
+ ->assertSessionMissing('_old_input.api_token');
}
/**
@@ -181,4 +186,59 @@ class GitConnectionTest extends TestCase
'id' => $gitConnection->id,
]);
}
+
+ public function test_empty_personal_connections_are_displayed(): void
+ {
+ UserGitConnection::factory()->create();
+
+ $this->actingAs(User::factory()->create())
+ ->get(route('git-connections.edit'))
+ ->assertOk()
+ ->assertInertia(fn (Assert $page) => $page
+ ->component('settings/GitConnections')
+ ->where('gitConnections', []),
+ );
+ }
+
+ public function test_guests_cannot_access_git_connections(): void
+ {
+ $this->get(route('git-connections.edit'))->assertRedirect(route('login'));
+ }
+
+ public function test_users_cannot_delete_foreign_connections(): void
+ {
+ $connection = UserGitConnection::factory()->create();
+
+ $this->actingAs(User::factory()->create())
+ ->delete(route('git-connections.destroy', $connection))
+ ->assertForbidden();
+
+ $this->assertModelExists($connection);
+ }
+
+ public function test_failed_provider_update_preserves_connection_and_does_not_flash_token(): void
+ {
+ Http::preventStrayRequests();
+ Http::fake(['https://git.changed.test/api/v1/user' => Http::response([], 503)]);
+ $user = User::factory()->create();
+ $connection = UserGitConnection::factory()->for($user)->create([
+ 'base_url' => 'https://git.original.test',
+ 'api_token' => 'original-secret',
+ ]);
+ $original = $connection->fresh()->getAttributes();
+
+ $this->actingAs($user)
+ ->from(route('git-connections.edit'))
+ ->patch(route('git-connections.update', $connection), [
+ 'provider' => 'gitea',
+ 'base_url' => 'https://git.changed.test',
+ 'api_token' => 'replacement-secret',
+ ])
+ ->assertRedirect(route('git-connections.edit'))
+ ->assertSessionHasErrors('api_token')
+ ->assertSessionMissing('_old_input.api_token');
+
+ $this->assertSame($original, $connection->fresh()->getAttributes());
+ $this->assertSame('original-secret', $connection->fresh()->api_token);
+ }
}
diff --git a/tests/Feature/Settings/GitConnectionsUiTest.php b/tests/Feature/Settings/GitConnectionsUiTest.php
new file mode 100644
index 0000000..4ff1fcd
--- /dev/null
+++ b/tests/Feature/Settings/GitConnectionsUiTest.php
@@ -0,0 +1,18 @@
+setTimeout(60);
+ $process->run();
+ $this->assertTrue($process->isSuccessful(), $process->getOutput().$process->getErrorOutput());
+ $this->assertStringContainsString('Git connections rendering checks passed.', $process->getOutput());
+ }
+}
diff --git a/tests/Feature/Settings/SecurityTest.php b/tests/Feature/Settings/SecurityTest.php
index 50816ea..386d679 100644
--- a/tests/Feature/Settings/SecurityTest.php
+++ b/tests/Feature/Settings/SecurityTest.php
@@ -6,6 +6,7 @@ use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Inertia\Testing\AssertableInertia as Assert;
+use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
use Laravel\Fortify\Features;
use Tests\TestCase;
@@ -249,4 +250,55 @@ class SecurityTest extends TestCase
$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());
+ }
}
diff --git a/tests/Feature/Settings/SecurityUiTest.php b/tests/Feature/Settings/SecurityUiTest.php
new file mode 100644
index 0000000..4681b6a
--- /dev/null
+++ b/tests/Feature/Settings/SecurityUiTest.php
@@ -0,0 +1,18 @@
+setTimeout(60);
+ $process->run();
+ $this->assertTrue($process->isSuccessful(), $process->getOutput().$process->getErrorOutput());
+ $this->assertStringContainsString('Security UI rendering checks passed.', $process->getOutput());
+ }
+}
diff --git a/tests/Feature/Settings/UserApplicationTest.php b/tests/Feature/Settings/UserApplicationTest.php
index d80c6b3..111e56c 100644
--- a/tests/Feature/Settings/UserApplicationTest.php
+++ b/tests/Feature/Settings/UserApplicationTest.php
@@ -25,7 +25,9 @@ class UserApplicationTest extends TestCase
->assertInertia(fn (Assert $page) => $page
->component('settings/Applications')
->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,
]);
}
+
+ 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);
+ }
}
diff --git a/tests/Fixtures/git-connections-browser.mjs b/tests/Fixtures/git-connections-browser.mjs
new file mode 100644
index 0000000..adef9f0
--- /dev/null
+++ b/tests/Fixtures/git-connections-browser.mjs
@@ -0,0 +1,242 @@
+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:4186';
+const context = await browser.newContext({
+ viewport: { width: 1440, height: 1000 },
+});
+const page = await context.newPage();
+page.setDefaultTimeout(10000);
+const errors = [];
+page.on('pageerror', (error) => errors.push(error.message));
+const dialog = () => page.getByRole('dialog');
+const button = (name) => dialog().getByRole('button', { name, exact: true });
+const state = (value) =>
+ dialog()
+ .locator(`[data-form-state="${value}"]`)
+ .waitFor({ state: 'visible' });
+const setResult = (value) =>
+ context.addCookies([{ name: 'git_test_result', value, url: base }]);
+const add = () =>
+ page.getByRole('button', { name: 'Add connection', exact: true }).click();
+const edit = () =>
+ page
+ .getByRole('button', {
+ name: 'Edit alex at https://git.example.test',
+ exact: true,
+ })
+ .click();
+const visit = async (query = '?reset') => {
+ await page.goto(`${base}/settings/git-connections${query}`);
+ await page
+ .getByRole('heading', { name: 'Git connections', exact: true })
+ .waitFor();
+};
+const noOverflow = async () =>
+ assert.equal(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth,
+ ),
+ true,
+ );
+const fill = async (token = 'test-secret') => {
+ await dialog()
+ .getByLabel('Gitea base URL', { exact: true })
+ .fill('https://git.example.test');
+ await page.locator('#git-token').fill(token);
+};
+const closed = () => dialog().waitFor({ state: 'hidden' });
+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 });
+ await visit();
+ await noOverflow();
+ assert.equal(
+ await page
+ .locator('[data-slot="card"]')
+ .first()
+ .evaluate(
+ (element) =>
+ element.getBoundingClientRect().right <=
+ window.innerWidth,
+ ),
+ true,
+ `Connection list clips at ${width}px in ${theme}`,
+ );
+ if (width === 390) {
+ await page.screenshot({
+ path: `/private/tmp/KAN-38-${theme}-list.png`,
+ fullPage: true,
+ });
+ }
+ await add();
+ await dialog().waitFor();
+ await noOverflow();
+ assert.equal(
+ await page.locator('#git-token').getAttribute('type'),
+ 'password',
+ );
+ assert.equal(
+ await page.locator('#git-token').getAttribute('autocomplete'),
+ 'new-password',
+ );
+ await page.keyboard.press('Tab');
+ assert.equal(
+ await dialog().evaluate((element) =>
+ element.contains(document.activeElement),
+ ),
+ true,
+ );
+ await dialog().evaluate((element) =>
+ Promise.all(
+ element
+ .getAnimations()
+ .map((animation) => animation.finished),
+ ),
+ );
+ if (width === 390) {
+ await page.screenshot({
+ path: `/private/tmp/KAN-38-${theme}-dialog.png`,
+ fullPage: true,
+ });
+ }
+ await page.keyboard.press('Escape');
+ await closed();
+ assert.equal(
+ await page
+ .getByRole('button', {
+ name: 'Add connection',
+ exact: true,
+ })
+ .evaluate((element) => document.activeElement === element),
+ true,
+ );
+ await edit();
+ assert.equal(
+ await page.locator('#git-base-url').inputValue(),
+ 'https://git.example.test',
+ );
+ assert.equal(await page.locator('#git-token').inputValue(), '');
+ await noOverflow();
+ await button('Cancel').click();
+ await closed();
+ }
+ }
+ await visit('?empty');
+ await page.getByText('No Git connections yet', { exact: true }).waitFor();
+ await add();
+ await fill();
+ await setResult('validation');
+ await button('Add connection').click();
+ await state('validation');
+ assert.equal(
+ await page.locator('#git-token').getAttribute('aria-invalid'),
+ 'true',
+ );
+ assert.equal(await page.locator('#git-token').inputValue(), 'test-secret');
+ await page
+ .getByText(
+ 'Gitea could not authenticate with this base URL and token.',
+ { exact: true },
+ )
+ .waitFor();
+ assert.doesNotMatch(
+ await page.evaluate(() => JSON.stringify(history.state)),
+ /test-secret/,
+ );
+ await page.route('**/settings/git-connections', (route) =>
+ route.abort('failed'),
+ );
+ await button('Add connection').click();
+ await state('network');
+ await page.unroute('**/settings/git-connections');
+ await setResult('server');
+ await button('Try again').click();
+ await state('server');
+ assert.equal(await page.locator('#git-token').inputValue(), 'test-secret');
+ await setResult('success');
+ const submitted = page.waitForRequest(
+ (request) =>
+ request.method() === 'POST' &&
+ request.url().endsWith('/settings/git-connections'),
+ );
+ await button('Try again').click();
+ assert.deepEqual((await submitted).postDataJSON(), {
+ provider: 'gitea',
+ base_url: 'https://git.example.test',
+ api_token: 'test-secret',
+ });
+ await closed();
+ await page.getByText('Git connection added.', { exact: true }).waitFor();
+ await add();
+ assert.equal(await page.locator('#git-token').inputValue(), '');
+ await button('Cancel').click();
+ await closed();
+
+ await visit();
+ await edit();
+ await page.locator('#git-token').fill('updated-secret');
+ const patch = page.waitForRequest(
+ (request) => request.method() === 'PATCH',
+ );
+ await button('Save changes').click();
+ assert.equal((await patch).postDataJSON().api_token, 'updated-secret');
+ await closed();
+ await page.getByText('Git connection updated.', { exact: true }).waitFor();
+ await edit();
+ assert.equal(await page.locator('#git-token').inputValue(), '');
+ await page.locator('#git-token').fill('discard-me');
+ page.once('dialog', (confirmation) => confirmation.dismiss());
+ await button('Cancel').click();
+ assert.equal(await dialog().isVisible(), true);
+ page.once('dialog', (confirmation) => confirmation.accept());
+ await button('Cancel').click();
+ await closed();
+ await edit();
+ assert.equal(await page.locator('#git-token').inputValue(), '');
+ await button('Cancel').click();
+ await closed();
+
+ await page
+ .getByRole('button', {
+ name: 'Remove alex at https://git.example.test',
+ exact: true,
+ })
+ .click();
+ await setResult('forbidden');
+ await button('Remove connection').click();
+ await state('server');
+ await page.getByText('Connection access denied', { exact: true }).waitFor();
+ assert.equal(await button('Try again').count(), 0);
+ await button('Cancel').click();
+ await closed();
+ await page
+ .getByRole('button', {
+ name: 'Remove alex at https://git.example.test',
+ exact: true,
+ })
+ .click();
+ await setResult('success');
+ const deletion = page.waitForRequest(
+ (request) => request.method() === 'DELETE',
+ );
+ await button('Remove connection').click();
+ assert.equal(
+ new URL((await deletion).url()).pathname,
+ '/settings/git-connections/1',
+ );
+ await closed();
+ await page.getByText('No Git connections yet', { exact: true }).waitFor();
+ assert.deepEqual(errors, []);
+ console.log(
+ 'Git connections browser checks passed: create, edit, remove, token privacy, provider errors, retries, permissions, discard, keyboard and both themes at 320/390/1440px.',
+ );
+} finally {
+ await browser.close();
+}
diff --git a/tests/Fixtures/git-connections-preview.mjs b/tests/Fixtures/git-connections-preview.mjs
new file mode 100644
index 0000000..b4d0c63
--- /dev/null
+++ b/tests/Fixtures/git-connections-preview.mjs
@@ -0,0 +1,16 @@
+import { createApp, h } from 'vue';
+import { createInertiaApp } from '@inertiajs/vue3';
+import '../../resources/css/app.css';
+import GitConnections from '../../resources/js/pages/settings/GitConnections.vue';
+import { createAppearance } from '../../resources/js/composables/useAppearance';
+import { createLocalization } from '../../resources/js/lib/localization';
+
+createInertiaApp({
+ resolve: () => GitConnections,
+ setup: ({ el, App, props, plugin }) =>
+ createApp({ render: () => h(App, props) })
+ .use(plugin)
+ .use(createLocalization())
+ .use(createAppearance())
+ .mount(el),
+});
diff --git a/tests/Fixtures/git-connections.mjs b/tests/Fixtures/git-connections.mjs
new file mode 100644
index 0000000..39ec4a4
--- /dev/null
+++ b/tests/Fixtures/git-connections.mjs
@@ -0,0 +1,210 @@
+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/git-connections-fixture',
+ plugins: [vue(), ...(serve ? [tailwind()] : [])],
+ resolve: {
+ alias: {
+ '@': fileURLToPath(new URL('../../resources/js', import.meta.url)),
+ },
+ },
+ server: serve
+ ? { host: '127.0.0.1', port: 4186, strictPort: true, hmr: false }
+ : { middlewareMode: true, hmr: false, watch: null },
+ appType: 'custom',
+});
+const connection = {
+ id: 1,
+ user_id: 1,
+ provider: 'gitea',
+ provider_label: 'Gitea',
+ base_url: 'https://git.example.test',
+ provider_user_id: '42',
+ account_login: 'alex',
+ account_name: 'Alex Morgan',
+ created_at: null,
+ updated_at: null,
+};
+function makePage(extra = {}) {
+ return {
+ component: 'GitConnections',
+ url: '/settings/git-connections',
+ version: null,
+ clearHistory: false,
+ encryptHistory: false,
+ props: {
+ name: 'KanbanGit',
+ errors: {},
+ sidebarOpen: true,
+ appearance: 'system',
+ status: null,
+ gitConnections: [connection],
+ 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) {
+ let connections = [connection];
+ server.middlewares.use(async (request, response, next) => {
+ if (!request.url.startsWith('/settings')) {
+ return next();
+ }
+ const url = new URL(request.url, 'http://localhost');
+ const mutation = request.method !== 'GET';
+ const result =
+ request.headers.cookie?.match(/git_test_result=(\w+)/)?.[1] ??
+ 'success';
+ let extra = {};
+ if (!mutation && url.searchParams.has('reset')) {
+ connections = [connection];
+ }
+ if (mutation && ['server', 'forbidden'].includes(result)) {
+ response.statusCode = result === 'forbidden' ? 403 : 503;
+ response.end('Simulated request failure');
+ return;
+ }
+ if (mutation) {
+ let body = '';
+ for await (const chunk of request) {
+ body += chunk;
+ }
+ const data = body ? JSON.parse(body) : {};
+ if (result === 'validation') {
+ extra.errors = {
+ api_token:
+ 'Gitea could not authenticate with this base URL and token.',
+ };
+ } else if (request.method === 'DELETE') {
+ connections = connections.filter(
+ (item) =>
+ item.id !== Number(url.pathname.split('/').at(-1)),
+ );
+ extra.status = 'alex @ https://git.example.test was removed.';
+ } else if (request.method === 'PATCH') {
+ connections = connections.map((item) =>
+ item.id === Number(url.pathname.split('/').at(-1))
+ ? { ...item, base_url: data.base_url }
+ : item,
+ );
+ extra.status = 'Git connection was updated.';
+ } else {
+ connections.push({
+ ...connection,
+ id: 2,
+ account_login: 'new-account',
+ base_url: data.base_url,
+ });
+ extra.status = 'Git connection was added.';
+ }
+ }
+ const page = makePage({
+ gitConnections: url.searchParams.has('empty') ? [] : connections,
+ ...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('&', '&')
+ .replaceAll('"', '"')
+ .replaceAll('<', '<');
+ response.setHeader('Content-Type', 'text/html');
+ response.end(
+ await server.transformIndexHtml(
+ request.url,
+ '
',
+ ),
+ );
+ });
+ await server.listen();
+ console.log('Git connections 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 { en } = await server.ssrLoadModule(
+ '/resources/js/locales/en.ts',
+ );
+ const component = (
+ await server.ssrLoadModule(
+ '/resources/js/pages/settings/GitConnections.vue',
+ )
+ ).default;
+ const render = async (extra = {}, locale = createLocalization()) =>
+ (
+ await createInertiaApp({
+ page: makePage(extra),
+ resolve: () => component,
+ render: renderToString,
+ setup: ({ App, props, plugin }) =>
+ createSSRApp({ render: () => h(App, props) })
+ .use(plugin)
+ .use(locale)
+ .use(createAppearance()),
+ })
+ ).body;
+ const html = await render();
+ assert.match(html, /Gitea/);
+ assert.match(html, /https:\/\/git.example.test/);
+ assert.match(html, /Edit alex at https:\/\/git.example.test/);
+ assert.doesNotMatch(html, /name="api_token"/);
+ assert.match(
+ await render({ gitConnections: [] }),
+ /No Git connections yet/,
+ );
+ assert.match(
+ await render(
+ {},
+ createLocalization(
+ { locale: 'de' },
+ {
+ de: {
+ ...en,
+ 'gitConnections.add': 'Verbindung hinzufügen',
+ },
+ },
+ ),
+ ),
+ /Verbindung hinzufügen/,
+ );
+ console.log('Git connections rendering checks passed.');
+ } finally {
+ await server.close();
+ }
+}
diff --git a/tests/Fixtures/security-browser.mjs b/tests/Fixtures/security-browser.mjs
new file mode 100644
index 0000000..28b3c1b
--- /dev/null
+++ b/tests/Fixtures/security-browser.mjs
@@ -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();
+}
diff --git a/tests/Fixtures/security-preview.mjs b/tests/Fixtures/security-preview.mjs
new file mode 100644
index 0000000..194ddd1
--- /dev/null
+++ b/tests/Fixtures/security-preview.mjs
@@ -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),
+});
diff --git a/tests/Fixtures/security.mjs b/tests/Fixtures/security.mjs
new file mode 100644
index 0000000..800c67f
--- /dev/null
+++ b/tests/Fixtures/security.mjs
@@ -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: '
',
+ }
+ : 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('&', '&')
+ .replaceAll('"', '"')
+ .replaceAll('<', '<');
+ response.setHeader('Content-Type', 'text/html');
+ response.end(
+ await server.transformIndexHtml(
+ request.url,
+ '
',
+ ),
+ );
+ });
+ 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();
+ }
+}