@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 120 lines 4.85 KB
Raw
1 /**
2 * Atomic file replacement shared by every tmp-write→rename site in the CLI
3 * (shell rc rewrites, the tool-permissions cache, analytics state).
4 *
5 * The tmp file lives next to the target so the final rename(2) stays on one
6 * filesystem and is atomic: readers observe either the old or the new
7 * contents, never a partial write. The tmp name contains a random UUID and is
8 * created exclusively so concurrent or hostile processes cannot share,
9 * replace, or redirect it. On any failure — including a failure of the initial write itself,
10 * e.g. ENOSPC mid-write — the tmp file is removed best-effort before the
11 * original error propagates, so no tmp litter is left next to the target.
12 */
13
14 import type { FileSystem, PlatformError } from 'effect';
15 import { Effect, Option, Predicate, Result } from 'effect';
16
17 const MAX_ATOMIC_WRITE_ATTEMPTS = 5;
18
19 export const atomicTmpPath = (target: string): string =>
20 `${target}.composio-tmp.${crypto.randomUUID()}`;
21
22 export const atomicWriteFileString = (params: {
23 readonly fs: FileSystem.FileSystem;
24 readonly target: string;
25 readonly contents: string;
26 /** Create the replacement with this exact mode, including over an existing target. */
27 readonly mode?: number;
28 /**
29 * Preserve an existing target's file mode across the replacement: the tmp
30 * copy is created with the target's mode from the start so private contents
31 * never sit in a default-mode, world-readable tmp file. open(2) masks the
32 * requested mode with the process umask (only ever clearing bits), so a
33 * chmod still follows to pin the exact mode. When the target does not
34 * exist (or `preserveMode` is false) the tmp is created with default mode.
35 */
36 readonly preserveMode?: boolean;
37 }): Effect.Effect<void, PlatformError.PlatformError> =>
38 Effect.gen(function* () {
39 const { fs, target, contents } = params;
40 const preservedMode = params.preserveMode
41 ? Option.map(yield* fs.stat(target).pipe(Effect.option), info => info.mode & 0o7777)
42 : Option.none<number>();
43 const targetMode = Option.fromUndefinedOr(params.mode).pipe(Option.orElse(() => preservedMode));
44 const stage = (attempt: number): Effect.Effect<string, PlatformError.PlatformError> =>
45 Effect.gen(function* () {
46 const tmpPath = atomicTmpPath(target);
47 const created = yield* Option.match(targetMode, {
48 onNone: () => fs.writeFileString(tmpPath, contents, { flag: 'wx' }),
49 onSome: mode => fs.writeFileString(tmpPath, contents, { flag: 'wx', mode }),
50 }).pipe(Effect.result);
51
52 if (Result.isFailure(created)) {
53 const isCollision = Predicate.isTagged(created.failure.reason, 'AlreadyExists');
54 if (isCollision && attempt < MAX_ATOMIC_WRITE_ATTEMPTS) {
55 return yield* stage(attempt + 1);
56 }
57 if (!isCollision) {
58 yield* fs.remove(tmpPath, { force: true }).pipe(Effect.ignore);
59 }
60 return yield* Effect.fail(created.failure);
61 }
62
63 return tmpPath;
64 });
65
66 // Effect keeps acquisition and release uninterruptible. The promotion stays
67 // interruptible, but cancellation cannot occur between staging and the
68 // cleanup responsibility being registered.
69 yield* Effect.acquireUseRelease(
70 stage(1),
71 tmpPath =>
72 Effect.gen(function* () {
73 yield* Option.match(targetMode, {
74 onNone: () => Effect.void,
75 onSome: mode => fs.chmod(tmpPath, mode),
76 });
77 yield* fs.rename(tmpPath, target);
78 }),
79 tmpPath => fs.remove(tmpPath, { force: true }).pipe(Effect.ignore)
80 );
81 });
82
83 export const atomicWritePrivateFileString = (params: {
84 readonly fs: FileSystem.FileSystem;
85 readonly target: string;
86 readonly contents: string;
87 }): Effect.Effect<void, PlatformError.PlatformError> =>
88 atomicWriteFileString({ ...params, mode: 0o600 });
89
90 /**
91 * Tighten a credential-bearing file written by an older CLI before reading it.
92 * This repairs existing files because a write mode only applies when creating
93 * a new file and cannot remove permissions from an existing one.
94 */
95 export const ensurePrivateFileMode = (params: {
96 readonly fs: FileSystem.FileSystem;
97 readonly target: string;
98 }): Effect.Effect<void> =>
99 Effect.gen(function* () {
100 const fileInfo = yield* params.fs.stat(params.target).pipe(
101 Effect.tapError(error =>
102 Effect.logWarning(
103 `Could not inspect permissions for credential file at ${params.target}; continuing with the read: ${String(error)}`
104 )
105 ),
106 Effect.option
107 );
108
109 if (Option.isNone(fileInfo) || (fileInfo.value.mode & 0o077) === 0) return;
110
111 yield* params.fs
112 .chmod(params.target, 0o600)
113 .pipe(
114 Effect.catch(error =>
115 Effect.logWarning(
116 `Could not tighten permissions for credential file at ${params.target}; continuing with the read: ${String(error)}`
117 )
118 )
119 );
120 });