movehat 0.2.1 → 0.2.3

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.
Files changed (176) hide show
  1. package/dist/__tests__/deployContract.test.js +56 -47
  2. package/dist/__tests__/deployContract.test.js.map +1 -1
  3. package/dist/__tests__/exports.test.d.ts +2 -0
  4. package/dist/__tests__/exports.test.d.ts.map +1 -0
  5. package/dist/__tests__/exports.test.js +30 -0
  6. package/dist/__tests__/exports.test.js.map +1 -0
  7. package/dist/__tests__/fixtures/sigint-deploy-harness.d.ts +4 -3
  8. package/dist/__tests__/fixtures/sigint-deploy-harness.d.ts.map +1 -1
  9. package/dist/__tests__/fixtures/sigint-deploy-harness.js +8 -7
  10. package/dist/__tests__/fixtures/sigint-deploy-harness.js.map +1 -1
  11. package/dist/__tests__/fork/api.test.js +5 -0
  12. package/dist/__tests__/fork/api.test.js.map +1 -1
  13. package/dist/__tests__/fork/api.timeout.test.d.ts +2 -0
  14. package/dist/__tests__/fork/api.timeout.test.d.ts.map +1 -0
  15. package/dist/__tests__/fork/api.timeout.test.js +98 -0
  16. package/dist/__tests__/fork/api.timeout.test.js.map +1 -0
  17. package/dist/cli.js +4 -0
  18. package/dist/cli.js.map +1 -1
  19. package/dist/commands/__tests__/compile.toml-mutation.test.d.ts +2 -0
  20. package/dist/commands/__tests__/compile.toml-mutation.test.d.ts.map +1 -0
  21. package/dist/commands/__tests__/compile.toml-mutation.test.js +69 -0
  22. package/dist/commands/__tests__/compile.toml-mutation.test.js.map +1 -0
  23. package/dist/commands/__tests__/init.test.js +73 -11
  24. package/dist/commands/__tests__/init.test.js.map +1 -1
  25. package/dist/commands/compile.d.ts.map +1 -1
  26. package/dist/commands/compile.js +19 -10
  27. package/dist/commands/compile.js.map +1 -1
  28. package/dist/commands/init.d.ts +22 -0
  29. package/dist/commands/init.d.ts.map +1 -1
  30. package/dist/commands/init.js +55 -6
  31. package/dist/commands/init.js.map +1 -1
  32. package/dist/commands/test.js +12 -19
  33. package/dist/commands/test.js.map +1 -1
  34. package/dist/core/AccountManager.d.ts.map +1 -1
  35. package/dist/core/AccountManager.js +14 -2
  36. package/dist/core/AccountManager.js.map +1 -1
  37. package/dist/core/Publisher.d.ts.map +1 -1
  38. package/dist/core/Publisher.js +72 -82
  39. package/dist/core/Publisher.js.map +1 -1
  40. package/dist/core/__tests__/AccountManager.global-state.test.d.ts +2 -0
  41. package/dist/core/__tests__/AccountManager.global-state.test.d.ts.map +1 -0
  42. package/dist/core/__tests__/AccountManager.global-state.test.js +69 -0
  43. package/dist/core/__tests__/AccountManager.global-state.test.js.map +1 -0
  44. package/dist/core/__tests__/movementProfile.test.d.ts +2 -0
  45. package/dist/core/__tests__/movementProfile.test.d.ts.map +1 -0
  46. package/dist/core/__tests__/movementProfile.test.js +112 -0
  47. package/dist/core/__tests__/movementProfile.test.js.map +1 -0
  48. package/dist/core/config.d.ts.map +1 -1
  49. package/dist/core/config.js +14 -10
  50. package/dist/core/config.js.map +1 -1
  51. package/dist/core/deployments.d.ts.map +1 -1
  52. package/dist/core/deployments.js +4 -2
  53. package/dist/core/deployments.js.map +1 -1
  54. package/dist/core/movementProfile.d.ts +55 -22
  55. package/dist/core/movementProfile.d.ts.map +1 -1
  56. package/dist/core/movementProfile.js +77 -99
  57. package/dist/core/movementProfile.js.map +1 -1
  58. package/dist/fork/__tests__/server.cors.test.d.ts +2 -0
  59. package/dist/fork/__tests__/server.cors.test.d.ts.map +1 -0
  60. package/dist/fork/__tests__/server.cors.test.js +79 -0
  61. package/dist/fork/__tests__/server.cors.test.js.map +1 -0
  62. package/dist/fork/api.d.ts +9 -1
  63. package/dist/fork/api.d.ts.map +1 -1
  64. package/dist/fork/api.js +37 -7
  65. package/dist/fork/api.js.map +1 -1
  66. package/dist/fork/manager.js +10 -10
  67. package/dist/fork/manager.js.map +1 -1
  68. package/dist/fork/server.d.ts +20 -1
  69. package/dist/fork/server.d.ts.map +1 -1
  70. package/dist/fork/server.js +40 -24
  71. package/dist/fork/server.js.map +1 -1
  72. package/dist/fork/test.d.ts.map +1 -1
  73. package/dist/fork/test.js +3 -2
  74. package/dist/fork/test.js.map +1 -1
  75. package/dist/harness/Harness.d.ts +6 -2
  76. package/dist/harness/Harness.d.ts.map +1 -1
  77. package/dist/harness/Harness.js +8 -2
  78. package/dist/harness/Harness.js.map +1 -1
  79. package/dist/harness/codeObject.d.ts.map +1 -1
  80. package/dist/harness/codeObject.js +41 -41
  81. package/dist/harness/codeObject.js.map +1 -1
  82. package/dist/harness/script.d.ts +3 -3
  83. package/dist/harness/script.d.ts.map +1 -1
  84. package/dist/harness/script.js +42 -35
  85. package/dist/harness/script.js.map +1 -1
  86. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.d.ts +2 -0
  87. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.d.ts.map +1 -0
  88. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.js +172 -0
  89. package/dist/helpers/__tests__/setupLocalTesting.fork-network.test.js.map +1 -0
  90. package/dist/helpers/setupLocalTesting.d.ts.map +1 -1
  91. package/dist/helpers/setupLocalTesting.js +31 -5
  92. package/dist/helpers/setupLocalTesting.js.map +1 -1
  93. package/dist/index.d.ts +1 -0
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/node/LocalNodeManager.d.ts +8 -0
  96. package/dist/node/LocalNodeManager.d.ts.map +1 -1
  97. package/dist/node/LocalNodeManager.js +70 -23
  98. package/dist/node/LocalNodeManager.js.map +1 -1
  99. package/dist/node/__tests__/LocalNodeManager.api-port.test.d.ts +2 -0
  100. package/dist/node/__tests__/LocalNodeManager.api-port.test.d.ts.map +1 -0
  101. package/dist/node/__tests__/LocalNodeManager.api-port.test.js +55 -0
  102. package/dist/node/__tests__/LocalNodeManager.api-port.test.js.map +1 -0
  103. package/dist/node/__tests__/LocalNodeManager.test.js +114 -14
  104. package/dist/node/__tests__/LocalNodeManager.test.js.map +1 -1
  105. package/dist/templates/move/Move.toml +1 -1
  106. package/dist/templates/move/sources/Counter.move +31 -4
  107. package/dist/templates/scripts/deploy-counter.ts +10 -0
  108. package/dist/types/config.d.ts +8 -1
  109. package/dist/types/config.d.ts.map +1 -1
  110. package/dist/ui/__tests__/logger.test.d.ts +2 -0
  111. package/dist/ui/__tests__/logger.test.d.ts.map +1 -0
  112. package/dist/ui/__tests__/logger.test.js +75 -0
  113. package/dist/ui/__tests__/logger.test.js.map +1 -0
  114. package/dist/ui/formatters.d.ts +0 -16
  115. package/dist/ui/formatters.d.ts.map +1 -1
  116. package/dist/ui/formatters.js +1 -1
  117. package/dist/ui/formatters.js.map +1 -1
  118. package/dist/ui/logger.d.ts +41 -0
  119. package/dist/ui/logger.d.ts.map +1 -1
  120. package/dist/ui/logger.js +49 -0
  121. package/dist/ui/logger.js.map +1 -1
  122. package/dist/ui/spinner.d.ts +25 -0
  123. package/dist/ui/spinner.d.ts.map +1 -1
  124. package/dist/ui/spinner.js +44 -0
  125. package/dist/ui/spinner.js.map +1 -1
  126. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.d.ts +2 -0
  127. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.d.ts.map +1 -0
  128. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.js +43 -0
  129. package/dist/utils/__tests__/childProcessAdapter.maxBuffer.test.js.map +1 -0
  130. package/dist/utils/childProcessAdapter.d.ts +7 -0
  131. package/dist/utils/childProcessAdapter.d.ts.map +1 -1
  132. package/dist/utils/childProcessAdapter.js +20 -2
  133. package/dist/utils/childProcessAdapter.js.map +1 -1
  134. package/package.json +1 -1
  135. package/src/__tests__/deployContract.test.ts +59 -50
  136. package/src/__tests__/exports.test.ts +32 -0
  137. package/src/__tests__/fixtures/sigint-deploy-harness.ts +8 -7
  138. package/src/__tests__/fork/api.test.ts +5 -0
  139. package/src/__tests__/fork/api.timeout.test.ts +150 -0
  140. package/src/cli.ts +4 -0
  141. package/src/commands/__tests__/compile.toml-mutation.test.ts +77 -0
  142. package/src/commands/__tests__/init.test.ts +96 -11
  143. package/src/commands/compile.ts +24 -15
  144. package/src/commands/init.ts +77 -6
  145. package/src/commands/test.ts +12 -19
  146. package/src/core/AccountManager.ts +18 -1
  147. package/src/core/Publisher.ts +103 -107
  148. package/src/core/__tests__/AccountManager.global-state.test.ts +83 -0
  149. package/src/core/__tests__/movementProfile.test.ts +131 -0
  150. package/src/core/config.ts +18 -11
  151. package/src/core/deployments.ts +5 -4
  152. package/src/core/movementProfile.ts +75 -127
  153. package/src/fork/__tests__/server.cors.test.ts +101 -0
  154. package/src/fork/api.ts +69 -10
  155. package/src/fork/manager.ts +10 -10
  156. package/src/fork/server.ts +59 -24
  157. package/src/fork/test.ts +3 -2
  158. package/src/harness/Harness.ts +11 -2
  159. package/src/harness/codeObject.ts +45 -48
  160. package/src/harness/script.ts +47 -43
  161. package/src/helpers/__tests__/setupLocalTesting.fork-network.test.ts +212 -0
  162. package/src/helpers/setupLocalTesting.ts +39 -5
  163. package/src/index.ts +9 -1
  164. package/src/node/LocalNodeManager.ts +87 -26
  165. package/src/node/__tests__/LocalNodeManager.api-port.test.ts +62 -0
  166. package/src/node/__tests__/LocalNodeManager.test.ts +144 -17
  167. package/src/templates/move/Move.toml +1 -1
  168. package/src/templates/move/sources/Counter.move +31 -4
  169. package/src/templates/scripts/deploy-counter.ts +10 -0
  170. package/src/types/config.ts +8 -1
  171. package/src/ui/__tests__/logger.test.ts +89 -0
  172. package/src/ui/formatters.ts +1 -1
  173. package/src/ui/logger.ts +62 -0
  174. package/src/ui/spinner.ts +47 -0
  175. package/src/utils/__tests__/childProcessAdapter.maxBuffer.test.ts +51 -0
  176. package/src/utils/childProcessAdapter.ts +32 -2
