@attocash/cli 0.3.2 → 0.5.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/README.md CHANGED
@@ -19,7 +19,7 @@ Requires **Node.js 24.15.0 or newer** and an accessible OS password store:
19
19
  | --- | --- |
20
20
  | macOS | Keychain access for the CLI |
21
21
  | Linux | `secret-tool` (usually `libsecret-tools`), an unlocked Secret Service provider such as GNOME Keyring or KWallet, and access to its D-Bus session |
22
- | Windows | Credential Manager access for the CLI |
22
+ | Windows | Credential Manager access and the [Microsoft Visual C++ v14 runtime](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170) matching Node.js architecture |
23
23
 
24
24
  ```sh
25
25
  npm install --global @attocash/cli
@@ -36,6 +36,10 @@ The executable is `atto`. There is no plaintext recovery-phrase fallback when
36
36
  the password store is unavailable. Headless Linux environments need a working
37
37
  Secret Service session too; check it with `atto doctor`.
38
38
 
39
+ Windows uses Node.js filesystem support and normal per-user profile permissions.
40
+ Recovery material stays in Credential Manager; no permission-checking executable
41
+ or additional SDK is needed.
42
+
39
43
  ## Set up the wallet
40
44
 
41
45
  Run this in your own interactive terminal:
@@ -249,7 +253,7 @@ shared spending limits and a durable request ID. See
249
253
 
250
254
  Review Marketplace's exact request file and typed challenge in your own terminal.
251
255
  See [local proof approvals](https://github.com/attocash/integrations/blob/main/docs/cli-reference.md#review-a-marketplace-wallet-approval)
252
- for origin checks, file requirements, and native Windows limitations.
256
+ for origin checks and private-file requirements on each supported platform.
253
257
 
254
258
  ## Profiles and recovery
255
259
 
@@ -3,6 +3,7 @@ import { isAbsolute, join, resolve } from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { AttoApplication } from '../application/app.js';
5
5
  import { amountRaw } from '../domain/amount.js';
6
+ import { formatSpendingPolicy as formatPolicy } from '../marketplace/wallet-setup.js';
6
7
  import { AttoError } from '../domain/errors.js';
7
8
  import { defaultCliDirectory, dedicatedMcpDirectory, resolveWalletProfile } from '../storage/profiles.js';
8
9
  import { hiddenPrompt, requireTerminal, showRecovery, terminalPrompt } from './terminal.js';
@@ -22,13 +23,6 @@ async function choose(prompt) {
22
23
  throw new AttoError('INVALID_INPUT', 'Choose 1 or 2.');
23
24
  return answer;
24
25
  }
25
- function formatPolicy(policy) {
26
- const perPayment = policy.perRequest ? `${policy.perRequest.amount} ${policy.perRequest.unit}` : 'Unlimited';
27
- const rolling = policy.rolling.length
28
- ? policy.rolling.map(rule => `${rule.amount} ${rule.unit} / ${rule.days} day${rule.days === 1 ? '' : 's'}`).join(', ')
29
- : 'Unlimited';
30
- return `Per payment: ${perPayment}; rolling: ${rolling}`;
31
- }
32
26
  function showProposal(review) {
33
27
  const { proposal } = review;
34
28
  process.stderr.write([
@@ -217,6 +211,9 @@ export async function setupMarketplaceWallet({ directory, controllerIndex, reuse
217
211
  const messageSigningIndexes = typedControllerApprovals ? usage.messageSigningIndexes : reuseExisting
218
212
  ? [...new Set([...usage.messageSigningIndexes, controllerIndex])].sort((a, b) => a - b) : [controllerIndex];
219
213
  const proposal = reuseExisting ? await application.store.withWalletLock(async () => {
214
+ if (application.store.get('wallet.reset')) {
215
+ throw new AttoError('WALLET_RESET_REQUIRED', 'Finish wallet reset before configuring Marketplace.');
216
+ }
220
217
  // Fail rather than replacing authority changed by another CLI/MCP session
221
218
  // while the user was answering terminal prompts.
222
219
  if (!isDeepStrictEqual(usage, {
@@ -226,13 +223,16 @@ export async function setupMarketplaceWallet({ directory, controllerIndex, reuse
226
223
  || !isDeepStrictEqual(status.identity, application.store.get('identity'))) {
227
224
  throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings or authority changed during setup. Review the current wallet and run setup again.');
228
225
  }
226
+ if (isDeepStrictEqual(usage, { policy, access: 'spend', pool, messageSigningIndexes }))
227
+ return null;
229
228
  return application.ledger.proposePolicy(policy, 'spend', {
230
229
  directory: profile.directory, walletFingerprint: status.identity.fingerprint, network: status.settings.network,
231
230
  }, pool, messageSigningIndexes);
232
231
  }) : (await application.call('limits_propose', {
233
232
  policy, access: 'spend', pool, messageSigningIndexes,
234
233
  })).proposal;
235
- await approve(application, proposal.id);
234
+ if (proposal)
235
+ await approve(application, proposal.id);
236
236
  return { directory: profile.directory, address: controller.address, index: controller.index };
237
237
  }
238
238
  finally {
@@ -23,3 +23,5 @@ export declare function signMarketplaceAttoController(options: {
23
23
  request: unknown;
24
24
  terminalConfirmed: true;
25
25
  }): Promise<import("./marketplace/proof-approval.js").MarketplaceProofApprovalResponse>;
26
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup, type MarketplaceWalletSetupSnapshot } from './marketplace/wallet-setup.js';
27
+ export { assertPrivatePermissions, assertPrivatePermissionsBatch, securePrivatePermissions, syncPrivateDirectory, type PrivatePath } from './storage/private-permissions.js';
@@ -48,3 +48,5 @@ export async function signMarketplaceAttoController(options) {
48
48
  await application.close();
49
49
  }
50
50
  }
51
+ export { inspectMarketplaceWalletSetup, withUnchangedMarketplaceWalletSetup } from './marketplace/wallet-setup.js';
52
+ export { assertPrivatePermissions, assertPrivatePermissionsBatch, securePrivatePermissions, syncPrivateDirectory } from './storage/private-permissions.js';
@@ -1,7 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { AttoError } from '../domain/errors.js';
5
+ import { assertPrivatePermissions, securePrivatePermissions, syncPrivateDirectory } from '../storage/private-permissions.js';
5
6
  const MAX_REQUEST_BYTES = 32_768;
6
7
  const PRIVATE_FILE_MODE = 0o600;
7
8
  export function readMarketplaceProofApprovalRequest(pathValue) {
@@ -10,14 +11,15 @@ export function readMarketplaceProofApprovalRequest(pathValue) {
10
11
  const path = resolve(pathValue);
11
12
  let descriptor;
12
13
  try {
14
+ assertRealParent(path);
13
15
  const before = lstatSync(path);
14
- if (!before.isFile() || before.isSymbolicLink() || !ownedByCurrentUser(before.uid)
15
- || (before.mode & 0o022) !== 0 || before.size < 2 || before.size > MAX_REQUEST_BYTES)
16
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1
17
+ || (process.platform !== 'win32' && (!ownedByCurrentUser(before.uid) || (before.mode & 0o022) !== 0)) || before.size < 2 || before.size > MAX_REQUEST_BYTES)
16
18
  throw invalidFile();
17
19
  descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
18
20
  const info = fstatSync(descriptor);
19
- if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino || !ownedByCurrentUser(info.uid)
20
- || (info.mode & 0o022) !== 0 || info.size < 2 || info.size > MAX_REQUEST_BYTES)
21
+ if (!info.isFile() || info.nlink !== 1 || info.dev !== before.dev || info.ino !== before.ino
22
+ || (process.platform !== 'win32' && (!ownedByCurrentUser(info.uid) || (info.mode & 0o022) !== 0)) || info.size < 2 || info.size > MAX_REQUEST_BYTES)
21
23
  throw invalidFile();
22
24
  const bytes = readFileSync(descriptor);
23
25
  if (bytes.length > MAX_REQUEST_BYTES)
@@ -43,17 +45,19 @@ export function writeMarketplaceProofApprovalResponse(requestPathValue, response
43
45
  if (!/^[a-f0-9]{32}\.request\.json$/.test(requestName) || requestName.slice(0, 32) !== response.handoffId)
44
46
  throw invalidFile();
45
47
  const directoryPath = dirname(requestPath);
48
+ assertRealParent(requestPath);
46
49
  const directory = lstatSync(directoryPath);
47
50
  const request = lstatSync(requestPath);
48
- if (!directory.isDirectory() || directory.isSymbolicLink() || !ownedByCurrentUser(directory.uid)
49
- || (directory.mode & 0o022) !== 0 || !request.isFile() || request.isSymbolicLink() || !ownedByCurrentUser(request.uid))
51
+ if (!directory.isDirectory() || directory.isSymbolicLink() || !request.isFile() || request.isSymbolicLink() || request.nlink !== 1
52
+ || (process.platform !== 'win32' && (!ownedByCurrentUser(directory.uid) || (directory.mode & 0o022) !== 0
53
+ || !ownedByCurrentUser(request.uid))))
50
54
  throw invalidFile();
51
55
  const responsePath = join(directoryPath, `${response.handoffId}.response.json`);
52
56
  const temporaryPath = join(directoryPath, `.${randomBytes(16).toString('hex')}.tmp`);
53
57
  let descriptor;
54
58
  try {
55
59
  descriptor = openSync(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, PRIVATE_FILE_MODE);
56
- fchmodSync(descriptor, PRIVATE_FILE_MODE);
60
+ securePrivatePermissions(temporaryPath, 'file');
57
61
  writeFileSync(descriptor, `${JSON.stringify(response)}\n`, { encoding: 'utf8' });
58
62
  fsyncSync(descriptor);
59
63
  closeSync(descriptor);
@@ -66,13 +70,24 @@ export function writeMarketplaceProofApprovalResponse(requestPathValue, response
66
70
  throw new AttoError('MARKETPLACE_APPROVAL_EXISTS', 'An approval response file already exists. Keep the exact response or request a new Marketplace challenge.');
67
71
  throw error;
68
72
  }
69
- const directoryFd = openSync(directoryPath, constants.O_RDONLY | constants.O_DIRECTORY);
70
73
  try {
71
- fsyncSync(directoryFd);
74
+ unlinkSync(temporaryPath);
75
+ }
76
+ catch (error) {
77
+ if (error.code !== 'ENOENT')
78
+ throw error;
72
79
  }
73
- finally {
74
- closeSync(directoryFd);
80
+ assertPrivatePermissions(responsePath, 'file');
81
+ if (process.platform === 'win32') {
82
+ const publishedFd = openSync(responsePath, constants.O_RDWR | constants.O_NOFOLLOW);
83
+ try {
84
+ fsyncSync(publishedFd);
85
+ }
86
+ finally {
87
+ closeSync(publishedFd);
88
+ }
75
89
  }
90
+ syncPrivateDirectory(directoryPath);
76
91
  return responsePath;
77
92
  }
78
93
  catch (error) {
@@ -89,6 +104,17 @@ export function writeMarketplaceProofApprovalResponse(requestPathValue, response
89
104
  catch { /* No temp file remains if link failed or cleanup already ran. */ }
90
105
  }
91
106
  }
107
+ function assertRealParent(path) {
108
+ for (let current = dirname(path);;) {
109
+ const info = lstatSync(current);
110
+ if (!info.isDirectory() || info.isSymbolicLink())
111
+ throw invalidFile();
112
+ const parent = dirname(current);
113
+ if (parent === current)
114
+ return;
115
+ current = parent;
116
+ }
117
+ }
92
118
  function ownedByCurrentUser(uid) {
93
119
  return typeof process.getuid === 'function' && uid === process.getuid();
94
120
  }
@@ -0,0 +1,35 @@
1
+ import { type LimitsProposal, type McpAccess } from '../spending/ledger.js';
2
+ import { type WalletProfile } from '../storage/profiles.js';
3
+ import type { AccountPool, NetworkName, SpendingPolicy, WalletAddress, WalletIdentity, WalletSettings } from '../wallet/types.js';
4
+ /** Public saved state only. Recovery credentials and payment journals never enter this snapshot. */
5
+ export interface MarketplaceWalletSetupSnapshot {
6
+ directory: string;
7
+ profile: WalletProfile;
8
+ address: string;
9
+ index: number;
10
+ fingerprint: string;
11
+ network: `atto:${Lowercase<NetworkName>}`;
12
+ identity: WalletIdentity;
13
+ settings: WalletSettings;
14
+ addresses: WalletAddress[];
15
+ access: McpAccess;
16
+ policy: SpendingPolicy;
17
+ pool: AccountPool;
18
+ messageSigningIndexes: number[];
19
+ authorityRevision: number;
20
+ proposal: LimitsProposal | null;
21
+ formattedLimits: string;
22
+ }
23
+ export declare function formatSpendingPolicy(policy: SpendingPolicy): string;
24
+ /** Short saved-state inspection; the wallet lock is released before terminal questions. */
25
+ export declare function inspectMarketplaceWalletSetup(options: {
26
+ directory: string;
27
+ index: number;
28
+ }): Promise<MarketplaceWalletSetupSnapshot>;
29
+ /** Persist Marketplace-owned selections only while the reviewed shared wallet remains unchanged. */
30
+ export declare function withUnchangedMarketplaceWalletSetup<T>(options: {
31
+ directory: string;
32
+ index: number;
33
+ expected: MarketplaceWalletSetupSnapshot;
34
+ terminalConfirmed: true;
35
+ }, action: () => Promise<T>): Promise<T>;
@@ -0,0 +1,119 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { AttoAddress } from '@attocash/commons-core';
6
+ import { requireTerminal } from '../cli/terminal.js';
7
+ import { AttoError } from '../domain/errors.js';
8
+ import { SpendLedger } from '../spending/ledger.js';
9
+ import { inspectWalletProfile } from '../storage/profiles.js';
10
+ import { StateStore } from '../storage/state.js';
11
+ import { assertPrivatePermissionsBatch } from '../storage/private-permissions.js';
12
+ export function formatSpendingPolicy(policy) {
13
+ const perPayment = policy.perRequest ? `${policy.perRequest.amount} ${policy.perRequest.unit}` : 'Unlimited';
14
+ const rolling = policy.rolling.length
15
+ ? policy.rolling.map(rule => `${rule.amount} ${rule.unit} / ${rule.days} day${rule.days === 1 ? '' : 's'}`).join(', ')
16
+ : 'Unlimited';
17
+ return `Per payment: ${perPayment}; rolling: ${rolling}`;
18
+ }
19
+ function snapshot(store, index) {
20
+ if (store.get('wallet.reset'))
21
+ throw new AttoError('WALLET_RESET_REQUIRED', 'Finish wallet reset before configuring Marketplace.');
22
+ const identity = store.get('identity');
23
+ const settings = store.get('settings');
24
+ if (!identity || typeof identity.address !== 'string' || typeof identity.fingerprint !== 'string' || !settings) {
25
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'Choose an initialized existing CLI wallet or use advanced wallet setup.');
26
+ }
27
+ if (!['LIVE', 'BETA', 'DEV', 'LOCAL'].includes(settings.network)) {
28
+ throw new AttoError('INVALID_STATE', 'The selected wallet network is invalid. Review it in the Atto CLI before setup.');
29
+ }
30
+ const addresses = store.get('addresses') ?? [];
31
+ if (!Array.isArray(addresses))
32
+ throw new AttoError('INVALID_STATE', 'The saved wallet addresses are invalid.');
33
+ const address = addresses.find(value => value?.index === index);
34
+ if (!address) {
35
+ throw new AttoError('MARKETPLACE_ADVANCED_SETUP_REQUIRED', 'This account index has no saved wallet address. Derive it in advanced Atto CLI wallet setup before selecting it for Marketplace.');
36
+ }
37
+ try {
38
+ if (!/^[0-9a-f]{64}$/.test(identity.fingerprint)
39
+ || AttoAddress.parse(identity.address).value !== identity.address
40
+ || AttoAddress.parse(address.address).value !== address.address)
41
+ throw new Error();
42
+ }
43
+ catch {
44
+ throw new AttoError('INVALID_STATE', 'The saved wallet identity or account address is invalid. Review it in the Atto CLI before setup.');
45
+ }
46
+ const ledger = new SpendLedger(store);
47
+ const policy = ledger.policy();
48
+ const authorityRevision = store.get('spending.policyRevision') ?? 0;
49
+ if (!Number.isSafeInteger(authorityRevision) || authorityRevision < 0 || authorityRevision === Number.MAX_SAFE_INTEGER) {
50
+ throw new AttoError('INVALID_STATE', 'The saved spending-policy revision is invalid.');
51
+ }
52
+ return {
53
+ directory: store.directory, profile: inspectWalletProfile(store.directory), address: address.address, index,
54
+ fingerprint: identity.fingerprint, network: `atto:${settings.network.toLowerCase()}`,
55
+ identity, settings, addresses, policy, access: ledger.mcpAccess(), pool: ledger.pool(),
56
+ messageSigningIndexes: ledger.messageSigningIndexes(), authorityRevision, proposal: ledger.proposal(),
57
+ formattedLimits: formatSpendingPolicy(policy),
58
+ };
59
+ }
60
+ async function withExistingWallet(options, action) {
61
+ requireTerminal();
62
+ if (!options.directory || !isAbsolute(options.directory)) {
63
+ throw new AttoError('INVALID_INPUT', 'Marketplace setup requires an explicit absolute existing wallet directory.');
64
+ }
65
+ if (!Number.isSafeInteger(options.index) || options.index < 0 || options.index > 0x7fff_ffff) {
66
+ throw new AttoError('INVALID_INPUT', 'The Marketplace account index must be a nonnegative integer.');
67
+ }
68
+ const profile = inspectWalletProfile(options.directory);
69
+ if (!existsSync(join(profile.directory, 'state.sqlite'))) {
70
+ throw new AttoError('WALLET_NOT_INITIALIZED', 'Choose an initialized existing CLI wallet or use advanced wallet setup.');
71
+ }
72
+ // Check the existing Windows database before even read-only schema inspection.
73
+ // New wallet state is still opened only after the normal lifecycle lease.
74
+ if (process.platform === 'win32')
75
+ assertPrivatePermissionsBatch([
76
+ { path: profile.directory, kind: 'directory' },
77
+ ...['', '-journal', '-wal', '-shm'].map(suffix => ({
78
+ path: join(profile.directory, `state.sqlite${suffix}`), kind: 'file', optional: suffix !== '',
79
+ })),
80
+ ]);
81
+ // Compact setup must not implicitly upgrade or repair an older profile.
82
+ const inspection = new DatabaseSync(join(profile.directory, 'state.sqlite'), { readOnly: true });
83
+ try {
84
+ const version = inspection.prepare('PRAGMA user_version').get()?.user_version;
85
+ const table = inspection.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'settings'").get();
86
+ if (version !== 2 || !table) {
87
+ throw new AttoError('STATE_VERSION', 'Open and review this wallet in the current Atto CLI before using compact Marketplace setup.');
88
+ }
89
+ }
90
+ finally {
91
+ inspection.close();
92
+ }
93
+ // Reuse the normal wallet lifecycle lease and mutation lock. Unlike opening
94
+ // AttoApplication, this never initializes settings, accesses credentials,
95
+ // derives addresses, or reconciles financial records.
96
+ const store = new StateStore(profile.directory);
97
+ try {
98
+ return await store.withWalletLock(() => action(store));
99
+ }
100
+ finally {
101
+ store.close();
102
+ }
103
+ }
104
+ /** Short saved-state inspection; the wallet lock is released before terminal questions. */
105
+ export function inspectMarketplaceWalletSetup(options) {
106
+ return withExistingWallet(options, async (store) => snapshot(store, options.index));
107
+ }
108
+ /** Persist Marketplace-owned selections only while the reviewed shared wallet remains unchanged. */
109
+ export async function withUnchangedMarketplaceWalletSetup(options, action) {
110
+ requireTerminal();
111
+ if (options.terminalConfirmed !== true)
112
+ throw new AttoError('LOCAL_APPROVAL_REQUIRED', 'Local terminal approval is required.');
113
+ return withExistingWallet(options, async (store) => {
114
+ if (!isDeepStrictEqual(options.expected, snapshot(store, options.index))) {
115
+ throw new AttoError('PROPOSAL_STALE', 'The shared wallet settings, identity, or authority changed during setup. Review it and run setup again.');
116
+ }
117
+ return action();
118
+ });
119
+ }
@@ -0,0 +1,19 @@
1
+ export type PrivatePathKind = 'file' | 'directory';
2
+ export interface PrivatePath {
3
+ path: string;
4
+ kind: PrivatePathKind;
5
+ /** Missing sidecars are allowed; existing artifacts always require validation. */
6
+ optional?: boolean;
7
+ }
8
+ /** Check ordinary file metadata and POSIX ownership/modes. Windows uses the
9
+ * permissions inherited from the user's directory; Node does not verify ACLs. */
10
+ export declare function assertPrivatePermissionsBatch(paths: readonly PrivatePath[]): void;
11
+ export declare function assertPrivatePermissions(path: string, kind: PrivatePathKind): void;
12
+ /** Apply POSIX owner-only modes before writing; check metadata on Windows. */
13
+ export declare function securePrivatePermissions(path: string, kind: PrivatePathKind): void;
14
+ /**
15
+ * POSIX persists directory entries. Windows has no portable directory-fsync
16
+ * equivalent: callers must fsync the published file, including after a rename
17
+ * or link. This does not promise power-loss durability of the parent namespace.
18
+ */
19
+ export declare function syncPrivateDirectory(path: string): void;
@@ -0,0 +1,88 @@
1
+ import { chmodSync, closeSync, constants, fsyncSync, lstatSync, openSync } from 'node:fs';
2
+ import { dirname, resolve, win32 } from 'node:path';
3
+ /** Check ordinary file metadata and POSIX ownership/modes. Windows uses the
4
+ * permissions inherited from the user's directory; Node does not verify ACLs. */
5
+ export function assertPrivatePermissionsBatch(paths) {
6
+ privatePermissionsBatch(paths, false);
7
+ }
8
+ export function assertPrivatePermissions(path, kind) {
9
+ assertPrivatePermissionsBatch([{ path, kind }]);
10
+ }
11
+ /** Apply POSIX owner-only modes before writing; check metadata on Windows. */
12
+ export function securePrivatePermissions(path, kind) {
13
+ privatePermissionsBatch([{ path, kind }], true);
14
+ }
15
+ function privatePermissionsBatch(paths, secure) {
16
+ for (const entry of paths) {
17
+ if (entry.kind !== 'file' && entry.kind !== 'directory')
18
+ throw privatePermissionsError();
19
+ const path = checkedPath(entry.path);
20
+ try {
21
+ const info = inspectPath(path, entry.kind);
22
+ if (process.platform !== 'win32') {
23
+ const mode = entry.kind === 'directory' ? 0o700 : 0o600;
24
+ if (secure)
25
+ chmodSync(path, mode);
26
+ else if ((info.mode & 0o777) !== mode)
27
+ throw privatePermissionsError();
28
+ }
29
+ }
30
+ catch (error) {
31
+ if (!entry.optional || error.code !== 'ENOENT')
32
+ throw error;
33
+ }
34
+ }
35
+ }
36
+ /**
37
+ * POSIX persists directory entries. Windows has no portable directory-fsync
38
+ * equivalent: callers must fsync the published file, including after a rename
39
+ * or link. This does not promise power-loss durability of the parent namespace.
40
+ */
41
+ export function syncPrivateDirectory(path) {
42
+ if (process.platform === 'win32')
43
+ return;
44
+ const descriptor = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
45
+ try {
46
+ fsyncSync(descriptor);
47
+ }
48
+ finally {
49
+ closeSync(descriptor);
50
+ }
51
+ }
52
+ function checkedPath(path) {
53
+ if (typeof path !== 'string' || path.length === 0 || path.includes('\0'))
54
+ throw privatePermissionsError();
55
+ if (process.platform !== 'win32')
56
+ return resolve(path);
57
+ // Exclude DOS devices, alternate streams and Win32 name aliases. They do not
58
+ // identify an ordinary local file with the same semantics as our callers.
59
+ if (!/^[a-z]:[\\/]/i.test(path) || /[\u0000-\u001f\u007f]/.test(path))
60
+ throw privatePermissionsError();
61
+ for (const component of path.slice(3).split(/[\\/]/)) {
62
+ if (component === '.' || component === '..' || /[<>:"|?*]/.test(component) || /[. ]$/.test(component)
63
+ || /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(component))
64
+ throw privatePermissionsError();
65
+ }
66
+ return win32.resolve(path);
67
+ }
68
+ function inspectPath(path, kind) {
69
+ const parentDirectory = process.platform === 'win32' ? win32.dirname : dirname;
70
+ let ancestor = parentDirectory(path);
71
+ for (;;) {
72
+ if (lstatSync(ancestor).isSymbolicLink())
73
+ throw privatePermissionsError();
74
+ const parent = parentDirectory(ancestor);
75
+ if (parent === ancestor)
76
+ break;
77
+ ancestor = parent;
78
+ }
79
+ const info = lstatSync(path);
80
+ if (info.isSymbolicLink() || (kind === 'directory' ? !info.isDirectory() : !info.isFile()))
81
+ throw privatePermissionsError();
82
+ if (process.platform !== 'win32' && (typeof process.getuid !== 'function' || info.uid !== process.getuid()))
83
+ throw privatePermissionsError();
84
+ return info;
85
+ }
86
+ function privatePermissionsError() {
87
+ return Object.assign(new Error('Private file metadata or permissions could not be verified.'), { code: 'PRIVATE_PERMISSIONS' });
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@attocash/cli",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Atto wallet CLI and reusable wallet engine with local key custody and shared spending limits",
5
5
  "license": "BSD-3-Clause",
6
6
  "type": "module",