feat(password-generator): add secure password generator tool (#609)

* feat(password-generator): add secure password generator tool

Add a new password generator that creates random passwords locally using the browser cryptographic random source.
The tool supports configurable length and batch count, uppercase/lowercase letters, numbers, symbols, and custom characters, with an option to exclude visually similar characters.

Also add unit tests for the generation service, an e2e test for the page, and English and Chinese translations.

* fix(password-generator): use placeholder selector and press Enter in e2e test

Naive UI NInputNumber renders input[type=text] without role='spinbutton'
and n-form-item label is not linked via for/id. Use placeholder-based
selector and press Enter to trigger Vue reactive update.
This commit is contained in:
LuoXingchen authored and GitHub committed 2026-12-05 21:20:51 +01:00
1 parent e7540163c4
commit 0876ebba74
7 files changed
+316

No files matched your search

+17
View File
@@ -171,6 +171,23 @@ tools:
start: Start
stop: Stop
reset: Reset
password-generator:
title: Password generator
description: Generate secure random passwords locally with customizable character sets and length.
uppercase: Uppercase (ABC...)
lowercase: Lowercase (abc...)
numbers: Numbers (123...)
symbols: Symbols (!, #, $...)
length: Password length
count: Number of passwords to generate
excludeSimilar: Exclude similar characters (Il1O0o)
customCharacters: Additional characters
customCharactersPlaceholder: Add your own characters to the password alphabet
passwordPlaceholder: Your password...
copy: Copy
refresh: Generate new passwords
copied: Password copied to the clipboard
linkToPassphraseGenerator: Prefer memorable passwords? Try the passphrase generator
token-generator:
title: Token generator
description: Generate random string with the chars you want, uppercase or
+17
View File
@@ -155,6 +155,23 @@ tools:
start: 开始
stop: 停止
reset: 重置
password-generator:
title: 密码生成器
description: 在本地生成安全的随机密码,可自定义长度和字符集。
uppercase: 大写字母(ABC...)
lowercase: 小写字母(abc...)
numbers: 数字(123...)
symbols: 符号(!、#、$...)
length: 密码长度
count: 要生成的密码数量
excludeSimilar: 排除易混淆字符(Il1O0o)
customCharacters: 自定义附加字符
customCharactersPlaceholder: 添加要加入密码字符集的字符
passwordPlaceholder: 您的密码...
copy: 复制
refresh: 生成新密码
copied: 密码已复制到剪贴板
linkToPassphraseGenerator: 需要易记的密码?试试密码短语生成器
token-generator:
title: 令牌生成器
description: 生成包含您所需字符的随机字符串,包括大写或小写字母、数字和/或符号。
+13
View File
@@ -0,0 +1,13 @@
import { translate as t } from '@/plugins/i18n.plugin';
import { defineTool } from '../tool';
export const tool = defineTool({
name: t('tools.password-generator.title'),
path: '/password-generator',
description: t('tools.password-generator.description'),
keywords: ['password', 'generator', 'random', 'secure', 'uppercase', 'lowercase', 'numbers', 'symbols'],
component: () => import('./password-generator.vue'),
icon: defineAsyncComponent(() => import('@vicons/material/es/PasswordRound')),
createdAt: new Date('2026-12-03'),
category: 'Generators',
});
@@ -0,0 +1,22 @@
import { expect, test } from '@playwright/test';
test.describe('Tool - Password generator', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/password-generator');
});
test('Has correct title', async ({ page }) => {
await expect(page).toHaveTitle('Password generator - IT Tools');
});
test('Generates a password with the requested length', async ({ page }) => {
const password = page.locator('.password-display textarea');
await expect(password).toHaveValue(/^.{20}$/);
const lengthInput = page.getByPlaceholder('Please Input').first();
await lengthInput.fill('32');
await lengthInput.press('Enter');
await expect(password).toHaveValue(/^.{32}$/);
});
});
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest';
import { createPassword } from './password-generator.service';
describe('password-generator', () => {
it('uses the browser cryptographic random source', () => {
const spy = vi.spyOn(Math, 'random');
createPassword({ length: 64 });
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('generates a password of the requested length', () => {
expect(createPassword({ length: 64 })).toHaveLength(64);
});
it('includes every selected character type', () => {
const password = createPassword({ length: 64, excludeSimilar: false });
expect(password).toMatch(/[A-Z]/);
expect(password).toMatch(/[a-z]/);
expect(password).toMatch(/[0-9]/);
expect(password).toMatch(/[!@#$%^&*()\-_=+\[\]{};:,.<>?/]/);
});
it('excludes visually similar characters by default', () => {
const password = createPassword({ length: 512, customCharacters: 'Il1O0o' });
expect(password).not.toMatch(/[Il1O0o]/);
});
it('includes custom characters', () => {
const password = createPassword({
length: 4,
withUppercase: false,
withLowercase: false,
withNumbers: false,
withSymbols: false,
customCharacters: '甲乙丙丁',
});
expect(password).toMatch(/^[甲乙丙丁]{4}$/);
});
it('returns an empty string when no usable characters are selected', () => {
expect(
createPassword({
withUppercase: false,
withLowercase: false,
withNumbers: false,
withSymbols: false,
}),
).toBe('');
});
it('returns an empty string when the length cannot include every selected type', () => {
expect(createPassword({ length: 3 })).toBe('');
});
});
@@ -0,0 +1,54 @@
import { randFromArray, randIndex, shuffleArrayMutate } from '@/utils/random';
const CHARACTER_SETS = {
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
numbers: '0123456789',
symbols: '!@#$%^&*()-_=+[]{};:,.<>?/',
};
export function createPassword({
length = 20,
withUppercase = true,
withLowercase = true,
withNumbers = true,
withSymbols = true,
excludeSimilar = true,
customCharacters = '',
}: {
length?: number;
withUppercase?: boolean;
withLowercase?: boolean;
withNumbers?: boolean;
withSymbols?: boolean;
excludeSimilar?: boolean;
customCharacters?: string;
}) {
const excludedCharacters = excludeSimilar ? new Set('Il1O0o') : new Set<string>();
const characterSets = [
withUppercase ? CHARACTER_SETS.uppercase : '',
withLowercase ? CHARACTER_SETS.lowercase : '',
withNumbers ? CHARACTER_SETS.numbers : '',
withSymbols ? CHARACTER_SETS.symbols : '',
customCharacters,
]
.map((characters) =>
Array.from(new Set(Array.from(characters)))
.filter((character) => !excludedCharacters.has(character))
.join(''),
)
.filter(Boolean);
const passwordLength = Math.max(0, Math.floor(length));
if (!characterSets.length || passwordLength < characterSets.length) {
return '';
}
const alphabet = Array.from(new Set(characterSets.join('')));
const characters = characterSets.map((characters) => randFromArray(Array.from(characters)) as string);
characters.push(
...Array.from({ length: passwordLength - characters.length }, () => alphabet[randIndex(alphabet.length)]),
);
return shuffleArrayMutate(characters).join('');
}
@@ -0,0 +1,135 @@
<script setup lang="ts">
import { computedRefreshable } from '@/composable/computedRefreshable';
import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { createPassword } from './password-generator.service';
const { t } = useI18n();
const count = useQueryParamOrStorage({ name: 'count', storageName: 'password-generator:count', defaultValue: 1 });
const length = useQueryParamOrStorage({ name: 'length', storageName: 'password-generator:length', defaultValue: 20 });
const withUppercase = useQueryParamOrStorage({
name: 'uppercase',
storageName: 'password-generator:uppercase',
defaultValue: true,
});
const withLowercase = useQueryParamOrStorage({
name: 'lowercase',
storageName: 'password-generator:lowercase',
defaultValue: true,
});
const withNumbers = useQueryParamOrStorage({
name: 'numbers',
storageName: 'password-generator:numbers',
defaultValue: true,
});
const withSymbols = useQueryParamOrStorage({
name: 'symbols',
storageName: 'password-generator:symbols',
defaultValue: true,
});
const excludeSimilar = useQueryParamOrStorage({
name: 'exclude-similar',
storageName: 'password-generator:exclude-similar',
defaultValue: true,
});
const customCharacters = useQueryParamOrStorage({
name: 'custom',
storageName: 'password-generator:custom',
defaultValue: '',
});
const [passwords, refreshPasswords] = computedRefreshable(() =>
Array.from({ length: count.value < 1 ? 1 : count.value }, () =>
createPassword({
length: length.value,
withUppercase: withUppercase.value,
withLowercase: withLowercase.value,
withNumbers: withNumbers.value,
withSymbols: withSymbols.value,
excludeSimilar: excludeSimilar.value,
customCharacters: customCharacters.value,
}),
).join('\n'),
);
const { copy } = useCopy({ source: passwords, text: t('tools.password-generator.copied') });
</script>
<template>
<div>
<n-space justify="center" mb-3>
<c-link target="_blank" to="/passphrase-generator">
{{ t('tools.password-generator.linkToPassphraseGenerator') }}
</c-link>
</n-space>
<c-card>
<n-form label-placement="left" label-width="140">
<n-space justify="center">
<n-form-item :label="t('tools.password-generator.uppercase')">
<n-switch v-model:value="withUppercase" />
</n-form-item>
<n-form-item :label="t('tools.password-generator.lowercase')">
<n-switch v-model:value="withLowercase" />
</n-form-item>
<n-form-item :label="t('tools.password-generator.numbers')">
<n-switch v-model:value="withNumbers" />
</n-form-item>
<n-form-item :label="t('tools.password-generator.symbols')">
<n-switch v-model:value="withSymbols" />
</n-form-item>
</n-space>
</n-form>
<n-form-item :label="t('tools.password-generator.excludeSimilar')" label-placement="left">
<n-switch v-model:value="excludeSimilar" />
</n-form-item>
<n-form-item :label="t('tools.password-generator.customCharacters')" label-placement="top">
<c-input-text
v-model:value="customCharacters"
:placeholder="t('tools.password-generator.customCharactersPlaceholder')"
/>
</n-form-item>
<n-form-item :label="`${t('tools.password-generator.length')} (${length})`" label-placement="left">
<n-slider v-model:value="length" :step="1" :min="4" :max="128" mr-2 />
<n-input-number-i18n v-model:value="length" :min="4" :max="128" size="small" />
</n-form-item>
<n-form-item :label="t('tools.password-generator.count')" label-placement="left">
<n-slider v-model:value="count" :step="1" :min="1" :max="50" mr-2 />
<n-input-number-i18n v-model:value="count" :min="1" :max="50" size="small" />
</n-form-item>
<c-input-text
v-model:value="passwords"
multiline
:placeholder="t('tools.password-generator.passwordPlaceholder')"
readonly
rows="3"
autosize
class="password-display"
word-wrap
/>
<div mt-5 flex justify-center gap-3>
<c-button @click="copy()">
{{ t('tools.password-generator.copy') }}
</c-button>
<c-button @click="refreshPasswords">
{{ t('tools.password-generator.refresh') }}
</c-button>
</div>
</c-card>
</div>
</template>
<style scoped lang="less">
::v-deep(.password-display) {
textarea {
text-align: center;
}
}
</style>