@gaganref/confect-alchemy 10.6.0-fork.2 → 10.6.0-fork.21

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,12 +1,19 @@
1
+ import * as Arr from "effect/Array";
2
+ import * as Str from "effect/String";
1
3
  import * as Config from "effect/Config";
2
4
  import * as Context from "effect/Context";
5
+ import * as Deferred from "effect/Deferred";
3
6
  import * as Effect from "effect/Effect";
4
7
  import * as FileSystem from "effect/FileSystem";
5
8
  import * as Layer from "effect/Layer";
6
9
  import * as Path from "effect/Path";
7
10
  import * as Redacted from "effect/Redacted";
11
+ import * as Result from "effect/Result";
8
12
  import * as Schema from "effect/Schema";
13
+ import * as Stream from "effect/Stream";
9
14
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
+ import { Buffer } from "node:buffer";
16
+ import { stripVTControlCharacters } from "node:util";
10
17
 
11
18
  export interface PrepareCommand {
12
19
  readonly command: string;
@@ -42,7 +49,20 @@ export class CommandError extends Schema.TaggedError<
42
49
  operation: Schema.Literals(["prepare", "deploy"]),
43
50
  reason: Schema.Literals(["configuration", "spawn", "exit"]),
44
51
  exitCode: Schema.optionalKey(Schema.Finite),
45
- }) {}
52
+ signal: Schema.optionalKey(Schema.String),
53
+ stdout: Schema.optionalKey(Schema.String),
54
+ stderr: Schema.optionalKey(Schema.String),
55
+ }) {
56
+ override get message(): string {
57
+ const status =
58
+ this.signal === undefined
59
+ ? this.exitCode === undefined
60
+ ? this.reason
61
+ : `exit code ${this.exitCode}`
62
+ : `signal ${this.signal}`;
63
+ return `${this.operation} command failed (${status})${this.stdout === undefined ? "" : `\nstdout:\n${this.stdout}`}${this.stderr === undefined ? "" : `\nstderr:\n${this.stderr}`}`;
64
+ }
65
+ }
46
66
 
47
67
  export class CommandRunner extends Context.Service<
48
68
  CommandRunner,
@@ -124,6 +144,92 @@ const packageBin = Effect.fn("CommandRunner.packageBin")(function* (
124
144
  }
125
145
  });
126
146
 
147
+ const outputTailSize = 8192;
148
+ const redaction = "<REDACTED>";
149
+ // Short needles match common diagnostic text rather than useful credentials.
150
+ const minimumCredentialLength = 8;
151
+
152
+ const outputTail = <E>(
153
+ stream: Stream.Stream<Uint8Array, E>,
154
+ secrets: ReadonlyArray<string>,
155
+ ) => {
156
+ const credentials = Arr.flatMap(
157
+ Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),
158
+ (value: string) => {
159
+ const bytes = Buffer.from(value);
160
+ const base64 = Arr.flatMap(
161
+ ["base64", "base64url"] as const,
162
+ (encoding) => [
163
+ Str.replace(/=+$/, "")(bytes.toString(encoding)),
164
+ ...Arr.map([0, 1, 2], (offset) =>
165
+ // The first and last partial sextets depend on bytes outside the key.
166
+ Str.slice(
167
+ Math.ceil((offset * 8) / 6),
168
+ Math.floor(((offset + bytes.length) * 8) / 6),
169
+ )(Buffer.concat([Buffer.alloc(offset), bytes]).toString(encoding)),
170
+ ),
171
+ ],
172
+ );
173
+ return [value, ...base64];
174
+ },
175
+ );
176
+ const percentEncoded = Arr.map(
177
+ Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),
178
+ (value) =>
179
+ Arr.join(
180
+ Arr.map(
181
+ Str.split(/(%[0-9A-F]{2})/)(encodeURIComponent(value)),
182
+ (part) =>
183
+ Str.startsWith("%")(part)
184
+ ? Arr.join(
185
+ Arr.map(Str.split("")(part), (char) =>
186
+ /[A-F]/.test(char)
187
+ ? `[${char}${Str.toLowerCase(char)}]`
188
+ : char,
189
+ ),
190
+ "",
191
+ )
192
+ : Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(part),
193
+ ),
194
+ "",
195
+ ),
196
+ );
197
+ return stream.pipe(
198
+ Stream.decodeText(),
199
+ Stream.runFold(
200
+ () => ({ text: "", truncated: false }),
201
+ (tail, chunk) => {
202
+ const text = tail.text + chunk;
203
+ return {
204
+ text: Str.slice(-outputTailSize)(text),
205
+ truncated: tail.truncated || text.length > outputTailSize,
206
+ };
207
+ },
208
+ ),
209
+ Effect.map(({ text, truncated }) => {
210
+ text = stripVTControlCharacters(text);
211
+ if (truncated) {
212
+ // A clipped token may be an unrecognised deploy key. Drop it whole.
213
+ text = Str.replace(/^\S*/, "")(text);
214
+ }
215
+ const pattern = new RegExp(
216
+ Arr.join(
217
+ [
218
+ "(?:prod|dev|preview|project|custom):[^\\s|]+\\|[^\\s\\\\\"'&)]+",
219
+ ...percentEncoded,
220
+ ...Arr.map(credentials, (value) =>
221
+ Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(value),
222
+ ),
223
+ ],
224
+ "|",
225
+ ),
226
+ "g",
227
+ );
228
+ return Str.slice(-outputTailSize)(Str.replace(pattern, redaction)(text));
229
+ }),
230
+ );
231
+ };
232
+
127
233
  /**
128
234
  * @internal
129
235
  */
