commit 540423f2bf17da18892b694e472dc20e359b8733 Author: dengqichen Date: Sun Nov 16 19:12:44 2025 +0800 aaaaa diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b3914a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Dependencies +node_modules/ +package-lock.json +yarn.lock + +# Logs +logs +*.log +npm-debug.log* + +# Environment +.env +.env.local + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Test coverage +coverage/ + +# Build output +dist/ +build/ + +# Temporary files +*.tmp +temp/ diff --git a/.windsurf/rules/project.md b/.windsurf/rules/project.md new file mode 100644 index 0000000..e96892e --- /dev/null +++ b/.windsurf/rules/project.md @@ -0,0 +1,4 @@ +--- +trigger: always_on +--- + diff --git a/README.md b/README.md new file mode 100644 index 0000000..0fd693f --- /dev/null +++ b/README.md @@ -0,0 +1,287 @@ +# Auto Account Machine (AAM) + +🛠️ **自动化工具集 - 虚拟数据生成工具** + +一个模块化、可扩展的命令行工具集,用于生成各种虚拟测试数据。 + +## ✨ 特性 + +- 🎯 **模块化设计** - 插件化架构,易于添加新工具 +- 🚀 **开箱即用** - 简单的CLI界面,无需复杂配置 +- 🔧 **高度可配置** - 支持多种输出格式和自定义选项 +- 📦 **轻量级** - 最小依赖,快速安装 +- 🌍 **跨平台** - 支持 macOS、Linux、Windows + +## 📦 安装 + +### 本地安装 + +```bash +# 克隆仓库 +git clone +cd auto-account-machine + +# 安装依赖 +npm install + +# 测试运行 +node src/index.js card +``` + +### 全局安装(可选) + +```bash +# 在项目目录下 +npm link + +# 现在可以全局使用 aam 命令 +aam --help +``` + +## 🚀 快速开始 + +### 生成信用卡 + +```bash +# 生成一张默认银联卡 +node src/index.js card + +# 或使用 npm script +npm run card +``` + +输出示例: +``` +6228367541234567|08|28|456 +``` + +## 📖 使用指南 + +### 信用卡生成器 + +#### 基本用法 + +```bash +# 生成一张银联卡 +node src/index.js card + +# 生成Visa卡 +node src/index.js card -t visa + +# 批量生成10张银联卡 +node src/index.js card -t unionpay -n 10 + +# JSON格式输出 +node src/index.js card -t visa -f json + +# 美化格式输出 +node src/index.js card -f pretty +``` + +#### 参数说明 + +| 参数 | 简写 | 说明 | 默认值 | 可选值 | +|------|------|------|--------|--------| +| --type | -t | 卡类型 | unionpay | unionpay, visa, mastercard, amex, discover | +| --count | -n | 生成数量 | 1 | 任意正整数 | +| --format | -f | 输出格式 | pipe | pipe, json, csv, pretty | + +#### 支持的卡类型 + +```bash +# 查看所有支持的卡类型 +node src/index.js card list-types +``` + +| 卡类型 | 说明 | 卡号长度 | CVV长度 | +|--------|------|----------|---------| +| unionpay | 中国银联 | 16 | 3 | +| visa | Visa | 16 | 3 | +| mastercard | MasterCard | 16 | 3 | +| amex | American Express | 15 | 4 | +| discover | Discover | 16 | 3 | + +#### 输出格式 + +```bash +# 查看所有支持的输出格式 +node src/index.js card list-formats +``` + +**Pipe 格式** (默认) +``` +6228367541234567|08|28|456 +``` + +**JSON 格式** +```json +{ + "number": "6228367541234567", + "month": "08", + "year": "28", + "cvv": "456", + "type": "中国银联 (UnionPay)" +} +``` + +**CSV 格式** +``` +6228367541234567,08,28,456 +``` + +**Pretty 格式** +``` +Card Number: 6228367541234567 +Expiry Date: 08/28 +CVV: 456 +Type: 中国银联 (UnionPay) +``` + +## 🔧 高级用法 + +### 管道操作 + +```bash +# 生成并保存到文件 +node src/index.js card -n 100 > cards.txt + +# 生成JSON格式并美化 +node src/index.js card -f json | jq + +# 批量生成CSV格式 +node src/index.js card -t visa -n 50 -f csv > visa_cards.csv +``` + +### 脚本集成 + +```javascript +// 在Node.js项目中使用 +const CardGenerator = require('./src/tools/card-generator/generator'); + +const generator = new CardGenerator(); +const card = generator.generate('unionpay'); + +console.log(card); +// { number: '6228367541234567', month: '08', year: '28', cvv: '456', type: '中国银联 (UnionPay)' } +``` + +## 🏗️ 项目结构 + +``` +auto-account-machine/ +├── bin/ +│ └── aam # CLI入口 +├── src/ +│ ├── index.js # 主入口和工具注册 +│ ├── cli.js # CLI路由 +│ ├── tools/ # 工具集目录 +│ │ └── card-generator/ # 信用卡生成器 +│ │ ├── index.js # 工具入口 +│ │ ├── generator.js # 生成逻辑 +│ │ ├── config.js # 配置 +│ │ └── formatter.js # 格式化 +│ └── shared/ # 共享模块 +│ ├── utils.js # 工具函数 +│ ├── logger.js # 日志 +│ └── errors.js # 错误处理 +├── tests/ # 测试 +├── docs/ # 文档 +├── package.json +└── README.md +``` + +## 🔌 扩展开发 + +### 添加新工具 + +1. 在 `src/tools/` 创建新目录 +2. 创建工具入口文件,导出符合以下接口的对象: + +```javascript +module.exports = { + name: 'tool-name', // 工具名称(必需) + alias: 'alias', // 别名(可选) + description: '工具描述', // 描述(必需) + execute: (options) => { // 执行函数(必需) + // 工具逻辑 + } +}; +``` + +3. 在 `src/cli.js` 注册命令 +4. 工具会自动被发现和加载 + +### 示例:创建新工具 + +```javascript +// src/tools/email-generator/index.js +module.exports = { + name: 'email-generator', + alias: 'email', + description: '生成虚拟邮箱地址', + execute: (options) => { + // 实现邮箱生成逻辑 + console.log('generated@example.com'); + } +}; +``` + +## 🧪 测试 + +```bash +# 运行测试(待实现) +npm test + +# 手动测试 +node src/index.js card -n 5 +``` + +## 📋 待办事项 + +- [ ] 添加更多工具(邮箱生成器、用户名生成器等) +- [ ] 添加单元测试 +- [ ] 添加配置文件支持 +- [ ] 发布到 npm +- [ ] 添加交互式模式 +- [ ] 支持自定义卡号规则 + +## 🤝 贡献 + +欢迎贡献代码、报告问题或提出建议! + +1. Fork 项目 +2. 创建特性分支 (`git checkout -b feature/AmazingFeature`) +3. 提交更改 (`git commit -m 'Add some AmazingFeature'`) +4. 推送到分支 (`git push origin feature/AmazingFeature`) +5. 开启 Pull Request + +## ⚠️ 免责声明 + +**重要提示:** 本工具生成的所有信用卡号仅供测试和教育目的使用。这些卡号是虚拟的,不具有任何实际的货币价值或购买能力。 + +- ❌ 请勿将生成的卡号用于任何非法活动 +- ❌ 请勿尝试使用这些卡号进行真实交易 +- ❌ 请勿用于欺诈、诈骗或其他违法行为 + +使用本工具进行非法活动是违法的,可能导致法律责任。我们强烈反对任何非法使用,并将配合执法部门对滥用行为进行调查。 + +**本工具仅用于:** +- ✅ 软件开发测试 +- ✅ 教育和学习目的 +- ✅ 系统集成测试 +- ✅ UI/UX 原型设计 + +## 📄 许可证 + +MIT License - 详见 [LICENSE](LICENSE) 文件 + +## 📧 联系方式 + +如有问题或建议,请通过以下方式联系: + +- 提交 Issue +- 发送 Pull Request + +--- + +**⭐ 如果这个项目对您有帮助,请给个星标支持!** diff --git a/bin/aam b/bin/aam new file mode 100755 index 0000000..79afa56 --- /dev/null +++ b/bin/aam @@ -0,0 +1,7 @@ +#!/usr/bin/env node + +/** + * Auto Account Machine CLI Entry Point + */ + +require('../src/cli'); diff --git a/docs/tools/card-generator.md b/docs/tools/card-generator.md new file mode 100644 index 0000000..37ea667 --- /dev/null +++ b/docs/tools/card-generator.md @@ -0,0 +1,231 @@ +# 信用卡生成器 (Card Generator) + +虚拟信用卡号生成工具,支持多种卡类型和输出格式。 + +## 功能特性 + +- ✅ 支持多种国际卡类型(银联、Visa、MasterCard、AMEX、Discover) +- ✅ 可选 Luhn 算法校验 +- ✅ 灵活的有效期生成(2026-2030) +- ✅ 多种输出格式(Pipe、JSON、CSV、Pretty) +- ✅ 批量生成支持 + +## 技术实现 + +### 卡号生成算法 + +#### 纯随机生成 +``` +卡号 = 固定前缀 + 随机数字 +``` + +#### Luhn算法生成 +``` +1. 固定前缀 + 随机数字(n-1位) +2. 计算校验位 +3. 附加校验位得到完整卡号 +``` + +### 有效期生成 + +```javascript +月份: random(1-12) → 格式化为两位数 "01"-"12" +年份: random(26-30) → 格式化为两位数 "26"-"30" +``` + +### CVV生成 + +```javascript +CVV = random(0, 10^cvvLength - 1) → 格式化为指定位数 +``` + +## 配置说明 + +### 卡类型配置结构 + +```javascript +{ + name: '卡类型名称', + prefix: '卡号前缀', + length: 卡号总长度, + cvvLength: CVV长度, + useLuhn: 是否使用Luhn算法 +} +``` + +### 添加新卡类型 + +编辑 `src/tools/card-generator/config.js`: + +```javascript +CARD_TYPES.newcard = { + name: '新卡类型', + prefix: '123456', + length: 16, + cvvLength: 3, + useLuhn: true +}; +``` + +## API 参考 + +### CardGenerator 类 + +```javascript +const CardGenerator = require('./generator'); +const generator = new CardGenerator(); +``` + +#### 方法 + +**generate(type)** +- 参数:`type` (string) - 卡类型,默认 'unionpay' +- 返回:Object - 包含 number, month, year, cvv, type + +**generateBatch(count, type)** +- 参数: + - `count` (number) - 生成数量 + - `type` (string) - 卡类型,默认 'unionpay' +- 返回:Array - 卡信息数组 + +**getSupportedTypes()** +- 返回:Array - 所有支持的卡类型 + +### Formatter 类 + +```javascript +const Formatter = require('./formatter'); +const formatter = new Formatter(); +``` + +#### 方法 + +**format(card, format)** +- 参数: + - `card` (Object) - 卡信息对象 + - `format` (string) - 格式类型,默认 'pipe' +- 返回:string - 格式化后的字符串 + +**formatBatch(cards, format)** +- 参数: + - `cards` (Array) - 卡信息数组 + - `format` (string) - 格式类型 +- 返回:string - 格式化后的字符串(多行) + +## 使用示例 + +### 基础用法 + +```bash +# 生成单张银联卡 +node src/index.js card + +# 生成Visa卡 +node src/index.js card -t visa + +# 批量生成 +node src/index.js card -n 10 +``` + +### 不同格式输出 + +```bash +# Pipe格式(默认) +node src/index.js card +# 输出: 6228367541234567|08|28|456 + +# JSON格式 +node src/index.js card -f json + +# CSV格式 +node src/index.js card -f csv + +# 美化格式 +node src/index.js card -f pretty +``` + +### 编程使用 + +```javascript +const CardGenerator = require('./src/tools/card-generator/generator'); +const Formatter = require('./src/tools/card-generator/formatter'); + +const generator = new CardGenerator(); +const formatter = new Formatter(); + +// 生成单张卡 +const card = generator.generate('visa'); +console.log(formatter.format(card, 'pipe')); + +// 批量生成 +const cards = generator.generateBatch(5, 'unionpay'); +cards.forEach(card => { + console.log(formatter.format(card, 'pipe')); +}); +``` + +## 测试验证 + +### 手动测试 + +```bash +# 测试不同卡类型 +node src/index.js card -t unionpay +node src/index.js card -t visa +node src/index.js card -t mastercard +node src/index.js card -t amex +node src/index.js card -t discover + +# 测试批量生成 +node src/index.js card -n 20 + +# 测试不同格式 +node src/index.js card -f json +node src/index.js card -f csv +node src/index.js card -f pretty +``` + +### Luhn算法验证 + +```bash +# 生成Visa卡(使用Luhn算法) +node src/index.js card -t visa -f json + +# 使用在线工具验证卡号 +# https://www.freeformatter.com/credit-card-number-generator-validator.html +``` + +## 常见问题 + +### Q: 为什么银联卡不使用Luhn算法? +A: 可以在配置中启用。默认不启用是为了保持与原始样本数据的一致性。 + +### Q: 如何修改有效期范围? +A: 编辑 `src/tools/card-generator/config.js` 中的 `EXPIRY_CONFIG`。 + +### Q: 生成的卡号能用于真实交易吗? +A: **绝对不能!** 这些是测试用的虚拟卡号,没有任何实际价值。 + +### Q: 如何添加自定义输出格式? +A: 在 `config.js` 的 `OUTPUT_FORMATS` 中添加新格式: + +```javascript +OUTPUT_FORMATS.custom = { + name: '自定义格式', + formatter: (card) => `${card.number} - ${card.month}/${card.year} - ${card.cvv}` +}; +``` + +## 扩展建议 + +- [ ] 支持自定义前缀和长度 +- [ ] 添加卡号验证功能 +- [ ] 支持配置文件导入卡类型 +- [ ] 生成完整的持卡人信息(姓名、地址等) +- [ ] 支持特定BIN(银行识别码)生成 + +## 相关资源 + +- [Luhn算法详解](https://en.wikipedia.org/wiki/Luhn_algorithm) +- [信用卡号结构](https://en.wikipedia.org/wiki/Payment_card_number) +- [BIN数据库](https://binlist.net/) diff --git a/package.json b/package.json new file mode 100644 index 0000000..8002016 --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "auto-account-machine", + "version": "1.0.0", + "description": "自动化工具集 - 虚拟数据生成工具", + "main": "src/index.js", + "bin": { + "aam": "./bin/aam" + }, + "scripts": { + "start": "node src/index.js", + "card": "node src/index.js card", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "generator", + "credit-card", + "tools", + "automation", + "virtual-data" + ], + "author": "", + "license": "MIT", + "dependencies": { + "commander": "^11.0.0" + }, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/src/cli.js b/src/cli.js new file mode 100644 index 0000000..e19736a --- /dev/null +++ b/src/cli.js @@ -0,0 +1,80 @@ +/** + * CLI - 命令行接口 + */ + +const { Command } = require('commander'); +const registry = require('./index'); +const logger = require('./shared/logger'); +const packageJson = require('../package.json'); + +const program = new Command(); + +// 主程序配置 +program + .name('aam') + .description('Auto Account Machine - 自动化工具集') + .version(packageJson.version); + +// 注册card-generator命令 +const cardTool = registry.get('card-generator'); +if (cardTool) { + const cardCommand = program + .command('card') + .description('生成虚拟信用卡号') + .option('-t, --type ', '卡类型 (unionpay, visa, mastercard, amex, discover)', 'unionpay') + .option('-n, --count ', '生成数量', '1') + .option('-f, --format ', '输出格式 (pipe, json, csv, pretty)', 'pipe') + .action((options) => { + cardTool.execute(options); + }); + + // 添加子命令 + cardCommand + .command('list-types') + .description('列出所有支持的卡类型') + .action(() => { + cardTool.listTypes(); + }); + + cardCommand + .command('list-formats') + .description('列出所有支持的输出格式') + .action(() => { + cardTool.listFormats(); + }); +} + +// 列出所有工具 +program + .command('list') + .description('列出所有可用工具') + .action(() => { + const tools = registry.getAll(); + console.log('\n可用工具:\n'); + tools.forEach(tool => { + const alias = tool.alias ? ` (${tool.alias})` : ''; + console.log(` ${tool.name}${alias.padEnd(20)} - ${tool.description}`); + }); + console.log(''); + }); + +// 帮助信息增强 +program.on('--help', () => { + console.log(''); + console.log('Examples:'); + console.log(' $ aam card # 生成一张默认银联卡'); + console.log(' $ aam card -t visa # 生成一张Visa卡'); + console.log(' $ aam card -t unionpay -n 10 # 生成10张银联卡'); + console.log(' $ aam card -t visa -f json # JSON格式输出'); + console.log(' $ aam card list-types # 查看支持的卡类型'); + console.log(' $ aam list # 列出所有工具'); + console.log(''); +}); + +// 解析命令 +program.parse(process.argv); + +// 如果没有参数,显示帮助 +if (!process.argv.slice(2).length) { + program.outputHelp(); +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..265e555 --- /dev/null +++ b/src/index.js @@ -0,0 +1,89 @@ +/** + * Auto Account Machine - 主入口 + * 工具注册和管理 + */ + +const fs = require('fs'); +const path = require('path'); +const logger = require('./shared/logger'); + +class ToolRegistry { + constructor() { + this.tools = new Map(); + } + + /** + * 注册工具 + * @param {Object} tool - 工具对象 + */ + register(tool) { + if (!tool.name || !tool.execute) { + throw new Error('Tool must have name and execute method'); + } + this.tools.set(tool.name, tool); + if (tool.alias) { + this.tools.set(tool.alias, tool); + } + } + + /** + * 获取工具 + * @param {string} name - 工具名称或别名 + * @returns {Object|null} + */ + get(name) { + return this.tools.get(name) || null; + } + + /** + * 获取所有工具 + * @returns {Array} + */ + getAll() { + const uniqueTools = new Map(); + for (const [key, tool] of this.tools) { + if (!uniqueTools.has(tool.name)) { + uniqueTools.set(tool.name, tool); + } + } + return Array.from(uniqueTools.values()); + } + + /** + * 自动发现并注册所有工具 + * @param {string} toolsDir - 工具目录路径 + */ + autoDiscover(toolsDir) { + try { + const items = fs.readdirSync(toolsDir); + + items.forEach(item => { + const itemPath = path.join(toolsDir, item); + const stat = fs.statSync(itemPath); + + if (stat.isDirectory()) { + try { + const tool = require(itemPath); + this.register(tool); + logger.debug('registry', `Registered tool: ${tool.name}`); + } catch (error) { + logger.warn('registry', `Failed to load tool from ${item}: ${error.message}`); + } + } + }); + + logger.debug('registry', `Total tools registered: ${this.getAll().length}`); + } catch (error) { + logger.error('registry', `Failed to discover tools: ${error.message}`); + } + } +} + +// 创建全局注册表实例 +const registry = new ToolRegistry(); + +// 自动发现工具 +const toolsDir = path.join(__dirname, 'tools'); +registry.autoDiscover(toolsDir); + +module.exports = registry; diff --git a/src/shared/errors.js b/src/shared/errors.js new file mode 100644 index 0000000..31f8897 --- /dev/null +++ b/src/shared/errors.js @@ -0,0 +1,40 @@ +/** + * Errors - 自定义错误类 + */ + +/** + * 工具错误基类 + */ +class ToolError extends Error { + constructor(toolName, message) { + super(`[${toolName}] ${message}`); + this.name = 'ToolError'; + this.toolName = toolName; + } +} + +/** + * 配置错误 + */ +class ConfigError extends ToolError { + constructor(toolName, message) { + super(toolName, `Configuration Error: ${message}`); + this.name = 'ConfigError'; + } +} + +/** + * 验证错误 + */ +class ValidationError extends ToolError { + constructor(toolName, message) { + super(toolName, `Validation Error: ${message}`); + this.name = 'ValidationError'; + } +} + +module.exports = { + ToolError, + ConfigError, + ValidationError +}; diff --git a/src/shared/logger.js b/src/shared/logger.js new file mode 100644 index 0000000..0982dd3 --- /dev/null +++ b/src/shared/logger.js @@ -0,0 +1,44 @@ +/** + * Logger - 统一日志工具 + */ + +const logger = { + /** + * 信息日志 + */ + info(tool, message) { + console.log(`[${tool}] ${message}`); + }, + + /** + * 成功日志 + */ + success(tool, message) { + console.log(`[${tool}] ✓ ${message}`); + }, + + /** + * 错误日志 + */ + error(tool, message) { + console.error(`[${tool}] ✗ ERROR: ${message}`); + }, + + /** + * 警告日志 + */ + warn(tool, message) { + console.warn(`[${tool}] ⚠ WARNING: ${message}`); + }, + + /** + * 调试日志 + */ + debug(tool, message) { + if (process.env.DEBUG) { + console.log(`[${tool}] [DEBUG] ${message}`); + } + } +}; + +module.exports = logger; diff --git a/src/shared/utils.js b/src/shared/utils.js new file mode 100644 index 0000000..87e9118 --- /dev/null +++ b/src/shared/utils.js @@ -0,0 +1,104 @@ +/** + * Utils - 通用工具函数 + */ + +/** + * 生成指定范围的随机整数 + * @param {number} min - 最小值(包含) + * @param {number} max - 最大值(包含) + * @returns {number} + */ +function randomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +/** + * 生成指定长度的随机数字字符串 + * @param {number} length - 长度 + * @returns {string} + */ +function randomDigits(length) { + let result = ''; + for (let i = 0; i < length; i++) { + result += randomInt(0, 9); + } + return result; +} + +/** + * 将数字填充为指定长度的字符串 + * @param {number} num - 数字 + * @param {number} length - 目标长度 + * @returns {string} + */ +function padZero(num, length = 2) { + return String(num).padStart(length, '0'); +} + +/** + * Luhn算法校验(信用卡号校验) + * @param {string} cardNumber - 卡号 + * @returns {boolean} + */ +function luhnCheck(cardNumber) { + let sum = 0; + let isEven = false; + + // 从右向左遍历 + for (let i = cardNumber.length - 1; i >= 0; i--) { + let digit = parseInt(cardNumber[i]); + + if (isEven) { + digit *= 2; + if (digit > 9) { + digit -= 9; + } + } + + sum += digit; + isEven = !isEven; + } + + return sum % 10 === 0; +} + +/** + * 生成符合Luhn算法的卡号 + * @param {string} prefix - 卡号前缀 + * @param {number} totalLength - 总长度 + * @returns {string} + */ +function generateLuhnNumber(prefix, totalLength) { + // 生成除最后一位外的随机数字 + const remaining = totalLength - prefix.length - 1; + let cardNumber = prefix + randomDigits(remaining); + + // 计算校验位 + let sum = 0; + let isEven = true; + + for (let i = cardNumber.length - 1; i >= 0; i--) { + let digit = parseInt(cardNumber[i]); + + if (isEven) { + digit *= 2; + if (digit > 9) { + digit -= 9; + } + } + + sum += digit; + isEven = !isEven; + } + + const checkDigit = (10 - (sum % 10)) % 10; + return cardNumber + checkDigit; +} + +module.exports = { + randomInt, + randomDigits, + padZero, + luhnCheck, + generateLuhnNumber +}; diff --git a/src/tools/card-generator/config.js b/src/tools/card-generator/config.js new file mode 100644 index 0000000..2c6adb2 --- /dev/null +++ b/src/tools/card-generator/config.js @@ -0,0 +1,85 @@ +/** + * Card Generator Configuration + * 卡类型配置 + */ + +const CARD_TYPES = { + unionpay: { + name: '中国银联 (UnionPay)', + prefix: '622836754', + length: 16, + cvvLength: 3, + useLuhn: false // 可选:是否使用Luhn算法 + }, + visa: { + name: 'Visa', + prefix: '4', + length: 16, + cvvLength: 3, + useLuhn: true + }, + mastercard: { + name: 'MasterCard', + prefix: '5', + length: 16, + cvvLength: 3, + useLuhn: true + }, + amex: { + name: 'American Express', + prefix: '34', + length: 15, + cvvLength: 4, + useLuhn: true + }, + discover: { + name: 'Discover', + prefix: '6011', + length: 16, + cvvLength: 3, + useLuhn: true + } +}; + +/** + * 有效期配置 + */ +const EXPIRY_CONFIG = { + minYear: 26, // 2026 + maxYear: 30, // 2030 + minMonth: 1, + maxMonth: 12 +}; + +/** + * 输出格式配置 + */ +const OUTPUT_FORMATS = { + pipe: { + name: 'Pipe分隔 (|)', + formatter: (card) => `${card.number}|${card.month}|${card.year}|${card.cvv}` + }, + json: { + name: 'JSON格式', + formatter: (card) => JSON.stringify(card, null, 2) + }, + csv: { + name: 'CSV格式', + formatter: (card) => `${card.number},${card.month},${card.year},${card.cvv}` + }, + pretty: { + name: '美化格式', + formatter: (card) => ` +Card Number: ${card.number} +Expiry Date: ${card.month}/${card.year} +CVV: ${card.cvv} +Type: ${card.type} + `.trim() + } +}; + +module.exports = { + CARD_TYPES, + EXPIRY_CONFIG, + OUTPUT_FORMATS +}; diff --git a/src/tools/card-generator/formatter.js b/src/tools/card-generator/formatter.js new file mode 100644 index 0000000..4055977 --- /dev/null +++ b/src/tools/card-generator/formatter.js @@ -0,0 +1,48 @@ +/** + * Formatter - 输出格式化 + */ + +const { OUTPUT_FORMATS } = require('./config'); + +class Formatter { + constructor() { + this.formats = OUTPUT_FORMATS; + } + + /** + * 格式化单张卡 + * @param {Object} card - 卡信息 + * @param {string} format - 格式类型 + * @returns {string} + */ + format(card, format = 'pipe') { + const formatter = this.formats[format]; + if (!formatter) { + throw new Error(`Unknown format: ${format}`); + } + return formatter.formatter(card); + } + + /** + * 格式化多张卡 + * @param {Array} cards - 卡信息数组 + * @param {string} format - 格式类型 + * @returns {string} + */ + formatBatch(cards, format = 'pipe') { + return cards.map(card => this.format(card, format)).join('\n'); + } + + /** + * 获取所有支持的格式 + * @returns {Array} + */ + getSupportedFormats() { + return Object.keys(this.formats).map(key => ({ + id: key, + name: this.formats[key].name + })); + } +} + +module.exports = Formatter; diff --git a/src/tools/card-generator/generator.js b/src/tools/card-generator/generator.js new file mode 100644 index 0000000..af798c8 --- /dev/null +++ b/src/tools/card-generator/generator.js @@ -0,0 +1,110 @@ +/** + * Card Generator - 核心生成逻辑 + */ + +const { randomInt, randomDigits, padZero, generateLuhnNumber } = require('../../shared/utils'); +const { CARD_TYPES, EXPIRY_CONFIG } = require('./config'); +const { ValidationError } = require('../../shared/errors'); + +class CardGenerator { + constructor() { + this.cardTypes = CARD_TYPES; + this.expiryConfig = EXPIRY_CONFIG; + } + + /** + * 生成卡号 + * @param {string} type - 卡类型 + * @returns {string} + */ + generateCardNumber(type) { + const config = this.cardTypes[type]; + if (!config) { + throw new ValidationError('card-generator', `Unknown card type: ${type}`); + } + + const { prefix, length, useLuhn } = config; + + if (useLuhn) { + // 使用Luhn算法生成 + return generateLuhnNumber(prefix, length); + } else { + // 纯随机生成 + const remainingLength = length - prefix.length; + return prefix + randomDigits(remainingLength); + } + } + + /** + * 生成有效期 + * @returns {{month: string, year: string}} + */ + generateExpiry() { + const month = randomInt(this.expiryConfig.minMonth, this.expiryConfig.maxMonth); + const year = randomInt(this.expiryConfig.minYear, this.expiryConfig.maxYear); + + return { + month: padZero(month, 2), + year: padZero(year, 2) + }; + } + + /** + * 生成CVV安全码 + * @param {string} type - 卡类型 + * @returns {string} + */ + generateCVV(type) { + const config = this.cardTypes[type]; + const cvvLength = config.cvvLength; + const maxValue = Math.pow(10, cvvLength) - 1; + const cvv = randomInt(0, maxValue); + return padZero(cvv, cvvLength); + } + + /** + * 生成完整的信用卡信息 + * @param {string} type - 卡类型,默认'unionpay' + * @returns {Object} + */ + generate(type = 'unionpay') { + const number = this.generateCardNumber(type); + const expiry = this.generateExpiry(); + const cvv = this.generateCVV(type); + + return { + number, + month: expiry.month, + year: expiry.year, + cvv, + type: this.cardTypes[type].name + }; + } + + /** + * 批量生成 + * @param {number} count - 数量 + * @param {string} type - 卡类型 + * @returns {Array} + */ + generateBatch(count, type = 'unionpay') { + const cards = []; + for (let i = 0; i < count; i++) { + cards.push(this.generate(type)); + } + return cards; + } + + /** + * 获取所有支持的卡类型 + * @returns {Array} + */ + getSupportedTypes() { + return Object.keys(this.cardTypes).map(key => ({ + id: key, + name: this.cardTypes[key].name + })); + } +} + +module.exports = CardGenerator; diff --git a/src/tools/card-generator/index.js b/src/tools/card-generator/index.js new file mode 100644 index 0000000..d02fc2b --- /dev/null +++ b/src/tools/card-generator/index.js @@ -0,0 +1,89 @@ +/** + * Card Generator Tool - 工具入口 + */ + +const CardGenerator = require('./generator'); +const Formatter = require('./formatter'); +const logger = require('../../shared/logger'); + +const TOOL_NAME = 'card-generator'; + +/** + * 执行卡生成 + * @param {Object} options - 选项 + */ +function execute(options) { + try { + const generator = new CardGenerator(); + const formatter = new Formatter(); + + const type = options.type || 'unionpay'; + const count = parseInt(options.count || 1); + const format = options.format || 'pipe'; + + // 验证卡类型 + const supportedTypes = generator.getSupportedTypes().map(t => t.id); + if (!supportedTypes.includes(type)) { + logger.error(TOOL_NAME, `不支持的卡类型: ${type}`); + logger.info(TOOL_NAME, `支持的类型: ${supportedTypes.join(', ')}`); + process.exit(1); + } + + // 生成卡 + let cards; + if (count === 1) { + cards = [generator.generate(type)]; + } else { + cards = generator.generateBatch(count, type); + } + + // 格式化输出 + const output = formatter.formatBatch(cards, format); + console.log(output); + + if (count > 1) { + logger.success(TOOL_NAME, `成功生成 ${count} 张 ${type} 卡`); + } + + } catch (error) { + logger.error(TOOL_NAME, error.message); + process.exit(1); + } +} + +/** + * 列出支持的卡类型 + */ +function listTypes() { + const generator = new CardGenerator(); + const types = generator.getSupportedTypes(); + + console.log('\n支持的卡类型:\n'); + types.forEach(type => { + console.log(` ${type.id.padEnd(15)} - ${type.name}`); + }); + console.log(''); +} + +/** + * 列出支持的输出格式 + */ +function listFormats() { + const formatter = new Formatter(); + const formats = formatter.getSupportedFormats(); + + console.log('\n支持的输出格式:\n'); + formats.forEach(format => { + console.log(` ${format.id.padEnd(15)} - ${format.name}`); + }); + console.log(''); +} + +module.exports = { + name: TOOL_NAME, + alias: 'card', + description: '生成虚拟信用卡号', + execute, + listTypes, + listFormats +};