@solidactions/cli 3.10.0 → 3.10.2
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.
|
@@ -101,6 +101,7 @@ function resolveDependencies(dependencies) {
|
|
|
101
101
|
filesystem: dependencies.filesystem ?? fs_1.default.promises,
|
|
102
102
|
input: dependencies.input,
|
|
103
103
|
now: dependencies.now ?? Date.now,
|
|
104
|
+
monotonicNow: dependencies.monotonicNow ?? (() => performance.now()),
|
|
104
105
|
abortSignal: dependencies.abortSignal,
|
|
105
106
|
controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
|
|
106
107
|
dataPlaneTimeoutMs: dependencies.dataPlaneTimeoutMs ?? database_data_plane_1.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS,
|
|
@@ -568,20 +569,18 @@ async function nextWritableInput(iterator, signal) {
|
|
|
568
569
|
});
|
|
569
570
|
});
|
|
570
571
|
}
|
|
571
|
-
function validateWritableAccess(access, now) {
|
|
572
|
+
function validateWritableAccess(access, now, monotonicNow) {
|
|
572
573
|
const value = access;
|
|
573
574
|
const url = typeof value?.url === 'string' ? value.url.trim() : '';
|
|
574
575
|
const token = typeof value?.token === 'string' ? value.token.trim() : '';
|
|
575
|
-
const
|
|
576
|
+
const deadline = (0, database_data_plane_1.databaseCredentialDeadline)(value, now, monotonicNow, WRITABLE_RENEWAL_WINDOW_MS);
|
|
576
577
|
if (value?.mode !== 'write'
|
|
577
578
|
|| url === ''
|
|
578
579
|
|| token === ''
|
|
579
|
-
|| !
|
|
580
|
-
|| !Number.isFinite(expiresAt)
|
|
581
|
-
|| expiresAt <= now + WRITABLE_RENEWAL_WINDOW_MS) {
|
|
580
|
+
|| !deadline) {
|
|
582
581
|
throw new database_data_plane_1.DatabaseOperationError('upstream_unavailable', 'The database access response was invalid.');
|
|
583
582
|
}
|
|
584
|
-
return { url, token,
|
|
583
|
+
return { url, token, deadline };
|
|
585
584
|
}
|
|
586
585
|
class WritableRenewalAttemptError extends Error {
|
|
587
586
|
publicError;
|
|
@@ -593,16 +592,8 @@ class WritableRenewalAttemptError extends Error {
|
|
|
593
592
|
delete this.stack;
|
|
594
593
|
}
|
|
595
594
|
}
|
|
596
|
-
function isAuthenticationExpired(error) {
|
|
597
|
-
const value = error;
|
|
598
|
-
const code = typeof value?.code === 'string' ? value.code.toUpperCase() : '';
|
|
599
|
-
const message = typeof value?.message === 'string' ? value.message : '';
|
|
600
|
-
if (['AUTH_TOKEN_EXPIRED', 'AUTH_EXPIRED', 'TOKEN_EXPIRED'].includes(code))
|
|
601
|
-
return true;
|
|
602
|
-
return code === 'SQLITE_AUTH' && /expired|expiration|\bjwt\b/i.test(message);
|
|
603
|
-
}
|
|
604
595
|
function classifyPullFailure(error) {
|
|
605
|
-
if (
|
|
596
|
+
if ((0, database_data_plane_1.isDatabaseCredentialAuthFailure)(error))
|
|
606
597
|
return 'credential_expiry';
|
|
607
598
|
const value = error;
|
|
608
599
|
const code = typeof value?.code === 'string' ? value.code.toUpperCase() : '';
|
|
@@ -718,6 +709,7 @@ async function databaseCreateWithConfig(name, options, config, dependencies = {}
|
|
|
718
709
|
filesystem: io.filesystem,
|
|
719
710
|
stdout: options.json ? () => undefined : io.stdout,
|
|
720
711
|
now: io.now,
|
|
712
|
+
monotonicNow: io.monotonicNow,
|
|
721
713
|
post: io.post,
|
|
722
714
|
loadClient: io.loadClient,
|
|
723
715
|
controlPlaneTimeoutMs: io.controlPlaneTimeoutMs,
|
|
@@ -757,6 +749,7 @@ async function databaseImportWithConfig(name, file, options, config, dependencie
|
|
|
757
749
|
filesystem: io.filesystem,
|
|
758
750
|
stdout: io.stdout,
|
|
759
751
|
now: io.now,
|
|
752
|
+
monotonicNow: io.monotonicNow,
|
|
760
753
|
post: io.post,
|
|
761
754
|
loadClient: io.loadClient,
|
|
762
755
|
controlPlaneTimeoutMs: io.controlPlaneTimeoutMs,
|
|
@@ -888,7 +881,7 @@ async function databaseWritablePullWithConfig(name, destination, options, config
|
|
|
888
881
|
let ownsSidecars = false;
|
|
889
882
|
let client;
|
|
890
883
|
let localCreateClient;
|
|
891
|
-
let
|
|
884
|
+
let credentialDeadline;
|
|
892
885
|
let inputSession;
|
|
893
886
|
let attachedClosePromise;
|
|
894
887
|
const closeAttachedClient = async () => {
|
|
@@ -925,7 +918,7 @@ async function databaseWritablePullWithConfig(name, destination, options, config
|
|
|
925
918
|
}
|
|
926
919
|
throw safeError;
|
|
927
920
|
}
|
|
928
|
-
const access = validateWritableAccess(loaded.access, io.now());
|
|
921
|
+
const access = validateWritableAccess(loaded.access, io.now(), io.monotonicNow());
|
|
929
922
|
const createClient = loaded.createClient;
|
|
930
923
|
if (initial) {
|
|
931
924
|
await handoffReplicaReservation(io, temp, reservationHandle);
|
|
@@ -987,7 +980,7 @@ async function databaseWritablePullWithConfig(name, destination, options, config
|
|
|
987
980
|
attachedClosePromise = undefined;
|
|
988
981
|
client = opened;
|
|
989
982
|
localCreateClient = createClient;
|
|
990
|
-
|
|
983
|
+
credentialDeadline = access.deadline;
|
|
991
984
|
};
|
|
992
985
|
try {
|
|
993
986
|
if (!await confirmFileOverwrite(target, options, io))
|
|
@@ -1010,7 +1003,10 @@ async function databaseWritablePullWithConfig(name, destination, options, config
|
|
|
1010
1003
|
while (true) {
|
|
1011
1004
|
if (io.abortSignal?.aborted || inputSession.interrupted())
|
|
1012
1005
|
break;
|
|
1013
|
-
|
|
1006
|
+
const deadlineNow = credentialDeadline?.clock === 'monotonic'
|
|
1007
|
+
? io.monotonicNow()
|
|
1008
|
+
: io.now();
|
|
1009
|
+
if (!credentialDeadline || deadlineNow >= credentialDeadline.renewalAt) {
|
|
1014
1010
|
try {
|
|
1015
1011
|
await closeAttachedClient();
|
|
1016
1012
|
await openAttachedClient(false);
|
|
@@ -1064,11 +1060,12 @@ async function databaseWritablePullWithConfig(name, destination, options, config
|
|
|
1064
1060
|
sessionFailure = error;
|
|
1065
1061
|
break;
|
|
1066
1062
|
}
|
|
1067
|
-
if (!
|
|
1063
|
+
if (!(0, database_data_plane_1.isDatabaseCredentialAuthFailure)(error)) {
|
|
1068
1064
|
io.stderr('Database statement failed.');
|
|
1069
1065
|
continue;
|
|
1070
1066
|
}
|
|
1071
|
-
|
|
1067
|
+
const credentialCode = (0, database_data_plane_1.databaseCredentialFailureCode)(credentialDeadline, io.now(), io.monotonicNow());
|
|
1068
|
+
io.stderr(`Database statement has an unknown outcome because of ${credentialCode}.`);
|
|
1072
1069
|
try {
|
|
1073
1070
|
await closeAttachedClient();
|
|
1074
1071
|
await openAttachedClient(false);
|
|
@@ -10,6 +10,7 @@ const axios_1 = __importDefault(require("axios"));
|
|
|
10
10
|
const chalk_1 = __importDefault(require("chalk"));
|
|
11
11
|
const readline_1 = __importDefault(require("readline"));
|
|
12
12
|
const api_1 = require("../utils/api");
|
|
13
|
+
const secure_write_1 = require("../utils/secure-write");
|
|
13
14
|
/**
|
|
14
15
|
* Prompt the user for confirmation (unless --yes flag is set).
|
|
15
16
|
*/
|
|
@@ -96,7 +97,7 @@ async function envPull(projectName, options = {}) {
|
|
|
96
97
|
// No .env file — create with just OAuth vars
|
|
97
98
|
console.log(chalk_1.default.yellow('No .env file found — creating with OAuth vars only. Run a full env:pull for all variables.'));
|
|
98
99
|
const content = oauthLines.join('\n') + '\n';
|
|
99
|
-
|
|
100
|
+
(0, secure_write_1.writeSecretFileSync)(outputPath, content);
|
|
100
101
|
}
|
|
101
102
|
else {
|
|
102
103
|
// Merge into existing .env file
|
|
@@ -133,7 +134,7 @@ async function envPull(projectName, options = {}) {
|
|
|
133
134
|
preservedLines.push(`# OAuth tokens (updated ${new Date().toISOString()})`);
|
|
134
135
|
preservedLines.push(...oauthLines);
|
|
135
136
|
preservedLines.push('');
|
|
136
|
-
|
|
137
|
+
(0, secure_write_1.writeSecretFileSync)(outputPath, preservedLines.join('\n'));
|
|
137
138
|
}
|
|
138
139
|
console.log(chalk_1.default.green(`\n✓ Updated ${oauthVars.length} OAuth token(s) in ${outputFile}`));
|
|
139
140
|
// Print any OAuth warnings
|
|
@@ -190,7 +191,7 @@ async function envPull(projectName, options = {}) {
|
|
|
190
191
|
}
|
|
191
192
|
lines.push('');
|
|
192
193
|
// Write to file
|
|
193
|
-
|
|
194
|
+
(0, secure_write_1.writeSecretFileSync)(outputPath, lines.join('\n'));
|
|
194
195
|
console.log(chalk_1.default.green(`\n✓ Wrote ${count} variables to ${outputFile}`));
|
|
195
196
|
if (secretCount > 0) {
|
|
196
197
|
console.log(chalk_1.default.yellow(` (includes ${secretCount} secret value${secretCount > 1 ? 's' : ''})`));
|
|
@@ -228,6 +229,10 @@ async function envPull(projectName, options = {}) {
|
|
|
228
229
|
console.error(chalk_1.default.red(`Failed: ${error.response.status}`), error.response.data);
|
|
229
230
|
}
|
|
230
231
|
}
|
|
232
|
+
else if (!axios_1.default.isAxiosError(error) && error.code) {
|
|
233
|
+
// A filesystem failure writing the .env — not a connection problem.
|
|
234
|
+
console.error(chalk_1.default.red(`Failed to write ${outputFile}: ${error.message}`));
|
|
235
|
+
}
|
|
231
236
|
else {
|
|
232
237
|
console.error(chalk_1.default.red('Connection failed:'), error.message);
|
|
233
238
|
}
|
|
@@ -4,6 +4,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.DatabaseOperationError = exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = void 0;
|
|
7
|
+
exports.databaseCredentialDeadline = databaseCredentialDeadline;
|
|
8
|
+
exports.isDatabaseCredentialAuthFailure = isDatabaseCredentialAuthFailure;
|
|
9
|
+
exports.databaseCredentialFailureCode = databaseCredentialFailureCode;
|
|
7
10
|
exports.safeDatabaseRequestError = safeDatabaseRequestError;
|
|
8
11
|
exports.runDatabaseClientOperationWithDeadline = runDatabaseClientOperationWithDeadline;
|
|
9
12
|
exports.requestDatabaseOperation = requestDatabaseOperation;
|
|
@@ -15,6 +18,42 @@ exports.formatDatabaseTableValue = formatDatabaseTableValue;
|
|
|
15
18
|
const axios_1 = __importDefault(require("axios"));
|
|
16
19
|
const api_1 = require("./api");
|
|
17
20
|
const database_client_support_1 = require("./database-client-support");
|
|
21
|
+
function databaseCredentialDeadline(access, wallNow, monotonicNow, renewalWindowMs) {
|
|
22
|
+
if (access.expires_in_seconds !== undefined) {
|
|
23
|
+
const lifetime = access.expires_in_seconds;
|
|
24
|
+
if (!Number.isSafeInteger(lifetime)
|
|
25
|
+
|| lifetime <= 0
|
|
26
|
+
|| !Number.isFinite(monotonicNow))
|
|
27
|
+
return null;
|
|
28
|
+
const lifetimeMs = lifetime * 1_000;
|
|
29
|
+
if (lifetimeMs <= renewalWindowMs)
|
|
30
|
+
return null;
|
|
31
|
+
return {
|
|
32
|
+
renewalAt: monotonicNow + lifetimeMs - renewalWindowMs,
|
|
33
|
+
expiresAt: monotonicNow + lifetimeMs,
|
|
34
|
+
clock: 'monotonic',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const expiresAt = Date.parse(access.expires_at);
|
|
38
|
+
if (!Number.isFinite(wallNow) || !Number.isFinite(expiresAt) || expiresAt <= wallNow + renewalWindowMs)
|
|
39
|
+
return null;
|
|
40
|
+
return { renewalAt: expiresAt - renewalWindowMs, expiresAt, clock: 'wall' };
|
|
41
|
+
}
|
|
42
|
+
function isDatabaseCredentialAuthFailure(error) {
|
|
43
|
+
const value = error;
|
|
44
|
+
const code = typeof value?.code === 'string' ? value.code.toUpperCase() : '';
|
|
45
|
+
const message = typeof value?.message === 'string' ? value.message : '';
|
|
46
|
+
if (['AUTH_TOKEN_EXPIRED', 'AUTH_EXPIRED', 'TOKEN_EXPIRED'].includes(code))
|
|
47
|
+
return true;
|
|
48
|
+
if (code === 'SQLITE_AUTH' && /expired|expiration|\bjwt\b/i.test(message))
|
|
49
|
+
return true;
|
|
50
|
+
const cause = value?.cause;
|
|
51
|
+
return value?.name === 'LibsqlError' && code === 'SERVER_ERROR' && cause?.status === 401;
|
|
52
|
+
}
|
|
53
|
+
function databaseCredentialFailureCode(deadline, wallNow, monotonicNow) {
|
|
54
|
+
const now = deadline.clock === 'monotonic' ? monotonicNow : wallNow;
|
|
55
|
+
return now >= deadline.expiresAt ? 'database_credential_expired' : 'database_credential_revoked';
|
|
56
|
+
}
|
|
18
57
|
exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = 30_000;
|
|
19
58
|
exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = 120_000;
|
|
20
59
|
class DatabaseOperationError extends Error {
|
|
@@ -309,20 +309,18 @@ function batchSql(groups) {
|
|
|
309
309
|
'PRAGMA foreign_keys=ON;',
|
|
310
310
|
].join('\n');
|
|
311
311
|
}
|
|
312
|
-
function validateAccess(access, now) {
|
|
312
|
+
function validateAccess(access, now, monotonicNow) {
|
|
313
313
|
const value = access;
|
|
314
314
|
const url = typeof value?.url === 'string' ? value.url.trim() : '';
|
|
315
315
|
const token = typeof value?.token === 'string' ? value.token.trim() : '';
|
|
316
|
-
const
|
|
316
|
+
const deadline = (0, database_data_plane_1.databaseCredentialDeadline)(value, now, monotonicNow, RENEWAL_WINDOW_MS);
|
|
317
317
|
if (value?.mode !== 'write'
|
|
318
318
|
|| url === ''
|
|
319
319
|
|| token === ''
|
|
320
|
-
|| !
|
|
321
|
-
|| !Number.isFinite(expiresAt)
|
|
322
|
-
|| expiresAt <= now + RENEWAL_WINDOW_MS) {
|
|
320
|
+
|| !deadline) {
|
|
323
321
|
throw importFailure('Database import access was invalid.');
|
|
324
322
|
}
|
|
325
|
-
return { url, token,
|
|
323
|
+
return { url, token, deadline };
|
|
326
324
|
}
|
|
327
325
|
async function acquireClient(prepared, config, dependencies) {
|
|
328
326
|
let loaded;
|
|
@@ -337,7 +335,7 @@ async function acquireClient(prepared, config, dependencies) {
|
|
|
337
335
|
throw error;
|
|
338
336
|
throw importFailure('Database import access could not be renewed.');
|
|
339
337
|
}
|
|
340
|
-
const access = validateAccess(loaded.access, dependencies.now());
|
|
338
|
+
const access = validateAccess(loaded.access, dependencies.now(), dependencies.monotonicNow());
|
|
341
339
|
let client;
|
|
342
340
|
try {
|
|
343
341
|
client = loaded.createClient({
|
|
@@ -358,7 +356,7 @@ async function acquireClient(prepared, config, dependencies) {
|
|
|
358
356
|
}
|
|
359
357
|
throw importFailure('Database import requires atomic multi-statement execution support.');
|
|
360
358
|
}
|
|
361
|
-
return { client,
|
|
359
|
+
return { client, deadline: access.deadline };
|
|
362
360
|
}
|
|
363
361
|
async function closeClient(client, timeoutMs = database_data_plane_1.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS) {
|
|
364
362
|
if (!client)
|
|
@@ -378,7 +376,7 @@ async function runPreparedDatabaseImport(prepared, config, dependencies) {
|
|
|
378
376
|
let suppressResume = false;
|
|
379
377
|
let client;
|
|
380
378
|
let clientClosePromise;
|
|
381
|
-
let
|
|
379
|
+
let deadline;
|
|
382
380
|
let failure;
|
|
383
381
|
const closeCurrentClient = () => {
|
|
384
382
|
clientClosePromise ??= closeClient(client, dependencies.dataPlaneTimeoutMs);
|
|
@@ -386,13 +384,14 @@ async function runPreparedDatabaseImport(prepared, config, dependencies) {
|
|
|
386
384
|
};
|
|
387
385
|
try {
|
|
388
386
|
while (nextStatement < prepared.groups.length) {
|
|
389
|
-
|
|
387
|
+
const deadlineNow = deadline?.clock === 'monotonic' ? dependencies.monotonicNow() : dependencies.now();
|
|
388
|
+
if (!client || !deadline || deadlineNow >= deadline.renewalAt) {
|
|
390
389
|
await closeCurrentClient();
|
|
391
390
|
client = undefined;
|
|
392
391
|
clientClosePromise = undefined;
|
|
393
392
|
const acquired = await acquireClient(prepared, config, dependencies);
|
|
394
393
|
client = acquired.client;
|
|
395
|
-
|
|
394
|
+
deadline = acquired.deadline;
|
|
396
395
|
}
|
|
397
396
|
const batch = nextBatch(prepared.groups, nextStatement);
|
|
398
397
|
try {
|
|
@@ -401,6 +400,11 @@ async function runPreparedDatabaseImport(prepared, config, dependencies) {
|
|
|
401
400
|
catch (error) {
|
|
402
401
|
if (error instanceof database_data_plane_1.DatabaseOperationError)
|
|
403
402
|
throw error;
|
|
403
|
+
if (deadline && (0, database_data_plane_1.isDatabaseCredentialAuthFailure)(error)) {
|
|
404
|
+
const code = (0, database_data_plane_1.databaseCredentialFailureCode)(deadline, dependencies.now(), dependencies.monotonicNow());
|
|
405
|
+
const label = code === 'database_credential_expired' ? 'expired' : 'was revoked';
|
|
406
|
+
throw new database_data_plane_1.DatabaseOperationError(code, `Database credential ${label} during an import batch; the batch outcome is unknown.`);
|
|
407
|
+
}
|
|
404
408
|
throw importFailure('A database import batch failed.');
|
|
405
409
|
}
|
|
406
410
|
const boundary = prepared.groups[batch.nextStatement - 1].endByte;
|
|
@@ -456,6 +460,7 @@ async function runPreparedDatabaseImport(prepared, config, dependencies) {
|
|
|
456
460
|
if (failure) {
|
|
457
461
|
const policyRefusal = failure.code === 'read_only_mode'
|
|
458
462
|
|| failure.code === 'plan_denied'
|
|
463
|
+
|| ['reads_exhausted', 'writes_exhausted', 'storage_exhausted'].includes(failure.code)
|
|
459
464
|
|| failure.status === 429;
|
|
460
465
|
const guidance = checkpointPublished && !suppressResume && !policyRefusal
|
|
461
466
|
? `\nLast completed position: batch ${completedBatches}, ${nextStatement} statements, ${completedSourceBytes} source bytes.\n${resumeLine(prepared.database, prepared.file, prepared.checkpointPath)}`
|
|
@@ -0,0 +1,104 @@
|
|
|
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.writeSecretFileSync = writeSecretFileSync;
|
|
7
|
+
exports.writeViaTempFileSync = writeViaTempFileSync;
|
|
8
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
10
|
+
const path_1 = __importDefault(require("path"));
|
|
11
|
+
/** The kernel's own symlink-resolution limit. */
|
|
12
|
+
const MAX_SYMLINK_HOPS = 40;
|
|
13
|
+
/**
|
|
14
|
+
* Find where a path that does not currently resolve should be created,
|
|
15
|
+
* following any symlink chain by hand.
|
|
16
|
+
*
|
|
17
|
+
* realpathSync cannot be used here: it throws ENOENT on a dangling symlink,
|
|
18
|
+
* and today's writeFileSync creates the link's target instead of failing.
|
|
19
|
+
*/
|
|
20
|
+
function resolveCreationPath(filePath) {
|
|
21
|
+
let current = filePath;
|
|
22
|
+
for (let hop = 0; hop <= MAX_SYMLINK_HOPS; hop++) {
|
|
23
|
+
let stats;
|
|
24
|
+
try {
|
|
25
|
+
stats = fs_1.default.lstatSync(current);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return current; // nothing here — this is the creation point
|
|
29
|
+
}
|
|
30
|
+
if (!stats.isSymbolicLink()) {
|
|
31
|
+
return current;
|
|
32
|
+
}
|
|
33
|
+
current = path_1.default.resolve(path_1.default.dirname(current), fs_1.default.readlinkSync(current));
|
|
34
|
+
}
|
|
35
|
+
// Defensive guard, unreachable in practice: statSync raises ELOOP first.
|
|
36
|
+
const error = new Error(`Too many symbolic links resolving ${filePath}`);
|
|
37
|
+
error.code = 'ELOOP';
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Write a secret-bearing file so the result is owner-only, whether or not the
|
|
42
|
+
* destination already exists.
|
|
43
|
+
*
|
|
44
|
+
* writeFileSync's `mode` only applies when it creates the file, so an existing
|
|
45
|
+
* world-readable file would silently keep its mode and receive fresh plaintext
|
|
46
|
+
* secrets. Writing to a sibling temp file at 0600 and renaming over the
|
|
47
|
+
* destination gives the final path a fresh inode carrying 0600 on both the
|
|
48
|
+
* create and the overwrite path, and makes the replacement atomic — readers
|
|
49
|
+
* never observe a partial file.
|
|
50
|
+
*
|
|
51
|
+
* The mode is masked by the process umask, which can only subtract bits, so
|
|
52
|
+
* the result is always <= 0600: never group- or world-readable.
|
|
53
|
+
*/
|
|
54
|
+
function writeSecretFileSync(filePath, contents) {
|
|
55
|
+
let stats;
|
|
56
|
+
try {
|
|
57
|
+
// statSync follows the whole chain, including magic /proc links.
|
|
58
|
+
stats = fs_1.default.statSync(filePath);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error.code !== 'ENOENT') {
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// FIFOs, sockets and character devices (`-o /dev/stdout`) have no
|
|
66
|
+
// persistent inode to protect, and a temp+rename beside them fails.
|
|
67
|
+
// Directories deliberately stay on the temp+rename path so they keep
|
|
68
|
+
// failing loudly.
|
|
69
|
+
if (stats && !stats.isFile() && !stats.isDirectory()) {
|
|
70
|
+
fs_1.default.writeFileSync(filePath, contents);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const target = stats ? fs_1.default.realpathSync(filePath) : resolveCreationPath(filePath);
|
|
74
|
+
const tempPath = path_1.default.join(path_1.default.dirname(target), `.${path_1.default.basename(target)}.${process.pid}.${crypto_1.default.randomBytes(4).toString('hex')}.tmp`);
|
|
75
|
+
writeViaTempFileSync(target, tempPath, contents);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Write `contents` to `tempPath` at 0600 and rename it over `target`.
|
|
79
|
+
*
|
|
80
|
+
* Exported so tests can stage a collision at a known temp path; production
|
|
81
|
+
* callers go through writeSecretFileSync, which randomizes that path.
|
|
82
|
+
*/
|
|
83
|
+
function writeViaTempFileSync(target, tempPath, contents) {
|
|
84
|
+
let created = false;
|
|
85
|
+
try {
|
|
86
|
+
// 'wx' refuses to follow or clobber an existing (or planted) temp path.
|
|
87
|
+
fs_1.default.writeFileSync(tempPath, contents, { flag: 'wx', mode: 0o600 });
|
|
88
|
+
created = true;
|
|
89
|
+
fs_1.default.renameSync(tempPath, target);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
// Only our own temp file may be removed: a failed 'wx' means the path
|
|
93
|
+
// holds someone else's file, which is not ours to delete.
|
|
94
|
+
if (created) {
|
|
95
|
+
try {
|
|
96
|
+
fs_1.default.unlinkSync(tempPath);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Nothing to clean up.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|