@@ -139,7 +245,77 @@ export const layer = Layer.effect(
139
245
  args: ReadonlyArray<string>,
140
246
  cwd: string,
141
247
  env: Record<string, string | undefined>,
248
+ credentials: ReadonlyArray<string> = [],
142
249
  ) {
250
+ if (operation === "deploy") {
251
+ return yield* Effect.scoped(
252
+ Effect.gen(function* () {
253
+ const child = yield* spawner.spawn(
254
+ ChildProcess.make(command, args, {
255
+ cwd,
256
+ env,
257
+ extendEnv: false,
258
+ stdin: "ignore",
259
+ stdout: "pipe",
260
+ stderr: "pipe",
261
+ }),
262
+ );
263
+ const exited = yield* Deferred.make<void>();
264
+ // Descendants can inherit pipes and keep them open after the CLI exits.
265
+ const drainDeadline = Deferred.await(exited).pipe(
266
+ Effect.andThen(Effect.sleep("1 second")),
267
+ );
268
+ const [code, stdout, stderr] = yield* Effect.all(
269
+ [
270
+ child.exitCode.pipe(
271
+ Effect.result,
272
+ Effect.tap(() => Deferred.succeed(exited, undefined)),
273
+ ),
274
+ outputTail(
275
+ child.stdout.pipe(Stream.interruptWhen(drainDeadline)),
276
+ credentials,
277
+ ),
278
+ outputTail(
279
+ child.stderr.pipe(Stream.interruptWhen(drainDeadline)),
280
+ credentials,
281
+ ),
282
+ ],
283
+ { concurrency: "unbounded" },
284
+ );
285
+ if (Result.isFailure(code)) {
286
+ // The spawner exposes a terminating signal only in its cause message.
287
+ const cause = code.failure.cause;
288
+ const signal =
289
+ cause instanceof Error
290
+ ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(
291
+ cause.message,
292
+ )?.[1]
293
+ : undefined;
294
+ return yield* CommandError.make({
295
+ operation,
296
+ reason: "exit",
297
+ ...(signal === undefined ? {} : { signal }),
298
+ stdout,
299
+ stderr,
300
+ });
301
+ }
302
+ if (code.success !== 0)
303
+ return yield* CommandError.make({
304
+ operation,
305
+ reason: "exit",
306
+ exitCode: Number(code.success),
307
+ stdout,
308
+ stderr,
309
+ });
310
+ }),
311
+ ).pipe(
312
+ Effect.mapError((error) =>
313
+ Schema.is(CommandError)(error)
314
+ ? error
315
+ : CommandError.make({ operation, reason: "spawn" }),
316
+ ),
317
+ );
318
+ }
143
319
  const code = yield* spawner
144
320
  .exitCode(
145
321
  ChildProcess.make(command, args, {
@@ -234,6 +410,11 @@ export const layer = Layer.effect(
234
410
  LOCALAPPDATA: temp,
235
411
  XDG_CONFIG_HOME: temp,
236
412
  },
413
+ [
414
+ Redacted.value(
415
+ target._tag === "Cloud" ? target.deployKey : target.adminKey,
416
+ ),
417
+ ],
237
418
  );
238
419
  }).pipe(
239
420
  Effect.mapError((error) =>