@sanity/cli-core 3.15.0 → 3.15.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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync } from 'node:fs';
|
|
1
|
+
import { chmodSync, mkdirSync, statSync } from 'node:fs';
|
|
2
2
|
import { dirname, join as joinPath } from 'node:path';
|
|
3
3
|
import { z } from 'zod/mini';
|
|
4
4
|
import { debug } from '../../_exports/debug.js';
|
|
@@ -59,6 +59,15 @@ export const _internals = {
|
|
|
59
59
|
setCachedTokenInfo(tokenInfo);
|
|
60
60
|
return tokenInfo;
|
|
61
61
|
}
|
|
62
|
+
// The config file holds the CLI auth token, so keep it readable by its owner only
|
|
63
|
+
const CONFIG_DIR_OPTIONS = {
|
|
64
|
+
mode: 0o700,
|
|
65
|
+
recursive: true
|
|
66
|
+
};
|
|
67
|
+
const CONFIG_WRITE_OPTIONS = {
|
|
68
|
+
mode: 0o600,
|
|
69
|
+
pretty: true
|
|
70
|
+
};
|
|
62
71
|
const cliUserConfigSchema = {
|
|
63
72
|
authToken: z.optional(z.string())
|
|
64
73
|
};
|
|
@@ -78,23 +87,17 @@ const cliUserConfigSchema = {
|
|
|
78
87
|
throw new Error(`Invalid value for config property "${prop}": ${message}`);
|
|
79
88
|
}
|
|
80
89
|
const configPath = getCliUserConfigPath();
|
|
81
|
-
mkdirSync(dirname(configPath),
|
|
82
|
-
recursive: true
|
|
83
|
-
});
|
|
90
|
+
mkdirSync(dirname(configPath), CONFIG_DIR_OPTIONS);
|
|
84
91
|
// When value is undefined, explicitly delete the key rather than relying
|
|
85
92
|
// on JSON.stringify silently dropping undefined values.
|
|
86
93
|
if (value === undefined) {
|
|
87
94
|
const { [prop]: _, ...rest } = config;
|
|
88
|
-
writeJsonFileSync(configPath, rest,
|
|
89
|
-
pretty: true
|
|
90
|
-
});
|
|
95
|
+
writeJsonFileSync(configPath, rest, CONFIG_WRITE_OPTIONS);
|
|
91
96
|
} else {
|
|
92
97
|
writeJsonFileSync(configPath, {
|
|
93
98
|
...config,
|
|
94
99
|
[prop]: value
|
|
95
|
-
},
|
|
96
|
-
pretty: true
|
|
97
|
-
});
|
|
100
|
+
}, CONFIG_WRITE_OPTIONS);
|
|
98
101
|
}
|
|
99
102
|
// Invalidate the in-process token cache so subsequent getCliToken() calls
|
|
100
103
|
// pick up the new value from disk.
|
|
@@ -140,15 +143,11 @@ const cliUserConfigSchema = {
|
|
|
140
143
|
set (key, value) {
|
|
141
144
|
const config = readConfig();
|
|
142
145
|
const configPath = getCliUserConfigPath();
|
|
143
|
-
mkdirSync(dirname(configPath),
|
|
144
|
-
recursive: true
|
|
145
|
-
});
|
|
146
|
+
mkdirSync(dirname(configPath), CONFIG_DIR_OPTIONS);
|
|
146
147
|
writeJsonFileSync(configPath, {
|
|
147
148
|
...config,
|
|
148
149
|
[key]: value
|
|
149
|
-
},
|
|
150
|
-
pretty: true
|
|
151
|
-
});
|
|
150
|
+
}, CONFIG_WRITE_OPTIONS);
|
|
152
151
|
if (key === 'authToken') clearCliTokenCache();
|
|
153
152
|
},
|
|
154
153
|
// No mkdirSync needed: if readConfig() succeeded the directory already exists.
|
|
@@ -156,9 +155,7 @@ const cliUserConfigSchema = {
|
|
|
156
155
|
const config = readConfig();
|
|
157
156
|
if (!(key in config)) return;
|
|
158
157
|
const { [key]: _, ...rest } = config;
|
|
159
|
-
writeJsonFileSync(getCliUserConfigPath(), rest,
|
|
160
|
-
pretty: true
|
|
161
|
-
});
|
|
158
|
+
writeJsonFileSync(getCliUserConfigPath(), rest, CONFIG_WRITE_OPTIONS);
|
|
162
159
|
if (key === 'authToken') clearCliTokenCache();
|
|
163
160
|
}
|
|
164
161
|
};
|
|
@@ -177,8 +174,10 @@ function assertCanAccessHostUserConfig() {
|
|
|
177
174
|
* @returns The whole CLI configuration.
|
|
178
175
|
* @internal
|
|
179
176
|
*/ function readConfig() {
|
|
177
|
+
const configPath = getCliUserConfigPath();
|
|
178
|
+
restrictConfigFilePermissions(configPath);
|
|
180
179
|
try {
|
|
181
|
-
const config = readJsonFileSync(
|
|
180
|
+
const config = readJsonFileSync(configPath);
|
|
182
181
|
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
|
183
182
|
throw new Error('Invalid config file - expected an object');
|
|
184
183
|
}
|
|
@@ -188,6 +187,25 @@ function assertCanAccessHostUserConfig() {
|
|
|
188
187
|
return {};
|
|
189
188
|
}
|
|
190
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* Remove group and other access from an existing config file. CLI versions from
|
|
192
|
+
* 6.0.0 created it with the default umask mode (usually 0644), exposing the auth
|
|
193
|
+
* token to other local users. Only touches files owned by the current user, and
|
|
194
|
+
* never adds permissions.
|
|
195
|
+
*
|
|
196
|
+
* @param configPath - Path to the CLI configuration file
|
|
197
|
+
*/ function restrictConfigFilePermissions(configPath) {
|
|
198
|
+
// No POSIX permissions to fix on Windows
|
|
199
|
+
if (typeof process.getuid !== 'function') return;
|
|
200
|
+
try {
|
|
201
|
+
const { mode, uid } = statSync(configPath);
|
|
202
|
+
if (uid !== process.getuid() || (mode & 0o077) === 0) return;
|
|
203
|
+
chmodSync(configPath, mode & 0o700);
|
|
204
|
+
debug('Restricted permissions of %s to owner only', configPath);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
debug('Could not restrict permissions of CLI config file: %s', err instanceof Error ? err.message : `${err}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
191
209
|
/**
|
|
192
210
|
* Get the file system location for the CLI user configuration file.
|
|
193
211
|
* Takes into account the active environment (staging vs production).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getCliExecutionContext} from '../../executionContext.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {\n clearCliTokenCache,\n type CliTokenInfo,\n getCachedTokenInfo,\n setCachedTokenInfo,\n} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\nexport {type CliTokenInfo} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token selected for the current invocation.\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n return (await getCliTokenInfo())?.token\n}\n\n/**\n * Get the CLI authentication token and where it was resolved from.\n *\n * @returns A promise that resolves to the token and its source, or undefined if no token is found\n * @internal\n */\nexport async function getCliTokenInfo(): Promise<CliTokenInfo | undefined> {\n // A per-invocation execution context token (e.g. per-request from an MCP\n // server) takes precedence and must bypass the process-wide cache entirely:\n // reading the cache would leak another invocation's token, and writing it\n // would leak this one's.\n const context = getCliExecutionContext()\n if (context) {\n return context.token === undefined\n ? undefined\n : {source: 'CLI execution context', token: context.token}\n }\n\n const cachedTokenInfo = getCachedTokenInfo()\n if (cachedTokenInfo !== undefined) {\n return cachedTokenInfo\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const tokenInfo = {\n source: 'SANITY_AUTH_TOKEN environment variable',\n token: token.trim(),\n }\n setCachedTokenInfo(tokenInfo)\n return tokenInfo\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n const tokenInfo =\n configToken === undefined ? undefined : {source: getCliUserConfigPath(), token: configToken}\n setCachedTokenInfo(tokenInfo)\n return tokenInfo\n}\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n assertCanAccessHostUserConfig()\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\nfunction assertCanAccessHostUserConfig(): void {\n if (getCliExecutionContext()) {\n throw new Error('Host CLI user configuration is unavailable during programmatic invocations')\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getCliExecutionContext","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedTokenInfo","setCachedTokenInfo","_internals","getCliUserConfig","getCliToken","getCliTokenInfo","token","context","undefined","source","cachedTokenInfo","process","env","SANITY_AUTH_TOKEN","tokenInfo","trim","configToken","getCliUserConfigPath","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","assertCanAccessHostUserConfig","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","recursive","_","rest","pretty","data","getUserConfig","get","key","set","delete","Array","isArray","err","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,sBAAsB,QAAO,4BAA2B;AAChE,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SACEC,kBAAkB,EAElBC,kBAAkB,EAClBC,kBAAkB,QACb,qBAAoB;AAG3B,8CAA8C;AAC9C,SAAQF,kBAAkB,QAAO,qBAAoB;AAGrD,wBAAwB;AACxB,OAAO,MAAMG,aAAa;IACxBC;AACF,EAAC;AAED;;;;;CAKC,GACD,OAAO,eAAeC;IACpB,OAAQ,CAAA,MAAMC,iBAAgB,GAAIC;AACpC;AAEA;;;;;CAKC,GACD,OAAO,eAAeD;IACpB,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,yBAAyB;IACzB,MAAME,UAAUZ;IAChB,IAAIY,SAAS;QACX,OAAOA,QAAQD,KAAK,KAAKE,YACrBA,YACA;YAACC,QAAQ;YAAyBH,OAAOC,QAAQD,KAAK;QAAA;IAC5D;IAEA,MAAMI,kBAAkBV;IACxB,IAAIU,oBAAoBF,WAAW;QACjC,OAAOE;IACT;IAEA,MAAMJ,QAAQK,QAAQC,GAAG,CAACC,iBAAiB;IAC3C,IAAIP,OAAO;QACT,MAAMQ,YAAY;YAChBL,QAAQ;YACRH,OAAOA,MAAMS,IAAI;QACnB;QACAd,mBAAmBa;QACnB,OAAOA;IACT;IAEA,MAAME,cAAcd,WAAWC,gBAAgB,CAAC;IAChD,MAAMW,YACJE,gBAAgBR,YAAYA,YAAY;QAACC,QAAQQ;QAAwBX,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{"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {chmodSync, mkdirSync, statSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getCliExecutionContext} from '../../executionContext.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {\n clearCliTokenCache,\n type CliTokenInfo,\n getCachedTokenInfo,\n setCachedTokenInfo,\n} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\nexport {type CliTokenInfo} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token selected for the current invocation.\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n return (await getCliTokenInfo())?.token\n}\n\n/**\n * Get the CLI authentication token and where it was resolved from.\n *\n * @returns A promise that resolves to the token and its source, or undefined if no token is found\n * @internal\n */\nexport async function getCliTokenInfo(): Promise<CliTokenInfo | undefined> {\n // A per-invocation execution context token (e.g. per-request from an MCP\n // server) takes precedence and must bypass the process-wide cache entirely:\n // reading the cache would leak another invocation's token, and writing it\n // would leak this one's.\n const context = getCliExecutionContext()\n if (context) {\n return context.token === undefined\n ? undefined\n : {source: 'CLI execution context', token: context.token}\n }\n\n const cachedTokenInfo = getCachedTokenInfo()\n if (cachedTokenInfo !== undefined) {\n return cachedTokenInfo\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const tokenInfo = {\n source: 'SANITY_AUTH_TOKEN environment variable',\n token: token.trim(),\n }\n setCachedTokenInfo(tokenInfo)\n return tokenInfo\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n const tokenInfo =\n configToken === undefined ? undefined : {source: getCliUserConfigPath(), token: configToken}\n setCachedTokenInfo(tokenInfo)\n return tokenInfo\n}\n\n// The config file holds the CLI auth token, so keep it readable by its owner only\nconst CONFIG_DIR_OPTIONS = {mode: 0o700, recursive: true}\nconst CONFIG_WRITE_OPTIONS = {mode: 0o600, pretty: true}\n\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), CONFIG_DIR_OPTIONS)\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, CONFIG_WRITE_OPTIONS)\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, CONFIG_WRITE_OPTIONS)\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n assertCanAccessHostUserConfig()\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), CONFIG_DIR_OPTIONS)\n writeJsonFileSync(configPath, {...config, [key]: value}, CONFIG_WRITE_OPTIONS)\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, CONFIG_WRITE_OPTIONS)\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\nfunction assertCanAccessHostUserConfig(): void {\n if (getCliExecutionContext()) {\n throw new Error('Host CLI user configuration is unavailable during programmatic invocations')\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n const configPath = getCliUserConfigPath()\n restrictConfigFilePermissions(configPath)\n try {\n const config = readJsonFileSync(configPath)\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Remove group and other access from an existing config file. CLI versions from\n * 6.0.0 created it with the default umask mode (usually 0644), exposing the auth\n * token to other local users. Only touches files owned by the current user, and\n * never adds permissions.\n *\n * @param configPath - Path to the CLI configuration file\n */\nfunction restrictConfigFilePermissions(configPath: string): void {\n // No POSIX permissions to fix on Windows\n if (typeof process.getuid !== 'function') return\n\n try {\n const {mode, uid} = statSync(configPath)\n if (uid !== process.getuid() || (mode & 0o077) === 0) return\n\n chmodSync(configPath, mode & 0o700)\n debug('Restricted permissions of %s to owner only', configPath)\n } catch (err: unknown) {\n debug(\n 'Could not restrict permissions of CLI config file: %s',\n err instanceof Error ? err.message : `${err}`,\n )\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["chmodSync","mkdirSync","statSync","dirname","join","joinPath","z","debug","getCliExecutionContext","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedTokenInfo","setCachedTokenInfo","_internals","getCliUserConfig","getCliToken","getCliTokenInfo","token","context","undefined","source","cachedTokenInfo","process","env","SANITY_AUTH_TOKEN","tokenInfo","trim","configToken","getCliUserConfigPath","CONFIG_DIR_OPTIONS","mode","recursive","CONFIG_WRITE_OPTIONS","pretty","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","assertCanAccessHostUserConfig","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","_","rest","data","getUserConfig","get","key","set","delete","restrictConfigFilePermissions","Array","isArray","err","getuid","uid","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,EAAEC,SAAS,EAAEC,QAAQ,QAAO,UAAS;AACtD,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,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AAO;QAC7BzB,MAAM,8CAA8CgD;IACtD,EAAE,OAAOY,KAAc;QACrB5D,MACE,yDACA4D,eAAeb,QAAQa,IAAIlB,OAAO,GAAG,GAAGkB,KAAK;IAEjD;AACF;AAEA;;;;;;;CAOC,GACD,SAASrC;IACP,OAAON,QAAQC,GAAG,CAAC6C,sBAAsB,IAAIjE,SAASI,sBAAsB;AAC9E"}
|
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
import { writeFileSync } from 'node:fs';
|
|
1
|
+
import { chmodSync, writeFileSync } from 'node:fs';
|
|
2
2
|
/**
|
|
3
3
|
* Serialize the given `data` as JSON and write it synchronously to the given path.
|
|
4
4
|
*
|
|
5
5
|
* @param filePath - Path to JSON file to write
|
|
6
|
+
* @param options - `mode` sets the file mode, both for new files and for files that already exist
|
|
6
7
|
* @internal
|
|
7
8
|
*/ export function writeJsonFileSync(filePath, data, options = {}) {
|
|
8
|
-
const { pretty = false } = options;
|
|
9
|
+
const { mode, pretty = false } = options;
|
|
9
10
|
try {
|
|
10
11
|
const stringified = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
|
11
|
-
writeFileSync(filePath, `${stringified}\n`, 'utf8'
|
|
12
|
+
writeFileSync(filePath, `${stringified}\n`, mode === undefined ? 'utf8' : {
|
|
13
|
+
encoding: 'utf8',
|
|
14
|
+
mode
|
|
15
|
+
});
|
|
16
|
+
// `writeFileSync` only applies `mode` when it creates the file
|
|
17
|
+
if (mode !== undefined) chmodSync(filePath, mode);
|
|
12
18
|
} catch (err) {
|
|
13
19
|
throw new Error(`Failed to write "${filePath}"`, {
|
|
14
20
|
cause: err
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/writeJsonFileSync.ts"],"sourcesContent":["import {writeFileSync} from 'node:fs'\n\n/**\n * Serialize the given `data` as JSON and write it synchronously to the given path.\n *\n * @param filePath - Path to JSON file to write\n * @internal\n */\nexport function writeJsonFileSync(\n filePath: string,\n data: unknown,\n options: {pretty?: boolean} = {},\n): void {\n const {pretty = false} = options\n try {\n const stringified = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data)\n writeFileSync(filePath
|
|
1
|
+
{"version":3,"sources":["../../src/util/writeJsonFileSync.ts"],"sourcesContent":["import {chmodSync, writeFileSync} from 'node:fs'\n\n/**\n * Serialize the given `data` as JSON and write it synchronously to the given path.\n *\n * @param filePath - Path to JSON file to write\n * @param options - `mode` sets the file mode, both for new files and for files that already exist\n * @internal\n */\nexport function writeJsonFileSync(\n filePath: string,\n data: unknown,\n options: {mode?: number; pretty?: boolean} = {},\n): void {\n const {mode, pretty = false} = options\n try {\n const stringified = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data)\n writeFileSync(\n filePath,\n `${stringified}\\n`,\n mode === undefined ? 'utf8' : {encoding: 'utf8', mode},\n )\n // `writeFileSync` only applies `mode` when it creates the file\n if (mode !== undefined) chmodSync(filePath, mode)\n } catch (err: unknown) {\n throw new Error(`Failed to write \"${filePath}\"`, {cause: err})\n }\n}\n"],"names":["chmodSync","writeFileSync","writeJsonFileSync","filePath","data","options","mode","pretty","stringified","JSON","stringify","undefined","encoding","err","Error","cause"],"mappings":"AAAA,SAAQA,SAAS,EAAEC,aAAa,QAAO,UAAS;AAEhD;;;;;;CAMC,GACD,OAAO,SAASC,kBACdC,QAAgB,EAChBC,IAAa,EACbC,UAA6C,CAAC,CAAC;IAE/C,MAAM,EAACC,IAAI,EAAEC,SAAS,KAAK,EAAC,GAAGF;IAC/B,IAAI;QACF,MAAMG,cAAcD,SAASE,KAAKC,SAAS,CAACN,MAAM,MAAM,KAAKK,KAAKC,SAAS,CAACN;QAC5EH,cACEE,UACA,GAAGK,YAAY,EAAE,CAAC,EAClBF,SAASK,YAAY,SAAS;YAACC,UAAU;YAAQN;QAAI;QAEvD,+DAA+D;QAC/D,IAAIA,SAASK,WAAWX,UAAUG,UAAUG;IAC9C,EAAE,OAAOO,KAAc;QACrB,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEX,SAAS,CAAC,CAAC,EAAE;YAACY,OAAOF;QAAG;IAC9D;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "3.15.
|
|
3
|
+
"version": "3.15.1",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -121,11 +121,11 @@
|
|
|
121
121
|
"dependencies": {
|
|
122
122
|
"@inquirer/core": "^12.0.6",
|
|
123
123
|
"@inquirer/prompts": "^8.7.5",
|
|
124
|
-
"@oclif/core": "^4.
|
|
124
|
+
"@oclif/core": "^4.14.0",
|
|
125
125
|
"@sanity/client": "^8.15.0",
|
|
126
126
|
"boxen": "^8.0.1",
|
|
127
|
-
"empathic": "^2.0
|
|
128
|
-
"get-it": "^9.
|
|
127
|
+
"empathic": "^2.1.0",
|
|
128
|
+
"get-it": "^9.7.0",
|
|
129
129
|
"get-tsconfig": "^4.14.3",
|
|
130
130
|
"import-meta-resolve": "^4.2.0",
|
|
131
131
|
"jiti": "^2.7.0",
|