ar-saas 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +62 -0
  2. package/dist/cli.js +67 -0
  3. package/dist/generator.js +242 -0
  4. package/dist/index.js +13 -0
  5. package/dist/license.js +71 -0
  6. package/package.json +46 -0
  7. package/templates/backend/.env.example +67 -0
  8. package/templates/backend/.prettierrc +4 -0
  9. package/templates/backend/README.md +168 -0
  10. package/templates/backend/eslint.config.mjs +35 -0
  11. package/templates/backend/nest-cli.json +8 -0
  12. package/templates/backend/package-lock.json +10979 -0
  13. package/templates/backend/package.json +88 -0
  14. package/templates/backend/src/app.controller.spec.ts +24 -0
  15. package/templates/backend/src/app.controller.ts +15 -0
  16. package/templates/backend/src/app.module.ts +40 -0
  17. package/templates/backend/src/app.service.ts +11 -0
  18. package/templates/backend/src/common/base/base.repository.ts +221 -0
  19. package/templates/backend/src/common/base/base.schema.ts +24 -0
  20. package/templates/backend/src/common/decorators/cookie.decorator.ts +9 -0
  21. package/templates/backend/src/common/decorators/current-user.decorator.ts +20 -0
  22. package/templates/backend/src/common/decorators/workspace-id.decorator.ts +14 -0
  23. package/templates/backend/src/common/filters/global-exception.filter.ts +61 -0
  24. package/templates/backend/src/common/guards/jwt-auth.guard.ts +5 -0
  25. package/templates/backend/src/common/interceptors/workspace-tenant.interceptor.ts +45 -0
  26. package/templates/backend/src/main.ts +51 -0
  27. package/templates/backend/src/modules/auth/auth.controller.ts +158 -0
  28. package/templates/backend/src/modules/auth/auth.module.ts +20 -0
  29. package/templates/backend/src/modules/auth/auth.service.ts +257 -0
  30. package/templates/backend/src/modules/auth/dto/forgot-password.dto.ts +9 -0
  31. package/templates/backend/src/modules/auth/dto/login.dto.ts +14 -0
  32. package/templates/backend/src/modules/auth/dto/refresh-token.dto.ts +12 -0
  33. package/templates/backend/src/modules/auth/dto/register.dto.ts +26 -0
  34. package/templates/backend/src/modules/auth/dto/reset-password.dto.ts +16 -0
  35. package/templates/backend/src/modules/auth/dto/verify-email.dto.ts +9 -0
  36. package/templates/backend/src/modules/auth/strategies/jwt.strategy.ts +43 -0
  37. package/templates/backend/src/modules/mail/mail.module.ts +9 -0
  38. package/templates/backend/src/modules/mail/mail.service.ts +141 -0
  39. package/templates/backend/src/modules/users/schemas/user.schema.ts +54 -0
  40. package/templates/backend/src/modules/users/users.module.ts +14 -0
  41. package/templates/backend/src/modules/users/users.repository.ts +51 -0
  42. package/templates/backend/src/modules/users/users.service.ts +104 -0
  43. package/templates/backend/src/modules/workspaces/schemas/workspace.schema.ts +26 -0
  44. package/templates/backend/src/modules/workspaces/workspaces.module.ts +16 -0
  45. package/templates/backend/src/modules/workspaces/workspaces.repository.ts +34 -0
  46. package/templates/backend/src/modules/workspaces/workspaces.service.ts +42 -0
  47. package/templates/backend/test/app.e2e-spec.ts +25 -0
  48. package/templates/backend/test/jest-e2e.json +9 -0
  49. package/templates/backend/tsconfig.build.json +4 -0
  50. package/templates/backend/tsconfig.json +26 -0
  51. package/templates/frontend/.env.local.example +1 -0
  52. package/templates/frontend/components.json +20 -0
  53. package/templates/frontend/eslint.config.mjs +14 -0
  54. package/templates/frontend/next.config.ts +5 -0
  55. package/templates/frontend/package-lock.json +6722 -0
  56. package/templates/frontend/package.json +40 -0
  57. package/templates/frontend/postcss.config.mjs +7 -0
  58. package/templates/frontend/src/app/(auth)/forgot-password/page.tsx +84 -0
  59. package/templates/frontend/src/app/(auth)/layout.tsx +28 -0
  60. package/templates/frontend/src/app/(auth)/login/page.tsx +111 -0
  61. package/templates/frontend/src/app/(auth)/register/page.tsx +119 -0
  62. package/templates/frontend/src/app/(auth)/reset-password/page.tsx +120 -0
  63. package/templates/frontend/src/app/(auth)/verify-email/page.tsx +78 -0
  64. package/templates/frontend/src/app/(dashboard)/dashboard/page.tsx +36 -0
  65. package/templates/frontend/src/app/(dashboard)/layout.tsx +59 -0
  66. package/templates/frontend/src/app/globals.css +81 -0
  67. package/templates/frontend/src/app/layout.tsx +26 -0
  68. package/templates/frontend/src/app/page.tsx +5 -0
  69. package/templates/frontend/src/app/setup/page.tsx +278 -0
  70. package/templates/frontend/src/components/ui/button.tsx +52 -0
  71. package/templates/frontend/src/components/ui/card.tsx +50 -0
  72. package/templates/frontend/src/components/ui/form.tsx +158 -0
  73. package/templates/frontend/src/components/ui/input.tsx +21 -0
  74. package/templates/frontend/src/components/ui/label.tsx +22 -0
  75. package/templates/frontend/src/components/ui/toast.tsx +109 -0
  76. package/templates/frontend/src/components/ui/toaster.tsx +30 -0
  77. package/templates/frontend/src/hooks/use-toast.ts +116 -0
  78. package/templates/frontend/src/lib/api/auth.ts +39 -0
  79. package/templates/frontend/src/lib/api/client.ts +66 -0
  80. package/templates/frontend/src/lib/hooks/use-auth.ts +1 -0
  81. package/templates/frontend/src/lib/utils.ts +6 -0
  82. package/templates/frontend/src/providers/auth-provider.tsx +60 -0
  83. package/templates/frontend/src/types/api.ts +12 -0
  84. package/templates/frontend/src/types/auth.ts +27 -0
  85. package/templates/frontend/tsconfig.json +23 -0
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # ar-saas
2
+
3
+ Generador de proyectos SaaS multi-tenant para startups argentinas.
4
+
5
+ ## Quickstart
6
+
7
+ ```bash
8
+ npx ar-saas mi-proyecto
9
+ ```
10
+
11
+ Seguí el asistente interactivo y en minutos tenés un proyecto listo para correr.
12
+
13
+ ## Qué genera
14
+
15
+ **Backend** — NestJS 11 + MongoDB + JWT en cookies HttpOnly + multi-tenancy por workspace + mail con Resend + Swagger automático.
16
+
17
+ **Frontend** — Next.js 15 + Tailwind CSS 4 + shadcn/ui + auth completo + refresh automático de tokens.
18
+
19
+ ## Módulos incluidos (free)
20
+
21
+ - Auth completo: registro, login, verificación de email, reset de password
22
+ - Multi-tenancy con aislamiento estricto por `workspaceId`
23
+ - Mail transaccional con Resend (verificación, bienvenida, reset)
24
+
25
+ ## Módulos adicionales
26
+
27
+ | Módulo | Descripción |
28
+ |---|---|
29
+ | OAuth + 2FA | Login con GitHub/Google + autenticación de dos factores |
30
+ | Notificaciones | Notificaciones in-app + Push Web (VAPID) |
31
+ | Invoices + Quotes | Facturación con generación de PDF |
32
+ | CRM | Kanban + Pipeline de ventas |
33
+ | MercadoPago | Suscripciones recurrentes con webhooks |
34
+
35
+ ## Opciones de deploy
36
+
37
+ El CLI genera la configuración para:
38
+
39
+ - **Railway** — `railway.toml` listo para usar
40
+ - **Fly.io** — `fly.toml` con región `gru` (São Paulo)
41
+ - **Docker** — `docker-compose.yml` con MongoDB incluido
42
+
43
+ ## Requisitos
44
+
45
+ - Node.js 18+
46
+ - MongoDB (o usar el Docker Compose incluido)
47
+ - Cuenta en [Resend](https://resend.com) para emails
48
+
49
+ ## Variables de entorno
50
+
51
+ El CLI copia `.env.example` → `.env` automáticamente. Completar al menos:
52
+
53
+ ```
54
+ MONGODB_URI=
55
+ JWT_ACCESS_SECRET=
56
+ JWT_REFRESH_SECRET=
57
+ RESEND_API_KEY=
58
+ ```
59
+
60
+ ## Licencia
61
+
62
+ MIT — el código generado es tuyo, sin restricciones.
package/dist/cli.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runCli = runCli;
7
+ const inquirer_1 = __importDefault(require("inquirer"));
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const ALWAYS_INCLUDED = ['auth', 'multi-tenancy', 'mail'];
10
+ async function runCli() {
11
+ console.log(chalk_1.default.bold('\n ar-saas'));
12
+ console.log(chalk_1.default.gray(' Backend NestJS + Frontend Next.js listos para producción\n'));
13
+ const answers = await inquirer_1.default.prompt([
14
+ {
15
+ type: 'input',
16
+ name: 'projectName',
17
+ message: 'Nombre del proyecto:',
18
+ default: 'my-saas',
19
+ validate: (input) => {
20
+ if (!/^[a-z0-9][a-z0-9-]{1,}$/.test(input)) {
21
+ return 'Solo letras minúsculas, números y guiones (mínimo 2 caracteres)';
22
+ }
23
+ return true;
24
+ },
25
+ },
26
+ {
27
+ type: 'list',
28
+ name: 'stack',
29
+ message: '¿Qué querés generar?',
30
+ choices: [
31
+ { name: 'Backend + Frontend', value: 'backend-frontend' },
32
+ { name: 'Solo Backend (NestJS)', value: 'backend' },
33
+ { name: 'Solo Frontend (Next.js)', value: 'frontend' },
34
+ ],
35
+ },
36
+ {
37
+ type: 'checkbox',
38
+ name: 'modules',
39
+ message: 'Módulos adicionales:',
40
+ choices: [
41
+ { name: 'OAuth GitHub/Google + 2FA', value: 'auth-advanced' },
42
+ { name: 'Notificaciones + Push Web', value: 'notifications' },
43
+ { name: 'Invoices + Quotes + PDF', value: 'invoices' },
44
+ { name: 'CRM + Kanban', value: 'crm' },
45
+ { name: 'MercadoPago suscripciones', value: 'mercadopago' },
46
+ ],
47
+ filter: (selected) => Array.from(new Set([...ALWAYS_INCLUDED, ...selected])),
48
+ },
49
+ {
50
+ type: 'list',
51
+ name: 'deployTarget',
52
+ message: '¿Dónde lo vas a deployar?',
53
+ choices: [
54
+ { name: 'Railway', value: 'railway' },
55
+ { name: 'Fly.io', value: 'flyio' },
56
+ { name: 'Docker', value: 'docker' },
57
+ { name: 'Después', value: 'later' },
58
+ ],
59
+ },
60
+ ]);
61
+ return {
62
+ projectName: answers.projectName,
63
+ stack: answers.stack,
64
+ modules: answers.modules,
65
+ deployTarget: answers.deployTarget,
66
+ };
67
+ }
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generate = generate;
7
+ const path_1 = __importDefault(require("path"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const fs_extra_1 = __importDefault(require("fs-extra"));
10
+ const chalk_1 = __importDefault(require("chalk"));
11
+ const ora_1 = __importDefault(require("ora"));
12
+ const TEMPLATES_DIR = path_1.default.join(__dirname, '..', 'templates');
13
+ const TEXT_EXTENSIONS = new Set([
14
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
15
+ '.json', '.md', '.txt',
16
+ '.env', '.example',
17
+ '.yml', '.yaml',
18
+ '.toml', '.ini',
19
+ '.html', '.css',
20
+ '.gitignore', '.npmignore', '.eslintrc',
21
+ '.prettierrc', '.editorconfig',
22
+ 'Dockerfile', 'Makefile', 'Procfile',
23
+ ]);
24
+ const SKIP_DIRS = new Set(['.git', 'node_modules', 'dist', '.next', '.turbo', 'build']);
25
+ const PRO_MODULES = new Set(['auth-advanced', 'notifications', 'invoices', 'crm', 'mercadopago']);
26
+ async function generate(config) {
27
+ const projectDir = path_1.default.join(process.cwd(), config.projectName);
28
+ const spinner = (0, ora_1.default)();
29
+ console.log();
30
+ if (fs_1.default.existsSync(projectDir)) {
31
+ console.error(chalk_1.default.red(`✖ El directorio "${config.projectName}" ya existe`));
32
+ process.exit(1);
33
+ }
34
+ spinner.start(`Creando ${chalk_1.default.cyan(config.projectName)}...`);
35
+ fs_1.default.mkdirSync(projectDir, { recursive: true });
36
+ const hasBackend = config.stack === 'backend' || config.stack === 'backend-frontend';
37
+ const hasFrontend = config.stack === 'frontend' || config.stack === 'backend-frontend';
38
+ const hasValidPro = [...config.modules].some((m) => PRO_MODULES.has(m));
39
+ if (hasBackend) {
40
+ spinner.text = 'Copiando backend...';
41
+ const src = path_1.default.join(TEMPLATES_DIR, 'backend');
42
+ const dest = path_1.default.join(projectDir, 'backend');
43
+ if (!fs_1.default.existsSync(src) || fs_1.default.readdirSync(src).length === 0) {
44
+ spinner.warn(chalk_1.default.yellow('Templates de backend vacíos — ejecutá npm run sync-templates antes de publicar'));
45
+ fs_1.default.mkdirSync(dest, { recursive: true });
46
+ }
47
+ else {
48
+ await fs_extra_1.default.copy(src, dest);
49
+ processDir(dest, config, hasValidPro);
50
+ }
51
+ }
52
+ if (hasFrontend) {
53
+ spinner.text = 'Copiando frontend...';
54
+ const src = path_1.default.join(TEMPLATES_DIR, 'frontend');
55
+ const dest = path_1.default.join(projectDir, 'frontend');
56
+ if (!fs_1.default.existsSync(src) || fs_1.default.readdirSync(src).length === 0) {
57
+ spinner.warn(chalk_1.default.yellow('Templates de frontend vacíos — ejecutá npm run sync-templates antes de publicar'));
58
+ fs_1.default.mkdirSync(dest, { recursive: true });
59
+ }
60
+ else {
61
+ await fs_extra_1.default.copy(src, dest);
62
+ processDir(dest, config, hasValidPro);
63
+ }
64
+ }
65
+ spinner.text = 'Generando configuración de deploy...';
66
+ generateDeployConfig(projectDir, config);
67
+ spinner.text = 'Configurando variables de entorno...';
68
+ setupEnvFiles(projectDir, config);
69
+ spinner.succeed(chalk_1.default.green(`Proyecto ${chalk_1.default.bold(config.projectName)} creado`));
70
+ printNextSteps(config);
71
+ }
72
+ function processDir(dir, config, hasValidPro) {
73
+ for (const file of collectTextFiles(dir)) {
74
+ try {
75
+ let content = fs_1.default.readFileSync(file, 'utf-8');
76
+ content = applyNameReplacements(content, config.projectName);
77
+ content = applyProModuleHandling(content, hasValidPro);
78
+ fs_1.default.writeFileSync(file, content, 'utf-8');
79
+ }
80
+ catch {
81
+ // skip unreadable or binary files
82
+ }
83
+ }
84
+ }
85
+ function collectTextFiles(dir) {
86
+ const result = [];
87
+ for (const entry of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
88
+ const fullPath = path_1.default.join(dir, entry.name);
89
+ if (entry.isDirectory()) {
90
+ if (!SKIP_DIRS.has(entry.name)) {
91
+ result.push(...collectTextFiles(fullPath));
92
+ }
93
+ }
94
+ else {
95
+ const ext = path_1.default.extname(entry.name);
96
+ if (TEXT_EXTENSIONS.has(ext) || TEXT_EXTENSIONS.has(entry.name) || entry.name.startsWith('.')) {
97
+ result.push(fullPath);
98
+ }
99
+ }
100
+ }
101
+ return result;
102
+ }
103
+ function applyNameReplacements(content, projectName) {
104
+ return content
105
+ .replace(/create-saas-ar-backend/g, `${projectName}-backend`)
106
+ .replace(/create-saas-ar-frontend/g, `${projectName}-frontend`)
107
+ .replace(/create-saas-ar/g, projectName);
108
+ }
109
+ function applyProModuleHandling(content, hasValidPro) {
110
+ if (hasValidPro) {
111
+ // Uncomment PRO code: remove the "// [PRO] " prefix
112
+ return content.replace(/^(\s*)\/\/ \[PRO\] /gm, '$1');
113
+ }
114
+ // Add explanatory placeholder for PRO lines
115
+ return content.replace(/^(\s*)\/\/ \[PRO\] (.+)$/gm, '$1// [PRO MODULE] $2 — requiere licencia PRO: https://ar-saas.dev');
116
+ }
117
+ function generateDeployConfig(projectDir, config) {
118
+ if (config.deployTarget === 'later')
119
+ return;
120
+ if (config.deployTarget === 'docker') {
121
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'docker-compose.yml'), buildDockerCompose(config), 'utf-8');
122
+ }
123
+ if (config.deployTarget === 'railway') {
124
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'railway.toml'), buildRailwayConfig(), 'utf-8');
125
+ }
126
+ if (config.deployTarget === 'flyio') {
127
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'fly.toml'), buildFlyConfig(config), 'utf-8');
128
+ }
129
+ }
130
+ function buildDockerCompose(config) {
131
+ const hasBackend = config.stack === 'backend' || config.stack === 'backend-frontend';
132
+ const hasFrontend = config.stack === 'frontend' || config.stack === 'backend-frontend';
133
+ const services = [];
134
+ if (hasBackend) {
135
+ services.push(` backend:
136
+ build: ./backend
137
+ ports:
138
+ - "3000:3000"
139
+ env_file:
140
+ - ./backend/.env
141
+ depends_on:
142
+ - mongodb
143
+ restart: unless-stopped
144
+
145
+ mongodb:
146
+ image: mongo:7
147
+ ports:
148
+ - "27017:27017"
149
+ volumes:
150
+ - mongodb_data:/data/db
151
+ restart: unless-stopped`);
152
+ }
153
+ if (hasFrontend) {
154
+ services.push(` frontend:
155
+ build: ./frontend
156
+ ports:
157
+ - "3001:3000"
158
+ env_file:
159
+ - ./frontend/.env.local
160
+ environment:
161
+ - NEXT_PUBLIC_API_URL=http://backend:3000
162
+ ${hasBackend ? 'depends_on:\n - backend\n ' : ''}restart: unless-stopped`);
163
+ }
164
+ const volumes = hasBackend ? '\nvolumes:\n mongodb_data:' : '';
165
+ return `version: '3.8'
166
+
167
+ services:
168
+ ${services.join('\n\n')}
169
+ ${volumes}
170
+ `;
171
+ }
172
+ function buildRailwayConfig() {
173
+ return `[build]
174
+ builder = "nixpacks"
175
+
176
+ [deploy]
177
+ startCommand = "npm run start:prod"
178
+ healthcheckPath = "/api/health"
179
+ healthcheckTimeout = 30
180
+ restartPolicyType = "on_failure"
181
+ `;
182
+ }
183
+ function buildFlyConfig(config) {
184
+ return `app = "${config.projectName}"
185
+ primary_region = "gru"
186
+
187
+ [build]
188
+
189
+ [http_service]
190
+ internal_port = 3000
191
+ force_https = true
192
+ auto_stop_machines = true
193
+ auto_start_machines = true
194
+ min_machines_running = 0
195
+
196
+ [[vm]]
197
+ memory = "256mb"
198
+ cpu_kind = "shared"
199
+ cpus = 1
200
+ `;
201
+ }
202
+ function setupEnvFiles(projectDir, config) {
203
+ const hasBackend = config.stack === 'backend' || config.stack === 'backend-frontend';
204
+ const hasFrontend = config.stack === 'frontend' || config.stack === 'backend-frontend';
205
+ if (hasBackend) {
206
+ const example = path_1.default.join(projectDir, 'backend', '.env.example');
207
+ const dest = path_1.default.join(projectDir, 'backend', '.env');
208
+ if (fs_1.default.existsSync(example) && !fs_1.default.existsSync(dest)) {
209
+ fs_extra_1.default.copySync(example, dest);
210
+ }
211
+ }
212
+ if (hasFrontend) {
213
+ const example = path_1.default.join(projectDir, 'frontend', '.env.local.example');
214
+ const dest = path_1.default.join(projectDir, 'frontend', '.env.local');
215
+ if (fs_1.default.existsSync(example) && !fs_1.default.existsSync(dest)) {
216
+ fs_extra_1.default.copySync(example, dest);
217
+ }
218
+ }
219
+ }
220
+ function printNextSteps(config) {
221
+ const hasBackend = config.stack === 'backend' || config.stack === 'backend-frontend';
222
+ const hasFrontend = config.stack === 'frontend' || config.stack === 'backend-frontend';
223
+ console.log();
224
+ console.log(chalk_1.default.bold('Próximos pasos:'));
225
+ if (hasBackend) {
226
+ console.log();
227
+ console.log(chalk_1.default.cyan(` cd ${config.projectName}/backend`));
228
+ console.log(chalk_1.default.gray(' # Completar las variables en .env'));
229
+ console.log(chalk_1.default.cyan(' npm install'));
230
+ console.log(chalk_1.default.cyan(' npm run start:dev'));
231
+ }
232
+ if (hasFrontend) {
233
+ console.log();
234
+ console.log(chalk_1.default.cyan(` cd ${config.projectName}/frontend`));
235
+ console.log(chalk_1.default.gray(' # Completar .env.local con la URL del backend'));
236
+ console.log(chalk_1.default.cyan(' npm install'));
237
+ console.log(chalk_1.default.cyan(' npm run dev'));
238
+ }
239
+ console.log();
240
+ console.log(chalk_1.default.gray(' Documentación: https://ar-saas.dev/docs'));
241
+ console.log();
242
+ }
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const cli_1 = require("./cli");
5
+ const generator_1 = require("./generator");
6
+ async function main() {
7
+ const config = await (0, cli_1.runCli)();
8
+ await (0, generator_1.generate)(config);
9
+ }
10
+ main().catch((error) => {
11
+ console.error(error.message);
12
+ process.exit(1);
13
+ });
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateLicense = validateLicense;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const CACHE_DIR = path_1.default.join(os_1.default.homedir(), '.ar-saas');
11
+ const CACHE_FILE = path_1.default.join(CACHE_DIR, 'license');
12
+ const LICENSE_API = 'https://api.create-saas-ar.dev/licenses/validate';
13
+ const LICENSE_REGEX = /^CSAR-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
14
+ async function validateLicense(license) {
15
+ const normalized = license.trim().toUpperCase();
16
+ if (!LICENSE_REGEX.test(normalized)) {
17
+ return {
18
+ valid: false,
19
+ error: 'Formato inválido. La licencia debe tener el formato CSAR-XXXX-XXXX-XXXX',
20
+ };
21
+ }
22
+ const cached = readCache();
23
+ if (cached === normalized) {
24
+ return { valid: true };
25
+ }
26
+ try {
27
+ const controller = new AbortController();
28
+ const timeout = setTimeout(() => controller.abort(), 5000);
29
+ const response = await fetch(LICENSE_API, {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify({ license: normalized }),
33
+ signal: controller.signal,
34
+ });
35
+ clearTimeout(timeout);
36
+ if (!response.ok) {
37
+ return { valid: false, error: 'Licencia inválida o expirada' };
38
+ }
39
+ const data = (await response.json());
40
+ if (data.valid) {
41
+ writeCache(normalized);
42
+ return { valid: true };
43
+ }
44
+ return { valid: false, error: 'Licencia inválida o expirada' };
45
+ }
46
+ catch {
47
+ // Fail open: si la API no está disponible, aceptar la licencia
48
+ writeCache(normalized);
49
+ return { valid: true };
50
+ }
51
+ }
52
+ function readCache() {
53
+ try {
54
+ if (fs_1.default.existsSync(CACHE_FILE)) {
55
+ return fs_1.default.readFileSync(CACHE_FILE, 'utf-8').trim();
56
+ }
57
+ }
58
+ catch {
59
+ // ignore
60
+ }
61
+ return null;
62
+ }
63
+ function writeCache(license) {
64
+ try {
65
+ fs_1.default.mkdirSync(CACHE_DIR, { recursive: true });
66
+ fs_1.default.writeFileSync(CACHE_FILE, license, 'utf-8');
67
+ }
68
+ catch {
69
+ // ignore — no bloquear al usuario si no se puede escribir la caché
70
+ }
71
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "ar-saas",
3
+ "version": "0.1.0",
4
+ "description": "Generador de proyectos SaaS multi-tenant para startups argentinas",
5
+ "main": "dist/index.js",
6
+ "bin": {
7
+ "ar-saas": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist/",
11
+ "templates/"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "dev": "tsx src/index.ts",
16
+ "sync-templates": "tsx scripts/sync-templates.ts",
17
+ "prepublishOnly": "npm run sync-templates && npm run build"
18
+ },
19
+ "keywords": [
20
+ "saas",
21
+ "nestjs",
22
+ "nextjs",
23
+ "argentina",
24
+ "cli",
25
+ "generator",
26
+ "multi-tenant"
27
+ ],
28
+ "author": "ignacio.becher@gmail.com",
29
+ "license": "MIT",
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ },
33
+ "dependencies": {
34
+ "chalk": "4.1.2",
35
+ "fs-extra": "^11.2.0",
36
+ "inquirer": "8.2.6",
37
+ "ora": "5.4.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/fs-extra": "^11.0.0",
41
+ "@types/inquirer": "^8.2.12",
42
+ "@types/node": "^20.0.0",
43
+ "tsx": "^4.7.0",
44
+ "typescript": "^5.4.0"
45
+ }
46
+ }
@@ -0,0 +1,67 @@
1
+ # =========================================
2
+ # create-saas-ar Backend
3
+ # Variables de entorno
4
+ # =========================================
5
+ # Copiá este archivo a .env y completá los valores
6
+ # =========================================
7
+
8
+ # ===== Aplicación =====
9
+ # Entorno: development | production | test
10
+ NODE_ENV=development
11
+
12
+ # Puerto donde corre el servidor
13
+ PORT=3000
14
+
15
+ # Prefijo para todas las rutas de la API
16
+ API_PREFIX=api
17
+
18
+ # ===== MongoDB =====
19
+ # URI de conexión a MongoDB
20
+ # Desarrollo local: mongodb://localhost:27017/saas-ar
21
+ # Atlas: mongodb+srv://user:pass@cluster.xxx.mongodb.net/saas-ar
22
+ # Con replica set (para transacciones): mongodb://localhost:27017/saas-ar?replicaSet=rs0
23
+ MONGODB_URI=mongodb://localhost:27017/saas-ar
24
+
25
+ # ===== JWT =====
26
+ # Secreto para firmar access tokens (usar openssl rand -hex 64 para generar)
27
+ JWT_ACCESS_SECRET=cambiar-por-secreto-seguro
28
+
29
+ # Duración del access token (formato: 15m, 1h, 7d)
30
+ JWT_ACCESS_EXPIRES_IN=15m
31
+
32
+ # Secreto para firmar refresh tokens
33
+ JWT_REFRESH_SECRET=cambiar-por-secreto-seguro
34
+
35
+ # Duración del refresh token (formato: 15m, 1h, 7d)
36
+ JWT_REFRESH_EXPIRES_IN=7d
37
+
38
+ # ===== Email (Resend) =====
39
+ # API Key de Resend (https://resend.com/api-keys)
40
+ RESEND_API_KEY=re_cambiar_por_api_key
41
+
42
+ # Email remitente (debe estar verificado en Resend)
43
+ RESEND_FROM_EMAIL=noreply@tuapp.com
44
+
45
+ # Nombre del remitente que ve el destinatario
46
+ RESEND_FROM_NAME="Tu App"
47
+
48
+ # ===== App URL =====
49
+ # URL del frontend (para links en emails de verificación, reset, etc)
50
+ APP_URL=http://localhost:5173
51
+
52
+ # ===== Swagger =====
53
+ # Habilitar documentación Swagger en /api/docs (solo development)
54
+ SWAGGER_ENABLED=true
55
+
56
+ # ===== CORS =====
57
+ # Orígenes permitidos (separados por coma)
58
+ CORS_ORIGINS=http://localhost:3001
59
+
60
+ # ===== Rate Limiting =====
61
+ # Cantidad máxima de requests por ventana de tiempo
62
+ THROTTLE_TTL=60
63
+ THROTTLE_LIMIT=100
64
+
65
+ # ===== Cookies =====
66
+ # Secreto para firmar cookies (usar openssl rand -hex 32 para generar)
67
+ COOKIE_SECRET=cambiar-por-secreto-seguro
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "all"
4
+ }