@@ -1,154 +1,102 @@
1
- import {
2
- chmodSync,
3
- existsSync,
4
- mkdirSync,
5
- readFileSync,
6
- renameSync,
7
- unlinkSync,
8
- writeFileSync,
9
- } from "fs";
10
- import { readFile } from "fs/promises";
11
- import { dirname } from "path";
1
+ import { chmodSync, existsSync, unlinkSync, writeFileSync } from "fs";
2
+ import { tmpdir } from "os";
3
+ import { join } from "path";
12
4
  import { randomUUID } from "crypto";
13
- import * as yaml from "js-yaml";
14
5
 
15
6
  /**
16
- * Shared helpers for working with the Movement CLI's `~/.aptos/config.yaml`
17
- * profile file and the SIGINT/SIGTERM cleanup pipeline.
7
+ * Per-deploy private-key file management and SIGINT/SIGTERM cleanup
8
+ * infrastructure shared across the Movement CLI invocations (`move
9
+ * publish`, `move deploy-object`, `move upgrade-object`, `move
10
+ * run-script`).
18
11
  *
19
- * Extracted from `core/Publisher.ts` so both the existing `move publish`
20
- * flow (`Publisher`) and the new `move deploy-object` / `upgrade-object`
21
- * flows (`harness/codeObject.ts`) can share the bug #36 / #37 / #43
22
- * hardening without duplicating it.
12
+ * **Why a temp key file rather than the CLI's profile yaml?** The
13
+ * Movement CLI's `--profile <name>` flag requires a config.yaml to
14
+ * exist in the working directory (older Movement CLI variants look
15
+ * for `<cwd>/.aptos/config.yaml`; newer variants look for
16
+ * `<cwd>/.movement/config.yaml`). On fresh user installs neither
17
+ * directory exists, and the CLI errors out before it would otherwise
18
+ * fall back to `~/.aptos/config.yaml`. Writing to a temp file and
19
+ * passing `--private-key-file <path> --sender-account <addr>`
20
+ * directly avoids the entire profile-yaml lookup chain — no CWD
21
+ * dependency, no CLI-variant dependency.
22
+ *
23
+ * The same SIGINT-safe cleanup pattern applies as the old profile
24
+ * flow: the temp key file persists private key material on disk and
25
+ * MUST be removed before process exit even on abnormal termination.
23
26
  *
24
27
  * @internal — not exported from `src/index.ts`.
25
28
  */
