create-tigra 4.1.0 → 5.0.1
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/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/create-tigra.js +68 -73
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +33 -59
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +18 -18
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +10 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +1 -24
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +18 -2
- package/modules/diagnostics/server/diagnostics.repo.ts +12 -2
- package/modules/diagnostics/server/diagnostics.routes.ts +1 -2
- package/modules/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +2 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +1 -0
- package/modules/metrics/performance.md +2 -2
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +22 -0
- package/modules/metrics/server/metrics.collector.ts +6 -3
- package/modules/metrics/server/metrics.routes.ts +1 -2
- package/modules/metrics/server/metrics.service.ts +6 -2
- package/package.json +1 -1
- package/template/AGENTS.md +4 -3
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- package/template/client/package-lock.json +51 -51
- package/template/client/package.json +2 -2
- package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,26 @@
|
|
|
3
3
|
A generated project never changes after it is created: these notes say what new projects get. To bring an older
|
|
4
4
|
project along, port the changes you need; the guides in [docs/](docs/) cover the ones that need care.
|
|
5
5
|
|
|
6
|
+
## 5.0.1 (2026-11-17)
|
|
7
|
+
|
|
8
|
+
- Pin Next.js and eslint-config-next to 16.4.6 in new projects. This includes the [security fixes released in Next.js 16.4.5](https://github.com/vercel/next.js/releases/tag/v16.4.5).
|
|
9
|
+
|
|
10
|
+
## 5.0.0 (2026-11-17)
|
|
11
|
+
|
|
12
|
+
### Compatibility
|
|
13
|
+
|
|
14
|
+
- The email-verification installer requires the new account transaction, mail queue, and client session code. Follow the [upgrade guide](docs/account-ban-vs-email-verification.md) before adding it to a 4.x project.
|
|
15
|
+
- The [server deployment guide](template/server/docs/deployment.md) describes the forward migrations and coordinated rollout for existing projects adopting session rotation, avatar cleanup, and account purge changes.
|
|
16
|
+
- Generated list endpoints cap page numbers at 1,000 and page sizes at 100. The admin and auth endpoints also enforce current account and session state during writes.
|
|
17
|
+
|
|
18
|
+
### Changes
|
|
19
|
+
|
|
20
|
+
- Queue password recovery and verification email in Redis. Make link issuance and redemption consistent across replicas, and commit credential revocation with account changes.
|
|
21
|
+
- Protect the last eligible admin, keep ordinary rate limits in place, and exempt authorized admin routes from quota counters and strikes.
|
|
22
|
+
- Keep browser sessions in sync across tabs and account switches. Prevent caching of authenticated responses and make avatar replacement and deletion visible on subsequent requests.
|
|
23
|
+
- Make scaffolding and optional module installation recoverable and keep local environment and build files out of the npm package. Test all eight combinations of email verification, metrics, and diagnostics in scaffold CI.
|
|
24
|
+
- Tighten outbound HTTP safeguards, health probes, and log redaction. Bound diagnostics queries and keep referrer and cookie data out of Web Vitals submissions.
|
|
25
|
+
|
|
6
26
|
## 4.1.0 (2026-11-10)
|
|
7
27
|
|
|
8
28
|
- Add optional performance metrics for Fastify requests, Node runtime health, named operations, and Next.js Web Vitals. The module stores five-minute aggregates in MySQL and provides a read-only admin API.
|
package/README.md
CHANGED
|
@@ -261,10 +261,13 @@ npx create-tigra add metrics
|
|
|
261
261
|
npx create-tigra add diagnostics
|
|
262
262
|
```
|
|
263
263
|
|
|
264
|
+
Run one module installer at a time per checkout. If it is interrupted, rerun the command after the prior process exits so the installer can recover before applying changes. If recovery reports an intervening edit, save that edit elsewhere and restore the named file to its pre-install or installer-written version before retrying.
|
|
265
|
+
|
|
264
266
|
The email verification module adds the routes (`POST /auth/send-verification`, `POST /auth/verify-account`), their integration
|
|
265
267
|
tests, the client's `useVerifyAccount` / `useSendVerification` hooks and service, and sets `REQUIRE_USER_VERIFICATION=true` in `server/.env`.
|
|
266
268
|
Then set `RESEND_API_KEY` in `server/.env` and restart the server. Answering "yes" to the email question when you
|
|
267
|
-
create a project does the same.
|
|
269
|
+
create a project does the same. The installer uses Tigra’s shared account transaction and Redis mail queue.
|
|
270
|
+
See the [email verification upgrade guide](docs/account-ban-vs-email-verification.md) for earlier projects.
|
|
268
271
|
|
|
269
272
|
The metrics module collects request and operation timings, Node runtime
|
|
270
273
|
measurements, and browser Web Vitals into five-minute MySQL buckets. Apply the
|
package/bin/create-tigra.js
CHANGED
|
@@ -8,6 +8,7 @@ import fs from 'fs-extra';
|
|
|
8
8
|
import path from 'path';
|
|
9
9
|
import { fileURLToPath } from 'url';
|
|
10
10
|
import crypto from 'crypto';
|
|
11
|
+
import { projectPath, stageScaffold } from '../lib/project-files.js';
|
|
11
12
|
|
|
12
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
13
14
|
const __dirname = path.dirname(__filename);
|
|
@@ -45,9 +46,7 @@ const SKIP_PATTERNS = [
|
|
|
45
46
|
'.next',
|
|
46
47
|
'dist',
|
|
47
48
|
'out',
|
|
48
|
-
'.
|
|
49
|
-
'.env.local',
|
|
50
|
-
'.env.*.local',
|
|
49
|
+
'.npmignore',
|
|
51
50
|
// package-lock.json is NOT skipped: new projects get the template's tested
|
|
52
51
|
// lockfiles, written with the npm in the Dockerfiles' image, so the first
|
|
53
52
|
// `npm ci` (locally and in Docker) installs exactly the versions we tested.
|
|
@@ -122,15 +121,11 @@ function appRuntimeWarnings() {
|
|
|
122
121
|
|
|
123
122
|
function shouldSkip(filePath) {
|
|
124
123
|
const parts = filePath.split(path.sep);
|
|
125
|
-
return parts.some((part) =>
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}
|
|
131
|
-
return part === pattern;
|
|
132
|
-
})
|
|
133
|
-
);
|
|
124
|
+
return parts.some((part) => {
|
|
125
|
+
const name = part.toLowerCase();
|
|
126
|
+
return SKIP_PATTERNS.includes(name) ||
|
|
127
|
+
(/^\.env(?:\.|$)/.test(name) && !['.env.example', '.env.example.production'].includes(part));
|
|
128
|
+
});
|
|
134
129
|
}
|
|
135
130
|
|
|
136
131
|
async function copyTemplate(templateDir, targetDir) {
|
|
@@ -152,10 +147,14 @@ async function copyTemplate(templateDir, targetDir) {
|
|
|
152
147
|
const destPath = path.join(targetDir, destName);
|
|
153
148
|
|
|
154
149
|
if (entry.isDirectory()) {
|
|
155
|
-
await
|
|
150
|
+
await projectPath(targetDir, destName, 'directory');
|
|
151
|
+
await fs.mkdir(destPath);
|
|
156
152
|
await copyTemplate(srcPath, destPath);
|
|
153
|
+
} else if (entry.isFile()) {
|
|
154
|
+
await projectPath(targetDir, destName, 'file');
|
|
155
|
+
await fs.copyFile(srcPath, destPath, fs.constants.COPYFILE_EXCL);
|
|
157
156
|
} else {
|
|
158
|
-
|
|
157
|
+
throw new Error(`Unsupported scaffold template entry: ${relativePath}`);
|
|
159
158
|
}
|
|
160
159
|
}
|
|
161
160
|
}
|
|
@@ -214,11 +213,11 @@ function registerAddCommand(program) {
|
|
|
214
213
|
console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
|
|
215
214
|
console.log();
|
|
216
215
|
|
|
217
|
-
const projectDir = process.cwd();
|
|
216
|
+
const projectDir = await fs.realpath(process.cwd());
|
|
218
217
|
|
|
219
218
|
// Detect if we're inside a Tigra project
|
|
220
|
-
const hasServer = await
|
|
221
|
-
const hasClient = await
|
|
219
|
+
const { stat: hasServer } = await projectPath(projectDir, 'server/src/modules/auth', 'directory');
|
|
220
|
+
const { stat: hasClient } = await projectPath(projectDir, 'client/src/features/auth', 'directory');
|
|
222
221
|
|
|
223
222
|
if (!hasServer || !hasClient) {
|
|
224
223
|
console.error(chalk.red(' This does not appear to be a Tigra project.'));
|
|
@@ -274,16 +273,6 @@ function registerAddCommand(program) {
|
|
|
274
273
|
}
|
|
275
274
|
|
|
276
275
|
if (moduleName === 'email-verification') {
|
|
277
|
-
// Check if already applied
|
|
278
|
-
const alreadyApplied = await fs.pathExists(
|
|
279
|
-
path.join(projectDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
|
|
280
|
-
);
|
|
281
|
-
if (alreadyApplied) {
|
|
282
|
-
console.log(chalk.yellow(' Email verification is already installed in this project.'));
|
|
283
|
-
console.log();
|
|
284
|
-
process.exit(0);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
276
|
const spinner = ora('Adding email verification module...').start();
|
|
288
277
|
|
|
289
278
|
try {
|
|
@@ -292,7 +281,11 @@ function registerAddCommand(program) {
|
|
|
292
281
|
);
|
|
293
282
|
// Also switches REQUIRE_USER_VERIFICATION on (env.ts default + every
|
|
294
283
|
// server env file), exactly as at scaffold time.
|
|
295
|
-
await applyEmailVerificationModule(projectDir);
|
|
284
|
+
const installed = await applyEmailVerificationModule(projectDir);
|
|
285
|
+
if (!installed) {
|
|
286
|
+
spinner.succeed('Email verification is already installed in this project.');
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
296
289
|
|
|
297
290
|
spinner.succeed('Email verification module added!');
|
|
298
291
|
} catch (error) {
|
|
@@ -313,7 +306,7 @@ function registerAddCommand(program) {
|
|
|
313
306
|
console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
|
|
314
307
|
console.log();
|
|
315
308
|
console.log(green(' ✓ ') + 'Files patched:');
|
|
316
|
-
console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts,
|
|
309
|
+
console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, jobs/index.ts'));
|
|
317
310
|
console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
|
|
318
311
|
console.log(dim(' postman/collection.json'));
|
|
319
312
|
console.log();
|
|
@@ -373,10 +366,11 @@ async function main() {
|
|
|
373
366
|
|
|
374
367
|
projectName = toKebabCase(projectName);
|
|
375
368
|
|
|
376
|
-
const
|
|
369
|
+
const parent = await fs.realpath(process.cwd());
|
|
370
|
+
const { file: targetDir, stat: targetStat } = await projectPath(parent, projectName, 'directory');
|
|
377
371
|
|
|
378
372
|
// Check if directory exists and is non-empty
|
|
379
|
-
if (
|
|
373
|
+
if (targetStat) {
|
|
380
374
|
const files = await fs.readdir(targetDir);
|
|
381
375
|
if (files.length > 0) {
|
|
382
376
|
console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
|
|
@@ -439,52 +433,53 @@ async function main() {
|
|
|
439
433
|
const spinner = ora('Scaffolding project...').start();
|
|
440
434
|
|
|
441
435
|
try {
|
|
442
|
-
await
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
436
|
+
await stageScaffold(parent, projectName, async (stage) => {
|
|
437
|
+
await copyTemplate(TEMPLATE_DIR, stage);
|
|
438
|
+
|
|
439
|
+
// Replace template variables in specific files
|
|
440
|
+
for (const filePath of FILES_TO_REPLACE) {
|
|
441
|
+
const fullPath = path.join(stage, filePath);
|
|
442
|
+
if (await fs.pathExists(fullPath)) {
|
|
443
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
444
|
+
const replaced = replaceVariables(content, variables);
|
|
445
|
+
await fs.writeFile(fullPath, replaced, 'utf-8');
|
|
446
|
+
}
|
|
452
447
|
}
|
|
453
|
-
}
|
|
454
448
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
449
|
+
// Generate .env from .env.example (so users don't have to copy manually).
|
|
450
|
+
// The real JWT secret is injected HERE and only here — .env is
|
|
451
|
+
// git-ignored, while .env.example is committed and must keep the
|
|
452
|
+
// CHANGE_ME placeholder.
|
|
453
|
+
const jwtSecret = crypto.randomBytes(48).toString('hex');
|
|
454
|
+
for (const envExample of ['server/.env.example', 'client/.env.example']) {
|
|
455
|
+
const examplePath = path.join(stage, envExample);
|
|
456
|
+
const envPath = path.join(stage, envExample.replace('.env.example', '.env'));
|
|
457
|
+
if (await fs.pathExists(examplePath)) {
|
|
458
|
+
const content = await fs.readFile(examplePath, 'utf-8');
|
|
459
|
+
await fs.writeFile(
|
|
460
|
+
envPath,
|
|
461
|
+
content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
|
|
462
|
+
{ encoding: 'utf-8', mode: 0o600, flag: 'wx' },
|
|
463
|
+
);
|
|
464
|
+
}
|
|
470
465
|
}
|
|
471
|
-
}
|
|
472
466
|
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
467
|
+
// Apply email verification module if selected. The template ships with
|
|
468
|
+
// REQUIRE_USER_VERIFICATION off everywhere (no verify route without the
|
|
469
|
+
// module); the patcher switches it on in env.ts and every env file.
|
|
470
|
+
if (enableVerification) {
|
|
471
|
+
const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
|
|
472
|
+
await applyEmailVerificationModule(stage);
|
|
473
|
+
}
|
|
474
|
+
if (enableMetrics) {
|
|
475
|
+
const { applyMetricsModule } = await import('../lib/patchers/metrics.patcher.js');
|
|
476
|
+
await applyMetricsModule(stage);
|
|
477
|
+
}
|
|
478
|
+
if (enableDiagnostics) {
|
|
479
|
+
const { applyDiagnosticsModule } = await import('../lib/patchers/diagnostics.patcher.js');
|
|
480
|
+
await applyDiagnosticsModule(stage);
|
|
481
|
+
}
|
|
482
|
+
});
|
|
488
483
|
|
|
489
484
|
spinner.succeed('Project scaffolded successfully!');
|
|
490
485
|
} catch (error) {
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rmdir, rm, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createParents, INSTALL_PREFIX, INSTALL_STATE, pathParts, privateInstallerPath, projectPath } from './project-files.js';
|
|
5
|
+
|
|
6
|
+
const uuid = '[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}';
|
|
7
|
+
const ownerPattern = new RegExp(`^owner-([1-9][0-9]*)-${uuid}$`);
|
|
8
|
+
const journalPattern = new RegExp(`^${uuid}$`);
|
|
9
|
+
const digestPattern = /^[a-f0-9]{64}$/;
|
|
10
|
+
const hash = (buffer) => buffer === null ? null : createHash('sha256').update(buffer).digest('hex');
|
|
11
|
+
const folder = (file) => path.posix.dirname(file);
|
|
12
|
+
const stateFile = (file) => `${INSTALL_STATE}/${file}`;
|
|
13
|
+
|
|
14
|
+
function normalizedFile(relative) {
|
|
15
|
+
const parts = pathParts(relative);
|
|
16
|
+
if (parts.some((part) => part.toLowerCase().startsWith(INSTALL_PREFIX))) {
|
|
17
|
+
throw new Error('An installer plan cannot change installer state');
|
|
18
|
+
}
|
|
19
|
+
return parts.join('/');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function readSnapshot(root, file) {
|
|
23
|
+
const entry = await projectPath(root, file, 'file');
|
|
24
|
+
return entry.stat
|
|
25
|
+
? { before: await readFile(entry.file), mode: entry.stat.mode & 0o777 }
|
|
26
|
+
: { before: null, mode: null };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function ownerAlive(pid) {
|
|
30
|
+
try {
|
|
31
|
+
process.kill(pid, 0);
|
|
32
|
+
return true;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error.code === 'ESRCH') return false;
|
|
35
|
+
return true; // Insufficient permissions or ambiguous ownership must not steal a lock.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Publish a nonempty directory so no process can observe a lock without an owner.
|
|
40
|
+
* Recovery claims a dead owner's unique filename with one rename. */
|
|
41
|
+
async function takeLock(root) {
|
|
42
|
+
const mine = `owner-${process.pid}-${randomUUID()}`;
|
|
43
|
+
const candidate = privateInstallerPath(root, 'candidate');
|
|
44
|
+
await mkdir(candidate, { mode: 0o700 });
|
|
45
|
+
try {
|
|
46
|
+
await writeFile(path.join(candidate, mine), '', { flag: 'wx', mode: 0o600 });
|
|
47
|
+
const lock = await projectPath(root, INSTALL_STATE, 'directory');
|
|
48
|
+
if (!lock.stat) {
|
|
49
|
+
try {
|
|
50
|
+
await rename(candidate, lock.file);
|
|
51
|
+
return lock.file;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (!(await projectPath(root, INSTALL_STATE, 'directory')).stat) throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const owners = (await readdir(lock.file)).filter((entry) => entry.startsWith('owner-'));
|
|
58
|
+
const owner = owners.length === 1 && ownerPattern.exec(owners[0]);
|
|
59
|
+
const pid = Number(owner?.[1]);
|
|
60
|
+
if (!owner || !Number.isSafeInteger(pid) || pid > 0x7fffffff || ownerAlive(pid)) {
|
|
61
|
+
throw new Error('Another installer owns this project lock. Retry after it exits.');
|
|
62
|
+
}
|
|
63
|
+
const prior = await projectPath(root, stateFile(owner[0]), 'file');
|
|
64
|
+
if (!prior.stat) throw new Error('The installer lock changed. Retry the command.');
|
|
65
|
+
// Only one requester can move this exact filename, even if both read the old PID.
|
|
66
|
+
await rename(prior.file, path.join(lock.file, mine)).catch((error) => {
|
|
67
|
+
if (error.code === 'ENOENT') throw new Error('Another installer claimed recovery. Retry after it exits.');
|
|
68
|
+
throw error;
|
|
69
|
+
});
|
|
70
|
+
return lock.file;
|
|
71
|
+
} finally {
|
|
72
|
+
await rm(candidate, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function tempFile(file, id, index) {
|
|
77
|
+
return path.posix.join(folder(file), `${INSTALL_PREFIX}-${id}-${index}.local`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The journal owns the temporary filename. Exclusive open and rename keep writes whole. */
|
|
81
|
+
async function replaceFile(root, file, temp, contents, mode, expected) {
|
|
82
|
+
const destination = await projectPath(root, file, 'file');
|
|
83
|
+
const staging = await projectPath(root, temp, 'file');
|
|
84
|
+
const handle = await open(staging.file, 'wx', 0o600);
|
|
85
|
+
try {
|
|
86
|
+
await handle.writeFile(contents);
|
|
87
|
+
if (mode !== null) await handle.chmod(mode);
|
|
88
|
+
await handle.sync();
|
|
89
|
+
} finally {
|
|
90
|
+
await handle.close();
|
|
91
|
+
}
|
|
92
|
+
if (expected !== undefined && hash((await readSnapshot(root, file)).before) !== expected) {
|
|
93
|
+
throw new Error(`Project file changed before publication: ${file}`);
|
|
94
|
+
}
|
|
95
|
+
await projectPath(root, file, 'file');
|
|
96
|
+
await rename(staging.file, destination.file);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseJournal(buffer) {
|
|
100
|
+
const journal = JSON.parse(buffer.toString());
|
|
101
|
+
if (!journal || !journalPattern.test(journal.id ?? '') || !Array.isArray(journal.entries) ||
|
|
102
|
+
!Array.isArray(journal.directories)) throw new Error('Invalid installer recovery journal');
|
|
103
|
+
const files = new Set();
|
|
104
|
+
const directoryCandidates = new Set();
|
|
105
|
+
for (const entry of journal.entries) {
|
|
106
|
+
const file = normalizedFile(entry.file);
|
|
107
|
+
if (file !== entry.file || files.has(file.toLowerCase()) || !digestPattern.test(entry.after ?? '') ||
|
|
108
|
+
(entry.original !== null && (typeof entry.original !== 'string' ||
|
|
109
|
+
!Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777))) {
|
|
110
|
+
throw new Error('Invalid installer recovery journal entry');
|
|
111
|
+
}
|
|
112
|
+
files.add(file.toLowerCase());
|
|
113
|
+
for (let dir = folder(file); dir !== '.'; dir = folder(dir)) directoryCandidates.add(dir);
|
|
114
|
+
}
|
|
115
|
+
if (journal.directories.some((dir) => !directoryCandidates.has(dir))) {
|
|
116
|
+
throw new Error('Invalid installer recovery directories');
|
|
117
|
+
}
|
|
118
|
+
return journal;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Verify all files before restoring any. An intervening edit keeps the journal for inspection. */
|
|
122
|
+
async function recover(root) {
|
|
123
|
+
const data = await readSnapshot(root, stateFile('journal.json'));
|
|
124
|
+
if (!data.before) return;
|
|
125
|
+
const journal = parseJournal(data.before);
|
|
126
|
+
if ((await projectPath(root, stateFile('committed'), 'file')).stat) return;
|
|
127
|
+
|
|
128
|
+
const changes = [];
|
|
129
|
+
for (const [index, entry] of journal.entries.entries()) {
|
|
130
|
+
const original = entry.original === null ? null : Buffer.from(entry.original, 'base64');
|
|
131
|
+
const current = await readSnapshot(root, entry.file);
|
|
132
|
+
const currentHash = hash(current.before);
|
|
133
|
+
if (currentHash !== entry.after && currentHash !== hash(original)) {
|
|
134
|
+
throw new Error(`Preserving intervening edit at ${entry.file}. Restore the installer-owned version and retry recovery.`);
|
|
135
|
+
}
|
|
136
|
+
changes.push({ ...entry, original, changed: currentHash !== hash(original), temp: tempFile(entry.file, journal.id, index) });
|
|
137
|
+
}
|
|
138
|
+
for (const change of changes.reverse()) {
|
|
139
|
+
const temp = await projectPath(root, change.temp, 'file');
|
|
140
|
+
if (temp.stat) await unlink(temp.file);
|
|
141
|
+
if (!change.changed) continue;
|
|
142
|
+
if (change.original === null) {
|
|
143
|
+
if (hash((await readSnapshot(root, change.file)).before) !== change.after) {
|
|
144
|
+
throw new Error(`Project file changed during recovery: ${change.file}`);
|
|
145
|
+
}
|
|
146
|
+
await unlink((await projectPath(root, change.file, 'file')).file);
|
|
147
|
+
} else {
|
|
148
|
+
await replaceFile(root, change.file, change.temp, change.original, change.mode, change.after);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (const dir of [...journal.directories].sort((a, b) => b.length - a.length)) {
|
|
152
|
+
const entry = await projectPath(root, dir, 'directory');
|
|
153
|
+
if (entry.stat) await rmdir(entry.file).catch((error) => {
|
|
154
|
+
if (!['ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function releaseLock(root, lock) {
|
|
160
|
+
// Retire the directory while it still has an owner. A competing installer
|
|
161
|
+
// sees the whole lock or no lock, and can never reuse the retired path.
|
|
162
|
+
await projectPath(root, INSTALL_STATE, 'directory');
|
|
163
|
+
const retired = privateInstallerPath(root, 'finished');
|
|
164
|
+
await rename(lock, retired);
|
|
165
|
+
await rm(retired, { recursive: true, force: true });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A patcher reads only guarded files and returns its ordered write set.
|
|
169
|
+
* No project source file is touched until the full plan and journal are ready. */
|
|
170
|
+
export async function installModule(project, plan) {
|
|
171
|
+
const root = await realpath(project);
|
|
172
|
+
const lock = await takeLock(root);
|
|
173
|
+
let keepJournal = false;
|
|
174
|
+
try {
|
|
175
|
+
try {
|
|
176
|
+
await recover(root);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
keepJournal = true;
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
for (const name of ['journal.json', 'journal.tmp', 'committed']) {
|
|
182
|
+
const entry = await projectPath(root, stateFile(name), 'file');
|
|
183
|
+
if (entry.stat) await unlink(entry.file);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const snapshots = new Map();
|
|
187
|
+
async function snapshot(file) {
|
|
188
|
+
const relative = normalizedFile(file);
|
|
189
|
+
if (!snapshots.has(relative)) snapshots.set(relative, await readSnapshot(root, relative));
|
|
190
|
+
return snapshots.get(relative);
|
|
191
|
+
}
|
|
192
|
+
const files = {
|
|
193
|
+
read: async (file, encoding) => {
|
|
194
|
+
const { before } = await snapshot(file);
|
|
195
|
+
if (before === null) throw new Error(`Missing project file: ${file}`);
|
|
196
|
+
return encoding ? before.toString(encoding) : before;
|
|
197
|
+
},
|
|
198
|
+
exists: async (file) => Boolean((await projectPath(root, normalizedFile(file))).stat),
|
|
199
|
+
list: async (dir) => {
|
|
200
|
+
const entry = await projectPath(root, normalizedFile(dir), 'directory');
|
|
201
|
+
return readdir(entry.file, { withFileTypes: true });
|
|
202
|
+
},
|
|
203
|
+
stage: async (paths, transform) => {
|
|
204
|
+
// Legacy AST transforms get a private, allowlisted copy of their inputs.
|
|
205
|
+
// They keep their existing file paths and cannot publish to the checkout.
|
|
206
|
+
const stage = await mkdtemp(path.join(lock, 'patch-'));
|
|
207
|
+
for (const file of paths) {
|
|
208
|
+
const { before } = await snapshot(file);
|
|
209
|
+
if (before === null) continue;
|
|
210
|
+
await createParents(stage, file);
|
|
211
|
+
await writeFile(path.join(stage, file), before, { mode: 0o600, flag: 'wx' });
|
|
212
|
+
}
|
|
213
|
+
await transform(stage);
|
|
214
|
+
const writes = new Map();
|
|
215
|
+
for (const file of paths) {
|
|
216
|
+
const { before: original } = await snapshot(file);
|
|
217
|
+
const { before } = await readSnapshot(stage, file);
|
|
218
|
+
if (before && (original === null || !before.equals(original))) writes.set(file, before);
|
|
219
|
+
}
|
|
220
|
+
return writes;
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
const writes = await plan(files);
|
|
224
|
+
if (!writes?.size) return false;
|
|
225
|
+
|
|
226
|
+
const id = randomUUID();
|
|
227
|
+
const directories = new Set();
|
|
228
|
+
const entries = [];
|
|
229
|
+
for (const [relative, content] of writes) {
|
|
230
|
+
const file = normalizedFile(relative);
|
|
231
|
+
const saved = await snapshot(file);
|
|
232
|
+
const current = await readSnapshot(root, file);
|
|
233
|
+
if (hash(current.before) !== hash(saved.before) || current.mode !== saved.mode) {
|
|
234
|
+
throw new Error(`Project file changed during installer preflight: ${file}`);
|
|
235
|
+
}
|
|
236
|
+
for (let dir = folder(file); dir !== '.'; dir = folder(dir)) {
|
|
237
|
+
if (!(await projectPath(root, dir, 'directory')).stat) directories.add(dir);
|
|
238
|
+
}
|
|
239
|
+
const data = Buffer.from(content);
|
|
240
|
+
entries.push({ file, original: saved.before?.toString('base64') ?? null, mode: saved.mode, after: hash(data), data });
|
|
241
|
+
}
|
|
242
|
+
const journal = JSON.stringify({
|
|
243
|
+
id, directories: [...directories], entries: entries.map(({ data, ...entry }) => entry),
|
|
244
|
+
});
|
|
245
|
+
parseJournal(Buffer.from(journal));
|
|
246
|
+
await replaceFile(root, stateFile('journal.json'), stateFile('journal.tmp'), journal, null);
|
|
247
|
+
try {
|
|
248
|
+
for (const [index, entry] of entries.entries()) {
|
|
249
|
+
const current = await readSnapshot(root, entry.file);
|
|
250
|
+
const original = await snapshot(entry.file);
|
|
251
|
+
if (hash(current.before) !== hash(original.before) || current.mode !== original.mode) {
|
|
252
|
+
throw new Error(`Project file changed during installation: ${entry.file}`);
|
|
253
|
+
}
|
|
254
|
+
await createParents(root, entry.file);
|
|
255
|
+
// Match ordinary source-file creation for new payloads. The journal
|
|
256
|
+
// and its temporary files keep private permissions via replaceFile.
|
|
257
|
+
const mode = entry.mode ?? (0o666 & ~process.umask());
|
|
258
|
+
await replaceFile(root, entry.file, tempFile(entry.file, id, index), entry.data, mode, hash(original.before));
|
|
259
|
+
}
|
|
260
|
+
await writeFile(path.join(lock, 'committed'), '', { flag: 'wx', mode: 0o600 });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
try {
|
|
263
|
+
await recover(root);
|
|
264
|
+
} catch (recoveryError) {
|
|
265
|
+
keepJournal = true;
|
|
266
|
+
throw recoveryError;
|
|
267
|
+
}
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
} finally {
|
|
272
|
+
// Preserve a conflicted recovery journal for inspection after the CLI exits.
|
|
273
|
+
if (!keepJournal) await releaseLock(root, lock);
|
|
274
|
+
}
|
|
275
|
+
}
|