create-fs-app 2.0.5 → 3.0.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.
- package/LICENSE +15 -0
- package/README.md +254 -150
- package/dist/cli/output.js +223 -0
- package/dist/cli/program.js +403 -0
- package/dist/cli/resolve-config.js +264 -0
- package/dist/cli/ui/errors.js +27 -0
- package/dist/cli/ui/help.js +43 -0
- package/dist/cli/ui/hints.js +22 -0
- package/dist/cli/ui/layer-log.js +109 -0
- package/dist/cli/ui/list.js +115 -0
- package/dist/cli/ui/text.js +56 -0
- package/dist/cli/wizard.js +275 -0
- package/dist/core/auth/jwt.js +478 -0
- package/dist/core/download.js +109 -0
- package/dist/core/health-check.js +42 -44
- package/dist/core/presets.js +75 -117
- package/dist/core/registry-fetch.js +101 -81
- package/dist/core/registry.fallback.json +892 -0
- package/dist/core/scaffold.js +121 -75
- package/dist/core/stack.js +109 -0
- package/dist/core/template-cache.js +95 -154
- package/dist/core/template-clone.js +351 -655
- package/dist/core/template-list.js +19 -141
- package/dist/core/template-registry.js +116 -216
- package/dist/index.js +13 -963
- package/dist/types/index.js +30 -82
- package/dist/utils/cli-error.js +15 -0
- package/dist/utils/exec.js +62 -0
- package/dist/utils/logger.js +10 -9
- package/dist/utils/theme.js +87 -0
- package/dist/utils/validation.js +24 -13
- package/package.json +22 -25
- package/dist/core/health-check.d.ts +0 -15
- package/dist/core/health-check.js.map +0 -1
- package/dist/core/presets.d.ts +0 -48
- package/dist/core/presets.js.map +0 -1
- package/dist/core/registry-fetch.d.ts +0 -20
- package/dist/core/registry-fetch.js.map +0 -1
- package/dist/core/scaffold.d.ts +0 -40
- package/dist/core/scaffold.js.map +0 -1
- package/dist/core/template-cache.d.ts +0 -38
- package/dist/core/template-cache.js.map +0 -1
- package/dist/core/template-clone.d.ts +0 -27
- package/dist/core/template-clone.js.map +0 -1
- package/dist/core/template-list.d.ts +0 -45
- package/dist/core/template-list.js.map +0 -1
- package/dist/core/template-registry.d.ts +0 -78
- package/dist/core/template-registry.js.map +0 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js.map +0 -1
- package/dist/types/index.d.ts +0 -102
- package/dist/types/index.js.map +0 -1
- package/dist/utils/errors.d.ts +0 -15
- package/dist/utils/errors.js +0 -50
- package/dist/utils/errors.js.map +0 -1
- package/dist/utils/logger.d.ts +0 -37
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/validation.d.ts +0 -48
- package/dist/utils/validation.js.map +0 -1
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JWT auth scaffolding for generated backends (NestJS and Express).
|
|
3
|
+
*
|
|
4
|
+
* Generated code never trusts the request: POST /auth/login verifies the
|
|
5
|
+
* credentials against AUTH_USER_EMAIL / AUTH_USER_PASSWORD_HASH (scrypt, via
|
|
6
|
+
* node:crypto), and the backend refuses to start without JWT_SECRET.
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'fs/promises';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { Logger } from '../../utils/logger.js';
|
|
11
|
+
/** Backends that get JWT auth. Keep in sync with scripts/e2e-templates.mjs. */
|
|
12
|
+
export const AUTH_SUPPORT = ['nest.js', 'express'];
|
|
13
|
+
export function supportsAuth(backend) {
|
|
14
|
+
return AUTH_SUPPORT.includes(backend ?? '');
|
|
15
|
+
}
|
|
16
|
+
// ── Shared sources ────────────────────────────────────────────────────────────
|
|
17
|
+
const CREDENTIALS_TS = `import { scrypt, timingSafeEqual } from 'crypto';
|
|
18
|
+
import { promisify } from 'util';
|
|
19
|
+
|
|
20
|
+
// Async scrypt: hashing does not block the event loop on every login attempt
|
|
21
|
+
const scryptAsync = promisify(scrypt) as (password: string, salt: Buffer, keylen: number) => Promise<Buffer>;
|
|
22
|
+
|
|
23
|
+
export interface AuthUser {
|
|
24
|
+
id: string;
|
|
25
|
+
email: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface AuthTokenPayload {
|
|
29
|
+
sub: string;
|
|
30
|
+
email: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Read JWT_SECRET; the backend must not start without it. */
|
|
34
|
+
export function getJwtSecret(): string {
|
|
35
|
+
const secret = process.env.JWT_SECRET;
|
|
36
|
+
if (!secret) {
|
|
37
|
+
throw new Error('JWT_SECRET is not set. Add it to apps/backend/.env (e.g. openssl rand -hex 32).');
|
|
38
|
+
}
|
|
39
|
+
return secret;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Check an email/password pair against AUTH_USER_EMAIL and
|
|
44
|
+
* AUTH_USER_PASSWORD_HASH ("scrypt:<saltHex>:<hashHex>", created with
|
|
45
|
+
* \`npm run auth:hash-password -- <password>\`). Resolves to null when they do not match.
|
|
46
|
+
*
|
|
47
|
+
* Replace this with a lookup in your users table when you add real accounts.
|
|
48
|
+
*/
|
|
49
|
+
export async function verifyCredentials(email: string, password: string): Promise<AuthUser | null> {
|
|
50
|
+
const userEmail = process.env.AUTH_USER_EMAIL?.trim().toLowerCase();
|
|
51
|
+
const stored = process.env.AUTH_USER_PASSWORD_HASH?.trim();
|
|
52
|
+
if (!userEmail || !stored) return null;
|
|
53
|
+
|
|
54
|
+
const [scheme, saltHex, hashHex] = stored.split(':');
|
|
55
|
+
if (scheme !== 'scrypt' || !saltHex || !hashHex) return null;
|
|
56
|
+
|
|
57
|
+
const expected = Buffer.from(hashHex, 'hex');
|
|
58
|
+
if (expected.length === 0) return null;
|
|
59
|
+
const actual = await scryptAsync(password, Buffer.from(saltHex, 'hex'), expected.length);
|
|
60
|
+
const passwordOk = timingSafeEqual(actual, expected);
|
|
61
|
+
|
|
62
|
+
if (!passwordOk || email.trim().toLowerCase() !== userEmail) return null;
|
|
63
|
+
return { id: userEmail, email: userEmail };
|
|
64
|
+
}
|
|
65
|
+
`;
|
|
66
|
+
const HASH_PASSWORD_MJS = `#!/usr/bin/env node
|
|
67
|
+
// Prints a value for AUTH_USER_PASSWORD_HASH.
|
|
68
|
+
// Usage: npm run auth:hash-password -- <password>
|
|
69
|
+
import { randomBytes, scryptSync } from 'node:crypto';
|
|
70
|
+
|
|
71
|
+
const password = process.argv.slice(2).find((arg) => arg !== '--');
|
|
72
|
+
if (!password) {
|
|
73
|
+
console.error('Usage: npm run auth:hash-password -- <password>');
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const salt = randomBytes(16);
|
|
78
|
+
const hash = scryptSync(password, salt, 64);
|
|
79
|
+
console.log(\`scrypt:\${salt.toString('hex')}:\${hash.toString('hex')}\`);
|
|
80
|
+
`;
|
|
81
|
+
// ── NestJS ────────────────────────────────────────────────────────────────────
|
|
82
|
+
const NEST_AUTH_MODULE = `import { Module } from '@nestjs/common';
|
|
83
|
+
import { JwtModule } from '@nestjs/jwt';
|
|
84
|
+
import { AuthController } from './auth.controller';
|
|
85
|
+
import { AuthService } from './auth.service';
|
|
86
|
+
import { JwtAuthGuard } from './jwt-auth.guard';
|
|
87
|
+
import { getJwtSecret } from './credentials';
|
|
88
|
+
|
|
89
|
+
@Module({
|
|
90
|
+
imports: [
|
|
91
|
+
JwtModule.register({
|
|
92
|
+
secret: getJwtSecret(),
|
|
93
|
+
signOptions: { expiresIn: '7d', algorithm: 'HS256' },
|
|
94
|
+
verifyOptions: { algorithms: ['HS256'] },
|
|
95
|
+
}),
|
|
96
|
+
],
|
|
97
|
+
controllers: [AuthController],
|
|
98
|
+
providers: [AuthService, JwtAuthGuard],
|
|
99
|
+
exports: [AuthService, JwtAuthGuard, JwtModule],
|
|
100
|
+
})
|
|
101
|
+
export class AuthModule {}
|
|
102
|
+
`;
|
|
103
|
+
const NEST_AUTH_SERVICE = `import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
104
|
+
import { JwtService } from '@nestjs/jwt';
|
|
105
|
+
import { AuthTokenPayload, verifyCredentials } from './credentials';
|
|
106
|
+
|
|
107
|
+
@Injectable()
|
|
108
|
+
export class AuthService {
|
|
109
|
+
constructor(private readonly jwtService: JwtService) {}
|
|
110
|
+
|
|
111
|
+
async login(email: string, password: string): Promise<{ access_token: string }> {
|
|
112
|
+
const user = await verifyCredentials(email, password);
|
|
113
|
+
if (!user) {
|
|
114
|
+
throw new UnauthorizedException('Invalid email or password');
|
|
115
|
+
}
|
|
116
|
+
const payload: AuthTokenPayload = { sub: user.id, email: user.email };
|
|
117
|
+
return { access_token: await this.jwtService.signAsync(payload) };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
`;
|
|
121
|
+
const NEST_JWT_GUARD = `import {
|
|
122
|
+
CanActivate,
|
|
123
|
+
ExecutionContext,
|
|
124
|
+
Injectable,
|
|
125
|
+
UnauthorizedException,
|
|
126
|
+
} from '@nestjs/common';
|
|
127
|
+
import { JwtService } from '@nestjs/jwt';
|
|
128
|
+
import type { Request } from 'express';
|
|
129
|
+
import type { AuthTokenPayload } from './credentials';
|
|
130
|
+
|
|
131
|
+
export interface AuthenticatedRequest extends Request {
|
|
132
|
+
user?: AuthTokenPayload;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Requires "Authorization: Bearer <token>"; sets request.user. */
|
|
136
|
+
@Injectable()
|
|
137
|
+
export class JwtAuthGuard implements CanActivate {
|
|
138
|
+
constructor(private readonly jwtService: JwtService) {}
|
|
139
|
+
|
|
140
|
+
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
141
|
+
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
|
142
|
+
const header = request.headers.authorization ?? '';
|
|
143
|
+
const token = header.startsWith('Bearer ') ? header.slice(7) : '';
|
|
144
|
+
if (!token) {
|
|
145
|
+
throw new UnauthorizedException('Missing Authorization header');
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
request.user = await this.jwtService.verifyAsync<AuthTokenPayload>(token);
|
|
149
|
+
} catch {
|
|
150
|
+
throw new UnauthorizedException('Invalid or expired token');
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
`;
|
|
156
|
+
const NEST_AUTH_CONTROLLER = `import {
|
|
157
|
+
Body,
|
|
158
|
+
Controller,
|
|
159
|
+
Get,
|
|
160
|
+
HttpCode,
|
|
161
|
+
HttpStatus,
|
|
162
|
+
Post,
|
|
163
|
+
Req,
|
|
164
|
+
UseGuards,
|
|
165
|
+
} from '@nestjs/common';
|
|
166
|
+
import {
|
|
167
|
+
ApiBearerAuth,
|
|
168
|
+
ApiOperation,
|
|
169
|
+
ApiProperty,
|
|
170
|
+
ApiTags,
|
|
171
|
+
} from '@nestjs/swagger';
|
|
172
|
+
import { Throttle } from '@nestjs/throttler';
|
|
173
|
+
import { IsEmail, IsString, MinLength } from 'class-validator';
|
|
174
|
+
import { AuthService } from './auth.service';
|
|
175
|
+
import { JwtAuthGuard } from './jwt-auth.guard';
|
|
176
|
+
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
|
177
|
+
|
|
178
|
+
export class LoginDto {
|
|
179
|
+
@ApiProperty()
|
|
180
|
+
@IsEmail()
|
|
181
|
+
email!: string;
|
|
182
|
+
|
|
183
|
+
@ApiProperty()
|
|
184
|
+
@IsString()
|
|
185
|
+
@MinLength(1)
|
|
186
|
+
password!: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
@ApiTags('auth')
|
|
190
|
+
@Controller('auth')
|
|
191
|
+
export class AuthController {
|
|
192
|
+
constructor(private readonly authService: AuthService) {}
|
|
193
|
+
|
|
194
|
+
// Stricter than the default limit: every attempt costs one scrypt hash.
|
|
195
|
+
// Applied by the global ThrottlerGuard in app.module.ts.
|
|
196
|
+
@Post('login')
|
|
197
|
+
@Throttle({
|
|
198
|
+
default: {
|
|
199
|
+
limit: Number(process.env.AUTH_RATE_LIMIT_MAX) || 5,
|
|
200
|
+
ttl: Number(process.env.AUTH_RATE_LIMIT_WINDOW_MS) || 15 * 60_000,
|
|
201
|
+
},
|
|
202
|
+
})
|
|
203
|
+
@HttpCode(HttpStatus.OK)
|
|
204
|
+
@ApiOperation({ summary: 'Log in and receive a JWT' })
|
|
205
|
+
login(@Body() dto: LoginDto) {
|
|
206
|
+
return this.authService.login(dto.email, dto.password);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
@Get('me')
|
|
210
|
+
@UseGuards(JwtAuthGuard)
|
|
211
|
+
@ApiBearerAuth()
|
|
212
|
+
@ApiOperation({ summary: 'Return the user from the JWT' })
|
|
213
|
+
me(@Req() req: AuthenticatedRequest) {
|
|
214
|
+
return { user: req.user };
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
`;
|
|
218
|
+
// ── Express ───────────────────────────────────────────────────────────────────
|
|
219
|
+
const EXPRESS_JWT = `import jwt from 'jsonwebtoken';
|
|
220
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
221
|
+
import { AuthTokenPayload, getJwtSecret } from './credentials';
|
|
222
|
+
|
|
223
|
+
// Read at startup: the backend does not start without JWT_SECRET
|
|
224
|
+
const JWT_SECRET = getJwtSecret();
|
|
225
|
+
|
|
226
|
+
export function signToken(payload: AuthTokenPayload): string {
|
|
227
|
+
return jwt.sign(payload, JWT_SECRET, { expiresIn: '7d', algorithm: 'HS256' });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Throws when the token is invalid, expired, or has an unexpected payload. */
|
|
231
|
+
export function verifyToken(token: string): AuthTokenPayload {
|
|
232
|
+
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
|
|
233
|
+
if (typeof decoded === 'string' || typeof decoded.sub !== 'string' || typeof decoded.email !== 'string') {
|
|
234
|
+
throw new Error('Invalid token payload');
|
|
235
|
+
}
|
|
236
|
+
return { sub: decoded.sub, email: decoded.email };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Requires "Authorization: Bearer <token>"; sets res.locals.user. */
|
|
240
|
+
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
|
|
241
|
+
const header = req.headers.authorization ?? '';
|
|
242
|
+
const token = header.startsWith('Bearer ') ? header.slice(7) : '';
|
|
243
|
+
if (!token) {
|
|
244
|
+
res.status(401).json({ message: 'Missing Authorization header' });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
try {
|
|
248
|
+
res.locals.user = verifyToken(token);
|
|
249
|
+
next();
|
|
250
|
+
} catch {
|
|
251
|
+
res.status(401).json({ message: 'Invalid or expired token' });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
`;
|
|
255
|
+
const EXPRESS_ROUTES = `import { Router } from 'express';
|
|
256
|
+
import { rateLimit } from 'express-rate-limit';
|
|
257
|
+
import { z } from 'zod';
|
|
258
|
+
import { verifyCredentials } from '../auth/credentials';
|
|
259
|
+
import { requireAuth, signToken } from '../auth/jwt';
|
|
260
|
+
|
|
261
|
+
export const authRouter = Router();
|
|
262
|
+
|
|
263
|
+
const LoginSchema = z.object({ email: z.string().email(), password: z.string().min(1) });
|
|
264
|
+
|
|
265
|
+
// Stricter than the app-wide limit: every attempt costs one scrypt hash
|
|
266
|
+
const loginLimiter = rateLimit({
|
|
267
|
+
windowMs: Number(process.env.AUTH_RATE_LIMIT_WINDOW_MS) || 15 * 60_000,
|
|
268
|
+
limit: Number(process.env.AUTH_RATE_LIMIT_MAX) || 5,
|
|
269
|
+
standardHeaders: 'draft-6',
|
|
270
|
+
legacyHeaders: false,
|
|
271
|
+
message: { message: 'Too many login attempts, please try again later.' },
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// Express 4 does not catch rejected promises: pass errors to the error handler
|
|
275
|
+
authRouter.post('/login', loginLimiter, async (req, res, next) => {
|
|
276
|
+
try {
|
|
277
|
+
const { email, password } = LoginSchema.parse(req.body);
|
|
278
|
+
const user = await verifyCredentials(email, password);
|
|
279
|
+
if (!user) {
|
|
280
|
+
res.status(401).json({ message: 'Invalid email or password' });
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
res.json({ access_token: signToken({ sub: user.id, email: user.email }) });
|
|
284
|
+
} catch (error) {
|
|
285
|
+
next(error);
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
authRouter.get('/me', requireAuth, (_req, res) => {
|
|
290
|
+
res.json({ user: res.locals.user });
|
|
291
|
+
});
|
|
292
|
+
`;
|
|
293
|
+
// ── Plans ─────────────────────────────────────────────────────────────────────
|
|
294
|
+
const SHARED_FILES = {
|
|
295
|
+
'apps/backend/scripts/hash-password.mjs': HASH_PASSWORD_MJS,
|
|
296
|
+
};
|
|
297
|
+
function planFor(backend) {
|
|
298
|
+
if (backend === 'nest.js') {
|
|
299
|
+
return {
|
|
300
|
+
files: {
|
|
301
|
+
'apps/backend/src/auth/credentials.ts': CREDENTIALS_TS,
|
|
302
|
+
'apps/backend/src/auth/auth.module.ts': NEST_AUTH_MODULE,
|
|
303
|
+
'apps/backend/src/auth/auth.service.ts': NEST_AUTH_SERVICE,
|
|
304
|
+
'apps/backend/src/auth/auth.controller.ts': NEST_AUTH_CONTROLLER,
|
|
305
|
+
'apps/backend/src/auth/jwt-auth.guard.ts': NEST_JWT_GUARD,
|
|
306
|
+
...SHARED_FILES,
|
|
307
|
+
},
|
|
308
|
+
// The official templates already have @nestjs/throttler; the login route's @Throttle needs it
|
|
309
|
+
dependencies: { '@nestjs/jwt': '^11.0.2', '@nestjs/throttler': '^6.8.0' },
|
|
310
|
+
devDependencies: {},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
return {
|
|
314
|
+
files: {
|
|
315
|
+
'apps/backend/src/auth/credentials.ts': CREDENTIALS_TS,
|
|
316
|
+
'apps/backend/src/auth/jwt.ts': EXPRESS_JWT,
|
|
317
|
+
'apps/backend/src/routes/auth.ts': EXPRESS_ROUTES,
|
|
318
|
+
...SHARED_FILES,
|
|
319
|
+
},
|
|
320
|
+
// The official templates already have express-rate-limit; the login limiter needs it
|
|
321
|
+
dependencies: { 'express-rate-limit': '^8.7.5', jsonwebtoken: '^9.0.2' },
|
|
322
|
+
devDependencies: { '@types/jsonwebtoken': '^9.0.7' },
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
const ENV_BLOCK = `
|
|
326
|
+
# JWT auth (see README "Authentication")
|
|
327
|
+
JWT_SECRET=
|
|
328
|
+
AUTH_USER_EMAIL=
|
|
329
|
+
AUTH_USER_PASSWORD_HASH=
|
|
330
|
+
# POST /auth/login: attempts per client IP per window
|
|
331
|
+
AUTH_RATE_LIMIT_MAX=5
|
|
332
|
+
AUTH_RATE_LIMIT_WINDOW_MS=900000
|
|
333
|
+
`;
|
|
334
|
+
/** Files generateJwtAuth writes, relative to the project root. */
|
|
335
|
+
export function jwtFiles(backend) {
|
|
336
|
+
return Object.keys(planFor(backend).files);
|
|
337
|
+
}
|
|
338
|
+
/** What generateJwtAuth changes, for --dry-run. */
|
|
339
|
+
export function describeJwtAuth(backend) {
|
|
340
|
+
const plan = planFor(backend);
|
|
341
|
+
const deps = { ...plan.dependencies, ...plan.devDependencies };
|
|
342
|
+
const wiring = backend === 'nest.js' ? 'apps/backend/src/app.module.ts' : 'apps/backend/src/app.ts';
|
|
343
|
+
return [
|
|
344
|
+
`Add JWT auth files: ${Object.keys(plan.files).join(', ')}`,
|
|
345
|
+
`Add backend dependencies: ${Object.entries(deps).map(([n, v]) => `${n}@${v}`).join(', ')}`,
|
|
346
|
+
`Wire /auth routes into ${wiring}`,
|
|
347
|
+
'Rate limit POST /auth/login to 5 attempts per 15 minutes per client IP (AUTH_RATE_LIMIT_MAX, AUTH_RATE_LIMIT_WINDOW_MS)',
|
|
348
|
+
'Add JWT_SECRET, AUTH_USER_EMAIL, AUTH_USER_PASSWORD_HASH, AUTH_RATE_LIMIT_MAX, AUTH_RATE_LIMIT_WINDOW_MS to apps/backend/.env.example',
|
|
349
|
+
'Append an "Authentication" section to README.md',
|
|
350
|
+
];
|
|
351
|
+
}
|
|
352
|
+
// ── Generation ────────────────────────────────────────────────────────────────
|
|
353
|
+
async function readIfExists(file) {
|
|
354
|
+
try {
|
|
355
|
+
return await fs.readFile(file, 'utf-8');
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/** Insert an import after the last top-level import statement. */
|
|
362
|
+
function addImport(source, importLine) {
|
|
363
|
+
const matches = [...source.matchAll(/^import [^;]+;\n/gm)];
|
|
364
|
+
const last = matches.at(-1);
|
|
365
|
+
if (!last || last.index === undefined)
|
|
366
|
+
return `${importLine}\n${source}`;
|
|
367
|
+
const at = last.index + last[0].length;
|
|
368
|
+
return source.slice(0, at) + importLine + '\n' + source.slice(at);
|
|
369
|
+
}
|
|
370
|
+
async function wireNest(targetDir) {
|
|
371
|
+
const file = path.join(targetDir, 'apps', 'backend', 'src', 'app.module.ts');
|
|
372
|
+
const source = await readIfExists(file);
|
|
373
|
+
if (source === null || !/imports:\s*\[/.test(source)) {
|
|
374
|
+
Logger.warn('Could not find the imports array in apps/backend/src/app.module.ts; add AuthModule there yourself.');
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (source.includes('AuthModule'))
|
|
378
|
+
return;
|
|
379
|
+
let next = addImport(source, "import { AuthModule } from './auth/auth.module';");
|
|
380
|
+
next = next.replace(/imports:\s*\[/, 'imports: [AuthModule, ');
|
|
381
|
+
await fs.writeFile(file, next);
|
|
382
|
+
if (!source.includes('ThrottlerGuard')) {
|
|
383
|
+
Logger.warn('apps/backend/src/app.module.ts does not register ThrottlerGuard, so POST /auth/login is not rate limited; add ThrottlerModule and a global ThrottlerGuard (@nestjs/throttler).');
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
async function wireExpress(targetDir) {
|
|
387
|
+
const file = path.join(targetDir, 'apps', 'backend', 'src', 'app.ts');
|
|
388
|
+
const source = await readIfExists(file);
|
|
389
|
+
const errorHandlerLine = /^app\.use\(errorHandler\);$/m;
|
|
390
|
+
if (source === null || !errorHandlerLine.test(source)) {
|
|
391
|
+
Logger.warn("Could not find app.use(errorHandler) in apps/backend/src/app.ts; add app.use('/auth', authRouter) yourself.");
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (source.includes('authRouter'))
|
|
395
|
+
return;
|
|
396
|
+
let next = addImport(source, "import { authRouter } from './routes/auth';");
|
|
397
|
+
next = next.replace(errorHandlerLine, "app.use('/auth', authRouter);\napp.use(errorHandler);");
|
|
398
|
+
await fs.writeFile(file, next);
|
|
399
|
+
}
|
|
400
|
+
async function updateBackendPackage(targetDir, plan) {
|
|
401
|
+
const file = path.join(targetDir, 'apps', 'backend', 'package.json');
|
|
402
|
+
const raw = await readIfExists(file);
|
|
403
|
+
if (raw === null)
|
|
404
|
+
return;
|
|
405
|
+
const pkg = JSON.parse(raw);
|
|
406
|
+
pkg.scripts = { ...pkg.scripts, 'auth:hash-password': 'node scripts/hash-password.mjs' };
|
|
407
|
+
pkg.dependencies = { ...pkg.dependencies, ...plan.dependencies };
|
|
408
|
+
if (Object.keys(plan.devDependencies).length > 0) {
|
|
409
|
+
pkg.devDependencies = { ...pkg.devDependencies, ...plan.devDependencies };
|
|
410
|
+
}
|
|
411
|
+
await fs.writeFile(file, JSON.stringify(pkg, null, 2) + '\n');
|
|
412
|
+
}
|
|
413
|
+
async function updateEnvExample(targetDir) {
|
|
414
|
+
const file = path.join(targetDir, 'apps', 'backend', '.env.example');
|
|
415
|
+
const env = await readIfExists(file);
|
|
416
|
+
if (env === null) {
|
|
417
|
+
await fs.writeFile(file, ENV_BLOCK.trimStart());
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
if (env.includes('JWT_SECRET'))
|
|
421
|
+
return;
|
|
422
|
+
await fs.writeFile(file, env.replace(/\n*$/, '\n') + ENV_BLOCK);
|
|
423
|
+
}
|
|
424
|
+
function readmeSection(backend, pm) {
|
|
425
|
+
const credentialsFile = 'apps/backend/src/auth/credentials.ts';
|
|
426
|
+
const guard = backend === 'nest.js'
|
|
427
|
+
? 'Protect your own routes with `@UseGuards(JwtAuthGuard)` from `apps/backend/src/auth/jwt-auth.guard.ts`.'
|
|
428
|
+
: 'Protect your own routes with the `requireAuth` middleware from `apps/backend/src/auth/jwt.ts`.';
|
|
429
|
+
const loginLimit = backend === 'nest.js'
|
|
430
|
+
? 'with `@Throttle()` from `@nestjs/throttler` in `apps/backend/src/auth/auth.controller.ts` (applied by the global `ThrottlerGuard`)'
|
|
431
|
+
: 'with its own `express-rate-limit` limiter in `apps/backend/src/routes/auth.ts`';
|
|
432
|
+
return `
|
|
433
|
+
## Authentication
|
|
434
|
+
|
|
435
|
+
The backend includes JWT authentication: \`POST /auth/login\` returns a token, \`GET /auth/me\` requires it.
|
|
436
|
+
|
|
437
|
+
1. Set \`JWT_SECRET\` in \`apps/backend/.env\`, for example with \`openssl rand -hex 32\`. The backend does not start without it.
|
|
438
|
+
2. Set \`AUTH_USER_EMAIL\`, then create the password hash and put the printed value in \`AUTH_USER_PASSWORD_HASH\`:
|
|
439
|
+
\`\`\`bash
|
|
440
|
+
cd apps/backend && ${pm} run auth:hash-password -- 'your-password'
|
|
441
|
+
\`\`\`
|
|
442
|
+
3. Log in and call the protected route:
|
|
443
|
+
\`\`\`bash
|
|
444
|
+
curl -s -X POST http://localhost:3001/auth/login -H 'content-type: application/json' \\
|
|
445
|
+
-d '{"email":"you@example.com","password":"your-password"}'
|
|
446
|
+
curl -s http://localhost:3001/auth/me -H "Authorization: Bearer <access_token>"
|
|
447
|
+
\`\`\`
|
|
448
|
+
|
|
449
|
+
Every login attempt costs one scrypt hash, so \`POST /auth/login\` has a stricter rate limit than the rest of the API, by default 5 attempts per 15 minutes per client IP, set ${loginLimit}. Over the limit the backend answers \`429 Too Many Requests\` with \`Retry-After\`. Change the limit with \`AUTH_RATE_LIMIT_MAX\` and \`AUTH_RATE_LIMIT_WINDOW_MS\` (milliseconds) in \`apps/backend/.env\`. The limit counts every attempt, successful or not, and the client IP is resolved as described in "Rate limiting" (set \`TRUST_PROXY\` behind a proxy).
|
|
450
|
+
|
|
451
|
+
${guard} \`verifyCredentials()\` in \`${credentialsFile}\` checks the single user from the environment; replace it with a lookup in your users table (store scrypt or bcrypt hashes, never plain passwords) when you add real accounts.
|
|
452
|
+
`;
|
|
453
|
+
}
|
|
454
|
+
async function appendReadme(targetDir, backend, pm) {
|
|
455
|
+
const file = path.join(targetDir, 'README.md');
|
|
456
|
+
const readme = await readIfExists(file);
|
|
457
|
+
if (readme === null || readme.includes('## Authentication'))
|
|
458
|
+
return;
|
|
459
|
+
await fs.writeFile(file, readme.replace(/\n*$/, '\n') + readmeSection(backend, pm));
|
|
460
|
+
}
|
|
461
|
+
/** Add JWT auth to the backend of a scaffolded official/contributed template. */
|
|
462
|
+
export async function generateJwtAuth(targetDir, backend, packageManager) {
|
|
463
|
+
const plan = planFor(backend);
|
|
464
|
+
for (const [relative, content] of Object.entries(plan.files)) {
|
|
465
|
+
const file = path.join(targetDir, relative);
|
|
466
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
467
|
+
await fs.writeFile(file, content);
|
|
468
|
+
}
|
|
469
|
+
await updateBackendPackage(targetDir, plan);
|
|
470
|
+
await updateEnvExample(targetDir);
|
|
471
|
+
if (backend === 'nest.js') {
|
|
472
|
+
await wireNest(targetDir);
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
await wireExpress(targetDir);
|
|
476
|
+
}
|
|
477
|
+
await appendReadme(targetDir, backend, packageManager);
|
|
478
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template download from GitHub as a tarball (no git needed).
|
|
3
|
+
*
|
|
4
|
+
* https://codeload.github.com/<owner>/<repo>/tar.gz/<ref> is streamed through
|
|
5
|
+
* node-tar; only entries under <top>/<subfolder>/ are extracted, with the
|
|
6
|
+
* prefix stripped. node-tar rejects absolute paths and ".." entries.
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'fs/promises';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
11
|
+
import { Readable } from 'stream';
|
|
12
|
+
import { pipeline } from 'stream/promises';
|
|
13
|
+
import { CliError } from '../utils/cli-error.js';
|
|
14
|
+
const DOWNLOAD_TIMEOUT = 60_000;
|
|
15
|
+
/** A download failure: `reason` says what went wrong, `fix` what to use instead. */
|
|
16
|
+
export class DownloadError extends CliError {
|
|
17
|
+
constructor(reason, fix = '--local-templates <dir>') {
|
|
18
|
+
super('Could not download the template', { reason, fix });
|
|
19
|
+
this.name = 'DownloadError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function networkError(reason) {
|
|
23
|
+
return new DownloadError(`GitHub could not be reached (${reason}). Check your connection.`);
|
|
24
|
+
}
|
|
25
|
+
export function parseRepo(repoUrl) {
|
|
26
|
+
const match = repoUrl.match(/^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/);
|
|
27
|
+
if (!match)
|
|
28
|
+
throw new Error(`Not a GitHub repository URL: ${repoUrl}`);
|
|
29
|
+
return { owner: match[1], repo: match[2] };
|
|
30
|
+
}
|
|
31
|
+
export function tarballUrl(repoUrl, ref) {
|
|
32
|
+
const { owner, repo } = parseRepo(repoUrl);
|
|
33
|
+
return `https://codeload.github.com/${owner}/${repo}/tar.gz/${ref}`;
|
|
34
|
+
}
|
|
35
|
+
function normalizeSubfolder(subfolder) {
|
|
36
|
+
return (subfolder ?? '').split('/').filter(Boolean).join('/');
|
|
37
|
+
}
|
|
38
|
+
async function countEntries(dir) {
|
|
39
|
+
try {
|
|
40
|
+
return (await fs.readdir(dir)).length;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Download `source` and extract it into `destDir`, which must not exist yet.
|
|
48
|
+
* Extraction goes to a sibling temp dir first, so a failed download never
|
|
49
|
+
* leaves a partial `destDir` behind.
|
|
50
|
+
*/
|
|
51
|
+
export async function downloadTemplate(source, destDir) {
|
|
52
|
+
const { owner, repo } = parseRepo(source.repoUrl);
|
|
53
|
+
const label = `${owner}/${repo}@${source.ref}`;
|
|
54
|
+
const subfolder = normalizeSubfolder(source.subfolder);
|
|
55
|
+
const url = tarballUrl(source.repoUrl, source.ref);
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetch(url, {
|
|
59
|
+
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT),
|
|
60
|
+
headers: { 'User-Agent': 'create-fs-app' },
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
const reason = error instanceof Error
|
|
65
|
+
? (error.cause instanceof Error ? error.cause.message : error.message)
|
|
66
|
+
: String(error);
|
|
67
|
+
throw networkError(reason);
|
|
68
|
+
}
|
|
69
|
+
if (res.status === 404) {
|
|
70
|
+
throw new DownloadError(`Template source not found: ${label} (HTTP 404).\nIf the registry or branch was changed recently, it may not be pushed yet.`);
|
|
71
|
+
}
|
|
72
|
+
if (!res.ok || !res.body) {
|
|
73
|
+
throw networkError(`HTTP ${res.status}`);
|
|
74
|
+
}
|
|
75
|
+
// Loaded on demand so commands like --help never load tar
|
|
76
|
+
const tar = await import('tar');
|
|
77
|
+
const parent = path.dirname(destDir);
|
|
78
|
+
await fs.mkdir(parent, { recursive: true });
|
|
79
|
+
const tmpDir = path.join(parent, `.${path.basename(destDir)}.download-${randomUUID()}`);
|
|
80
|
+
await fs.mkdir(tmpDir);
|
|
81
|
+
// GitHub tarballs have one top-level directory: <repo>-<sha>/
|
|
82
|
+
const depth = subfolder ? subfolder.split('/').length : 0;
|
|
83
|
+
const prefix = subfolder ? `${subfolder}/` : '';
|
|
84
|
+
try {
|
|
85
|
+
try {
|
|
86
|
+
await pipeline(Readable.fromWeb(res.body), tar.x({
|
|
87
|
+
cwd: tmpDir,
|
|
88
|
+
strip: 1 + depth,
|
|
89
|
+
filter: (entryPath) => {
|
|
90
|
+
const rest = entryPath.split('/').slice(1).join('/');
|
|
91
|
+
return prefix === '' || rest.startsWith(prefix);
|
|
92
|
+
},
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
throw networkError(error instanceof Error ? error.message : String(error));
|
|
97
|
+
}
|
|
98
|
+
if ((await countEntries(tmpDir)) === 0) {
|
|
99
|
+
throw new DownloadError(subfolder
|
|
100
|
+
? `Folder "${subfolder}" not found in ${label}.`
|
|
101
|
+
: `Repository ${label} is empty.`, 'create-fs-app list');
|
|
102
|
+
}
|
|
103
|
+
await fs.rename(tmpDir, destDir);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|