26
29
 
27
30
  /**
28
- * In-process serializer for `~/.aptos/config.yaml` mutations. Without it,
29
- * two concurrent profile writes would race in the read-modify-write cycle
30
- * and the second writer would silently drop the first's profile. See #37.
31
+ * Write the private key to a `mode 0o600` file in the system temp
32
+ * directory and return the path. The filename is UUID-suffixed so
33
+ * concurrent deploys don't collide.
34
+ *
35
+ * The key string is written verbatim — callers should format to
36
+ * AIP-80 before calling (see `PrivateKey.formatPrivateKey` from
37
+ * `@aptos-labs/ts-sdk`).
31
38
  */
32
- let yamlLock: Promise<unknown> = Promise.resolve();
33
- export function withYamlLock<T>(fn: () => Promise<T>): Promise<T> {
34
- const prev = yamlLock;
35
- // .then(success, failure) continue even if the previous holder rejected,
36
- // so a failure in one deploy doesn't poison the lock for the others.
37
- const next = prev.then(
38
- () => fn(),
39
- () => fn()
40
- );
41
- yamlLock = next.catch(() => {}); // swallow on the shared chain; caller still gets the original
42
- return next;
43
- }
44
-
45
- export interface ProfileData {
46
- private_key: string;
47
- public_key: string;
48
- account: string;
49
- rest_url: string;
50
- }
51
-
52
- interface AptosConfigYaml {
53
- profiles?: Record<string, ProfileData>;
54
- [key: string]: unknown;
39
+ export function writeTempKeyFile(privateKey: string): string {
40
+ const path = join(tmpdir(), `movehat-key-${randomUUID()}`);
41
+ // mode in the open() call may be filtered by the process umask
42
+ // (typically 0o022 resulting perms 0o644). chmod after write
43
+ // is defense in depth so the file can never be observable as
44
+ // group-/world-readable while it carries the private key.
45
+ writeFileSync(path, privateKey, { mode: 0o600 });
46
+ chmodSync(path, 0o600);
47
+ return path;
55
48
  }
56
49
 
57
50
  /**
58
- * Atomic write: write payload to a temp sibling chmod the temp to 0o600
59
- * rename over the target. The chmod-before-rename order eliminates a
60
- * window where the target file could be observable with default umask
61
- * perms (typically 0o644) while carrying the private key.
62
- */
63
- function atomicWriteYaml(path: string, content: string): void {
64
- const tmpPath = `${path}.tmp.${randomUUID().slice(0, 8)}`;
65
- writeFileSync(tmpPath, content, { mode: 0o600 });
66
- chmodSync(tmpPath, 0o600); // defense in depth in case umask filtered the open mode
67
- renameSync(tmpPath, path);
68
- }
69
-
70
- /** Add the deploy's profile to ~/.aptos/config.yaml. Creates the file if absent. */
71
- export async function addProfile(
72
- configPath: string,
73
- name: string,
74
- data: ProfileData
75
- ): Promise<void> {
76
- const configDir = dirname(configPath);
77
- if (!existsSync(configDir)) {
78
- mkdirSync(configDir, { recursive: true, mode: 0o700 });
79
- }
80
- let yamlObj: AptosConfigYaml = {};
81
- if (existsSync(configPath)) {
82
- const raw = await readFile(configPath, "utf-8");
83
- yamlObj = (yaml.load(raw) as AptosConfigYaml) || {};
84
- }
85
- if (!yamlObj.profiles) yamlObj.profiles = {};
86
- yamlObj.profiles[name] = data;
87
- atomicWriteYaml(configPath, yaml.dump(yamlObj));
88
- }
89
-
90
- /**
91
- * Remove the deploy's profile from ~/.aptos/config.yaml. Idempotent —
92
- * a missing file or missing profile is a no-op. If removal leaves the
93
- * yaml with only an empty `profiles:` block, the whole file is unlinked
94
- * to preserve the "didn't exist before" semantic for the first-ever deploy.
51
+ * Sync unlink for SIGINT/SIGTERM handlers never throws, never logs.
52
+ * The event loop is dead by the time this runs; observability isn't
53
+ * possible. Worst case: a stale 0o600 temp file in `os.tmpdir()`
54
+ * that the OS reaps eventually.
55
+ *
56
+ * **Do not use this from a normal `finally` cleanup path** — failures
57
+ * become invisible there, hiding the case where a private-key temp
58
+ * file persists on disk after a deploy. Use {@link removeKeyFile}
59
+ * instead for those paths.
95
60
  */
96
- export async function removeProfile(configPath: string, name: string): Promise<void> {
97
- if (!existsSync(configPath)) return;
98
- const raw = await readFile(configPath, "utf-8");
99
- const yamlObj: AptosConfigYaml = (yaml.load(raw) as AptosConfigYaml) || {};
100
- if (!yamlObj.profiles || !(name in yamlObj.profiles)) return;
101
- delete yamlObj.profiles[name];
102
-
103
- const profilesEmpty = Object.keys(yamlObj.profiles).length === 0;
104
- const onlyProfilesKey =
105
- Object.keys(yamlObj).length === 1 && "profiles" in yamlObj;
106
- if (profilesEmpty && onlyProfilesKey) {
107
- // We created this file fresh; remove it.
108
- try {
109
- unlinkSync(configPath);
110
- } catch {
111
- // best-effort
112
- }
113
- return;
61
+ export function removeKeyFileSyncBestEffort(path: string): void {
62
+ try {
63
+ unlinkSync(path);
64
+ } catch {
65
+ // event loop dead best-effort
114
66
  }
115
- atomicWriteYaml(configPath, yaml.dump(yamlObj));
116
67
  }
117
68
 
118
69
  /**
119
- * Synchronous twin of `removeProfile` for the SIGINT/SIGTERM handler.
120
- * The event loop is dead by the time the handler runs we cannot
121
- * await. Bypasses the async mutex because signal handlers are
122
- * sequential by construction; the operation is idempotent so a
123
- * benign double-delete (handler then finally, or vice versa) is fine.
70
+ * Sync unlink for the normal cleanup path (a `finally` block after the
71
+ * Movement CLI invocation returns). Returns `null` on successeither
72
+ * the file was removed, or it was already gone (ENOENT is treated as
73
+ * benign success). Returns an `Error` only when the file **still
74
+ * exists on disk** after the unlink attempt failed (EPERM, EACCES,
75
+ * EBUSY, EISDIR if the path collided with a directory, etc.).
76
+ *
77
+ * Callers SHOULD `logger.warning` when a non-null Error is returned —
78
+ * a private-key temp file would otherwise persist silently.
124
79
  */
125
- export function removeProfileSync(configPath: string, name: string): void {
80
+ export function removeKeyFile(path: string): Error | null {
126
81
  try {
127
- if (!existsSync(configPath)) return;
128
- const raw = readFileSync(configPath, "utf-8");
129
- const yamlObj: AptosConfigYaml = (yaml.load(raw) as AptosConfigYaml) || {};
130
- if (!yamlObj.profiles || !(name in yamlObj.profiles)) return;
131
- delete yamlObj.profiles[name];
132
-
133
- const profilesEmpty = Object.keys(yamlObj.profiles).length === 0;
134
- const onlyProfilesKey =
135
- Object.keys(yamlObj).length === 1 && "profiles" in yamlObj;
136
- if (profilesEmpty && onlyProfilesKey) {
137
- unlinkSync(configPath);
138
- return;
139
- }
140
- atomicWriteYaml(configPath, yaml.dump(yamlObj));
141
- } catch {
142
- // Signal handlers should never throw — swallow and exit. Better to
143
- // leave a stale profile (recoverable by re-running the deploy) than
144
- // to crash the parent process mid-shutdown.
82
+ unlinkSync(path);
83
+ return null;
84
+ } catch (err) {
85
+ const code = (err as NodeJS.ErrnoException).code;
86
+ if (code === "ENOENT") return null;
87
+ // The unlink call failed but verify the file actually still exists
88
+ // before declaring this preocupante — some races (parallel cleanup,
89
+ // tmpdir reaper) can race with us and the file may already be gone
90
+ // despite the syscall reporting an unexpected error.
91
+ if (!existsSync(path)) return null;
92
+ return err instanceof Error ? err : new Error(String(err));
145
93
  }
146
94
  }
147
95
 
148
96
  /**
149
97
  * Process-level signal handling. A single registered handler iterates
150
- * the per-deploy cleanup callbacks. Install-once because multiple
151
- * concurrent deploys share the same parent process — installing per
98
+ * the per-deploy cleanup callbacks. Installed once per process because
99
+ * multiple concurrent deploys share the same parent — installing per
152
100
  * deploy would re-add the listener and exceed Node's max-listeners
153
101
  * warning threshold under heavy parallelism.
154
102
  */
@@ -159,7 +107,7 @@ export function ensureSignalHandler(): void {
159
107
  if (signalHandlerInstalled) return;
160
108
  signalHandlerInstalled = true;
161
109
  const handler = (sig: NodeJS.Signals) => {
162
- // Synchronous cleanup of every active deploy's profile entry.
110
+ // Synchronous cleanup of every active deploy's resources.
163
111
  for (const cb of [...cleanupCallbacks]) {
164
112
  try {
165
113
  cb();
@@ -0,0 +1,101 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
2
+ import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { AddressInfo } from "node:net";
6
+
7
+ import { ForkServer } from "../server.js";
8
+
9
+ /**
10
+ * F2 — ForkServer must not advertise `Access-Control-Allow-Origin: *`
11
+ * by default. Cached fork state may include account resources fetched
12
+ * from authenticated upstream nodes; any web page open in the dev's
13
+ * browser should not be able to read it through the loopback listener.
14
+ *
15
+ * Default contract:
16
+ * - No CORS header emitted unless the caller opts in via
17
+ * `corsAllowOrigins`.
18
+ * - When opted in, only requests whose `Origin` is in the allowlist
19
+ * receive a matching `Access-Control-Allow-Origin` (echo of origin,
20
+ * not `*`).
21
+ */
22
+
23
+ function makeForkDir(): string {
24
+ const dir = mkdtempSync(join(tmpdir(), "movehat-fork-cors-"));
25
+ mkdirSync(join(dir, "resources"), { recursive: true });
26
+ writeFileSync(
27
+ join(dir, "metadata.json"),
28
+ JSON.stringify({
29
+ network: "test",
30
+ nodeUrl: "http://example.invalid/v1",
31
+ chainId: 0,
32
+ ledgerVersion: "0",
33
+ timestamp: "0",
34
+ epoch: "0",
35
+ blockHeight: "0",
36
+ createdAt: new Date().toISOString(),
37
+ }),
38
+ );
39
+ writeFileSync(join(dir, "accounts.json"), "{}");
40
+ return dir;
41
+ }
42
+
43
+ function boundPort(server: ForkServer): number {
44
+ const internal = (server as unknown as {
45
+ server: { address(): AddressInfo };
46
+ }).server;
47
+ const addr = internal.address();
48
+ return addr.port;
49
+ }
50
+
51
+ async function fetchFromServer(
52
+ port: number,
53
+ origin?: string
54
+ ): Promise<Response> {
55
+ const headers: Record<string, string> = {};
56
+ if (origin !== undefined) headers.Origin = origin;
57
+ return fetch(`http://127.0.0.1:${port}/v1/`, { headers });
58
+ }
59
+
60
+ describe("F2 — ForkServer CORS is closed by default", () => {
61
+ let forkDir: string;
62
+ let server: ForkServer | null = null;
63
+
64
+ beforeEach(() => {
65
+ forkDir = makeForkDir();
66
+ });
67
+
68
+ afterEach(async () => {
69
+ if (server) {
70
+ await server.stop();
71
+ server = null;
72
+ }
73
+ rmSync(forkDir, { recursive: true, force: true });
74
+ });
75
+
76
+ it("does not emit Access-Control-Allow-Origin by default", async () => {
77
+ server = new ForkServer(forkDir, 0);
78
+ await server.start();
79
+ const port = boundPort(server);
80
+
81
+ const res = await fetchFromServer(port, "https://evil.example");
82
+ expect(res.status).toBe(200);
83
+ expect(res.headers.get("access-control-allow-origin")).toBeNull();
84
+ });
85
+
86
+ it("echoes only allow-listed origins when corsAllowOrigins is set", async () => {
87
+ server = new ForkServer(forkDir, 0, "127.0.0.1", {
88
+ corsAllowOrigins: ["https://trusted.example"],
89
+ });
90
+ await server.start();
91
+ const port = boundPort(server);
92
+
93
+ const allowed = await fetchFromServer(port, "https://trusted.example");
94
+ expect(allowed.headers.get("access-control-allow-origin")).toBe(
95
+ "https://trusted.example"
96
+ );
97
+
98
+ const denied = await fetchFromServer(port, "https://evil.example");
99
+ expect(denied.headers.get("access-control-allow-origin")).toBeNull();
100
+ });
101
+ });
package/src/fork/api.ts CHANGED
@@ -4,6 +4,16 @@ import { URL } from 'url';
4
4
  import type { LedgerInfo, AccountData, AccountResource } from '../types/fork.js';
5
5
  import { normalizeAddressShort } from '../utils/address.js';
6
6
 
7
+ export interface MovementApiClientOptions {
8
+ /** Abort the request after this many ms (default: 30_000). */
9
+ timeoutMs?: number;
10
+ /** Reject responses larger than this many bytes (default: 16 MiB). */
11
+ maxBytes?: number;
12
+ }
13
+
14
+ const DEFAULT_TIMEOUT_MS = 30_000;
15
+ const DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
16
+
7
17
  /**
8
18
  * Client for interacting with Movement L1 JSON API.
9
19
  *
@@ -15,8 +25,14 @@ import { normalizeAddressShort } from '../utils/address.js';
15
25
  export class MovementApiClient {
16
26
  private nodeUrl: string;
17
27
  private readonly apiKey?: string;
18
-
19
- constructor(nodeUrl: string, apiKey?: string) {
28
+ private readonly timeoutMs: number;
29
+ private readonly maxBytes: number;
30
+
31
+ constructor(
32
+ nodeUrl: string,
33
+ apiKey?: string,
34
+ options: MovementApiClientOptions = {}
35
+ ) {
20
36
  // Remove trailing slash
21
37
  let normalized = nodeUrl.replace(/\/$/, '');
22
38
 
@@ -28,6 +44,8 @@ export class MovementApiClient {
28
44
 
29
45
  this.nodeUrl = normalized;
30
46
  if (apiKey !== undefined) this.apiKey = apiKey;
47
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
48
+ this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
31
49
  }
32
50
 
33
51
  /**
@@ -52,31 +70,72 @@ export class MovementApiClient {
52
70
  requestOptions.headers = { Authorization: `Bearer ${this.apiKey}` };
53
71
  }
54
72
 
73
+ const timeoutMs = this.timeoutMs;
74
+ const maxBytes = this.maxBytes;
75
+
55
76
  return new Promise((resolve, reject) => {
56
- const req = client.get(fullUrl, requestOptions, (res) => {
57
- let data = '';
77
+ let settled = false;
78
+ const settle = (fn: () => void) => {
79
+ if (settled) return;
80
+ settled = true;
81
+ fn();
82
+ };
58
83
 
59
- res.on('data', (chunk) => {
60
- data += chunk;
84
+ const req = client.get(fullUrl, requestOptions, (res) => {
85
+ const chunks: Buffer[] = [];
86
+ let totalBytes = 0;
87
+
88
+ res.on('data', (chunk: Buffer | string) => {
89
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
90
+ totalBytes += buf.length;
91
+ if (totalBytes > maxBytes) {
92
+ req.destroy();
93
+ settle(() =>
94
+ reject(
95
+ new Error(
96
+ `Response exceeded maxBytes (${maxBytes}); ${totalBytes} bytes received before abort`
97
+ )
98
+ )
99
+ );
100
+ return;
101
+ }
102
+ chunks.push(buf);
61
103
  });
62
104
 
63
105
  res.on('end', () => {
106
+ if (settled) return;
107
+ const data = Buffer.concat(chunks).toString('utf8');
64
108
  if (res.statusCode !== 200) {
65
- reject(new Error(`API request failed with status ${res.statusCode}: ${data}`));
109
+ settle(() =>
110
+ reject(
111
+ new Error(
112
+ `API request failed with status ${res.statusCode}: ${data}`
113
+ )
114
+ )
115
+ );
66
116
  return;
67
117
  }
68
118
 
69
119
  try {
70
120
  const parsed = JSON.parse(data);
71
- resolve(parsed);
121
+ settle(() => resolve(parsed));
72
122
  } catch (err) {
73
- reject(new Error(`Failed to parse JSON response: ${err}`));
123
+ settle(() =>
124
+ reject(new Error(`Failed to parse JSON response: ${err}`))
125
+ );
74
126
  }
75
127
  });
76
128
  });
77
129
 
130
+ req.setTimeout(timeoutMs, () => {
131
+ req.destroy();
132
+ settle(() =>
133
+ reject(new Error(`API request timed out after ${timeoutMs}ms`))
134
+ );
135
+ });
136
+
78
137
  req.on('error', (err) => {
79
- reject(new Error(`API request failed: ${err.message}`));
138
+ settle(() => reject(new Error(`API request failed: ${err.message}`)));
80
139
  });
81
140
 
82
141
  req.end();
@@ -89,7 +89,7 @@ export class ForkManager {
89
89
 
90
90
  this.storage.saveMetadata(this.metadata);
91
91
 
92
- console.log(`✓ Fork initialized at ledger version ${ledgerInfo.ledger_version}`);
92
+ logger.success(`Fork initialized at ledger version ${ledgerInfo.ledger_version}`);
93
93
  }
94
94
 
95
95
  /**
@@ -123,7 +123,7 @@ export class ForkManager {
123
123
  throw new Error('Fork not initialized. Call initialize() or load() first.');
124
124
  }
125
125
 
126
- console.log(` Fetching account ${normalizedAddress} from network...`);
126
+ logger.info(`Fetching account ${normalizedAddress} from network...`, 2);
127
127
  const accountData = await this.apiClient.getAccount(normalizedAddress);
128
128
 
129
129
  accountState = {
@@ -132,7 +132,7 @@ export class ForkManager {
132
132
  };
133
133
 
134
134
  this.storage.saveAccount(normalizedAddress, accountState);
135
- console.log(`Cached account ${normalizedAddress}`);
135
+ logger.success(`Cached account ${normalizedAddress}`, 2);
136
136
  }
137
137
 
138
138
  return accountState;
@@ -148,14 +148,14 @@ export class ForkManager {
148
148
  throw new Error('Fork not initialized. Call initialize() or load() first.');
149
149
  }
150
150
 
151
- console.log(` Fetching resource ${resourceType} for ${normalizedAddress}...`);
151
+ logger.info(`Fetching resource ${resourceType} for ${normalizedAddress}...`, 2);
152
152
 
153
153
  try {
154
154
  const resourceData = await this.apiClient.getAccountResource(normalizedAddress, resourceType);
155
155
  resource = resourceData.data;
156
156
 
157
157
  this.storage.saveResource(normalizedAddress, resourceType, resource);
158
- console.log(`Cached resource ${resourceType}`);
158
+ logger.success(`Cached resource ${resourceType}`, 2);
159
159
  } catch (error) {
160
160
  const msg = error instanceof Error ? error.message : String(error);
161
161
  if (msg.includes('404')) {
@@ -178,7 +178,7 @@ export class ForkManager {
178
178
  throw new Error('Fork not initialized. Call initialize() or load() first.');
179
179
  }
180
180
 
181
- console.log(` Fetching all resources for ${normalizedAddress}...`);
181
+ logger.info(`Fetching all resources for ${normalizedAddress}...`, 2);
182
182
  const resourcesList = await this.apiClient.getAccountResources(normalizedAddress);
183
183
 
184
184
  resources = {};
@@ -187,7 +187,7 @@ export class ForkManager {
187
187
  }
188
188
 
189
189
  this.storage.saveAllResources(normalizedAddress, resources);
190
- console.log(`Cached ${Object.keys(resources).length} resources`);
190
+ logger.success(`Cached ${Object.keys(resources).length} resources`, 2);
191
191
  }
192
192
 
193
193
  return resources;
@@ -196,7 +196,7 @@ export class ForkManager {
196
196
  async setResource(address: string, resourceType: string, data: unknown): Promise<void> {
197
197
  const normalizedAddress = normalizeAddress(address);
198
198
  this.storage.saveResource(normalizedAddress, resourceType, data);
199
- console.log(`Updated resource ${resourceType} for ${normalizedAddress}`);
199
+ logger.success(`Updated resource ${resourceType} for ${normalizedAddress}`, 2);
200
200
  }
201
201
 
202
202
  /** Adds to the existing balance rather than replacing it. */
@@ -258,7 +258,7 @@ export class ForkManager {
258
258
  this.storage.saveAccount(normalizedAddress, account);
259
259
  }
260
260
 
261
- console.log(`Funded ${normalizedAddress} with ${amount} coins`);
261
+ logger.success(`Funded ${normalizedAddress} with ${amount} coins`, 2);
262
262
  }
263
263
 
264
264
  listAccounts(): string[] {
@@ -335,7 +335,7 @@ export class ForkManager {
335
335
  };
336
336
 
337
337
  this.storage.saveAccount(normalizedAddress, newAccount);
338
- console.log(`Created new account ${normalizedAddress}`);
338
+ logger.success(`Created new account ${normalizedAddress}`, 2);
339
339
 
340
340
  return newAccount;
341
341
  }