@relyon/kit 0.0.0-stage → 1.0.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.
Files changed (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
@@ -0,0 +1,820 @@
1
+ import { SANDBOX_OBJECT, TEST_KEY_OBJECT } from "./wire-names.js";
2
+ import { constants } from "node:fs";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { lstat, mkdir, open, realpath, readdir, link, rename, rmdir, unlink } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { usableApiKey, usableTestKey } from "./api-key.js";
8
+ /** The key file the runtime reads. */
9
+ export const SANDBOX_FILE = "sandbox.json";
10
+ /** A Test key the merchant entered (init --key-from-stdin). */
11
+ export const ENTERED_KEY_FILE = "test-key.json";
12
+ /** The private ownership (claim) link, kept apart from the key file. */
13
+ export const CLAIM_LINK_FILE = "ownership-link.txt";
14
+ function validClaimUrl(value) {
15
+ if (typeof value !== "string")
16
+ return false;
17
+ try {
18
+ const url = new URL(value);
19
+ return url.origin === "https://core.getrelyon.com" && url.pathname === "/claim-sandbox"
20
+ && !url.search && !url.username && !url.password && /^#token=[A-Za-z0-9_-]{16,300}$/.test(url.hash);
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ function validKeyFields(v) {
27
+ return v.object === SANDBOX_OBJECT && v.livemode === false && typeof v.id === "string" && Boolean(v.id)
28
+ && typeof v.restrictedKey === "string" && /^rly_test_[A-Za-z0-9_-]{16,200}$/.test(v.restrictedKey)
29
+ && typeof v.publishableKey === "string" && /^pk_test_[A-Za-z0-9_-]{16,200}$/.test(v.publishableKey)
30
+ && typeof v.expiresAt === "string" && Number.isFinite(Date.parse(v.expiresAt));
31
+ }
32
+ /** A saved key file: the key fields, and (in files saved by kit 0.1.6 or earlier) the claim link. */
33
+ function validSavedSandbox(value) {
34
+ if (!value || typeof value !== "object")
35
+ return false;
36
+ const v = value;
37
+ return validKeyFields(v) && (v.claimUrl === undefined || validClaimUrl(v.claimUrl));
38
+ }
39
+ /** A newly provisioned response must be complete and still within its unclaimed lifetime. */
40
+ export function validSandbox(value) {
41
+ if (!value || typeof value !== "object")
42
+ return false;
43
+ const v = value;
44
+ return validKeyFields(v) && validClaimUrl(v.claimUrl) && Date.parse(v.expiresAt) > Date.now();
45
+ }
46
+ /** Fail closed on links, shared permissions, tracked storage, or app descendants. */
47
+ export async function privateDirectory(dir, project) {
48
+ if (process.platform === "win32" || !path.isAbsolute(dir))
49
+ throw Error("unsafe private directory");
50
+ const root = await realpath(project);
51
+ const resolved = path.resolve(dir);
52
+ if (await realpath(resolved) !== resolved || resolved === root || resolved.startsWith(`${root}${path.sep}`))
53
+ throw Error("unsafe private directory");
54
+ let current = path.parse(resolved).root;
55
+ for (const part of resolved.slice(current.length).split(path.sep).filter(Boolean)) {
56
+ current = path.join(current, part);
57
+ const stat = await lstat(current);
58
+ if (!stat.isDirectory() || stat.isSymbolicLink())
59
+ throw Error("unsafe private directory");
60
+ try {
61
+ await lstat(path.join(current, ".git"));
62
+ throw Error("private storage must be outside git trees");
63
+ }
64
+ catch (error) {
65
+ if (error.code !== "ENOENT")
66
+ throw error;
67
+ }
68
+ // Ancestors may be shared only with the sticky bit (e.g. /tmp).
69
+ if (current !== resolved && (stat.mode & 0o022) && !(stat.mode & 0o1000))
70
+ throw Error("unsafe ancestor");
71
+ }
72
+ const stat = await lstat(resolved);
73
+ if ((stat.mode & 0o777) !== 0o700 || stat.uid !== process.getuid?.())
74
+ throw Error("unsafe private directory");
75
+ // Storage inside ANY git working tree is refused, including ignored paths.
76
+ const git = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: resolved, encoding: "utf8", env: { PATH: process.env.PATH } });
77
+ if (git.error || git.status === 0 || git.status !== 128)
78
+ throw Error("unverified private directory");
79
+ return resolved;
80
+ }
81
+ /** A short, stable folder name for a project: its name and a hash of its real path. */
82
+ export function projectId(realProject) {
83
+ const name = path.basename(realProject).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "project";
84
+ return `${name}-${createHash("sha256").update(realProject).digest("hex").slice(0, 16)}`;
85
+ }
86
+ /**
87
+ * The default private folder candidates for a project when RELYON_PRIVATE_DIR
88
+ * is unset, most preferred first: `$XDG_CONFIG_HOME/relyon/<project-id>`, then
89
+ * `$HOME/.config/relyon/<project-id>`. Distinct absolute paths only; empty when
90
+ * the environment names neither.
91
+ */
92
+ export async function defaultPrivateDirs(project, env) {
93
+ const id = projectId(await realpath(project));
94
+ const out = [];
95
+ const xdg = env.XDG_CONFIG_HOME?.trim();
96
+ if (xdg && path.isAbsolute(xdg))
97
+ out.push(path.join(xdg, "relyon", id));
98
+ const home = env.HOME?.trim();
99
+ if (home && path.isAbsolute(home))
100
+ out.push(path.join(home, ".config", "relyon", id));
101
+ return [...new Set(out)];
102
+ }
103
+ /** The first default candidate (unchanged when only one exists); for callers that report a location. */
104
+ export async function defaultPrivateDir(project, env) {
105
+ return (await defaultPrivateDirs(project, env))[0];
106
+ }
107
+ /**
108
+ * Why a candidate folder would be unsafe, checked without creating anything:
109
+ * the nearest existing ancestor is resolved, the would-be real path rebuilt
110
+ * from it, and the candidate refused when it would sit inside the project or
111
+ * inside a git tree. A dangling link on the way reads as existing but has no
112
+ * real path, so it is refused the same as an uncheckable one.
113
+ * Undefined when the candidate passes, on every host.
114
+ */
115
+ async function screenPrivateDir(dir, realProject) {
116
+ let ancestor = dir;
117
+ const missing = [];
118
+ for (;;) {
119
+ try {
120
+ await lstat(ancestor);
121
+ break;
122
+ }
123
+ catch (error) {
124
+ const code = error.code;
125
+ if (code !== "ENOENT" && code !== "ENOTDIR")
126
+ return "its location can't be checked";
127
+ missing.unshift(path.basename(ancestor));
128
+ const parent = path.dirname(ancestor);
129
+ if (parent === ancestor)
130
+ return "its location can't be checked";
131
+ ancestor = parent;
132
+ }
133
+ }
134
+ let realAncestor;
135
+ try {
136
+ realAncestor = await realpath(ancestor);
137
+ }
138
+ catch {
139
+ return "its location can't be checked";
140
+ }
141
+ if (!(await lstat(realAncestor)).isDirectory())
142
+ return "its path is not a directory";
143
+ const real = missing.length ? path.join(realAncestor, ...missing) : realAncestor;
144
+ if (real === realProject || real.startsWith(`${realProject}${path.sep}`))
145
+ return "it would be inside the project";
146
+ if (await insideGitTree(realAncestor))
147
+ return "it would be inside a git tree";
148
+ return undefined;
149
+ }
150
+ /**
151
+ * The verified private folder: RELYON_PRIVATE_DIR (must already exist) or the
152
+ * first usable default candidate (created 0700 when `create`). A candidate
153
+ * that would sit inside the project or a git tree is skipped before anything
154
+ * is created, so a refused candidate leaves no empty folder behind; a
155
+ * just-created folder that still fails verification is removed best-effort.
156
+ * The first refusal is carried out so init can name it.
157
+ */
158
+ async function resolvePrivateDir(project, env, create) {
159
+ const realProject = await realpath(project);
160
+ if (env.RELYON_PRIVATE_DIR) {
161
+ try {
162
+ const dir = await privateDirectory(env.RELYON_PRIVATE_DIR, project);
163
+ return { dir };
164
+ }
165
+ catch (error) {
166
+ return { refused: { path: env.RELYON_PRIVATE_DIR, reason: error?.message ?? "unsafe private directory" } };
167
+ }
168
+ }
169
+ let refused;
170
+ for (const candidate of await defaultPrivateDirs(project, env)) {
171
+ const problem = await screenPrivateDir(candidate, realProject);
172
+ if (problem) {
173
+ refused ??= { path: candidate, reason: problem };
174
+ continue;
175
+ }
176
+ if (!create) {
177
+ let real;
178
+ try {
179
+ real = path.join(await realpath(path.dirname(candidate)), path.basename(candidate));
180
+ }
181
+ catch {
182
+ continue;
183
+ }
184
+ try {
185
+ await lstat(real);
186
+ }
187
+ catch {
188
+ continue;
189
+ }
190
+ try {
191
+ return { dir: await privateDirectory(real, project) };
192
+ }
193
+ catch (error) {
194
+ refused ??= { path: candidate, reason: error?.message ?? "unsafe private directory" };
195
+ continue;
196
+ }
197
+ }
198
+ let real;
199
+ let created = false;
200
+ try {
201
+ const parent = path.dirname(candidate);
202
+ await mkdir(parent, { recursive: true, mode: 0o700 });
203
+ // Build the final path on the real parent, so a linked home folder still verifies.
204
+ real = path.join(await realpath(parent), path.basename(candidate));
205
+ try {
206
+ await mkdir(real, { mode: 0o700 });
207
+ created = true;
208
+ }
209
+ catch (error) {
210
+ if (error.code !== "EEXIST")
211
+ throw error;
212
+ }
213
+ return { dir: await privateDirectory(real, project) };
214
+ }
215
+ catch (error) {
216
+ // A folder this run created but can't use is removed again, best-effort.
217
+ // rmdir, never a recursive delete: it is empty (verification failed
218
+ // before anything was written), and a non-empty one is left alone.
219
+ if (created && real)
220
+ await rmdir(real).catch(() => { });
221
+ refused ??= { path: candidate, reason: error?.message ?? "unsafe private directory" };
222
+ }
223
+ }
224
+ return refused ? { refused } : {};
225
+ }
226
+ /** Reads a small owner-only regular file, refusing links, hard links and shared modes. */
227
+ async function readOwnerOnly(file, maxBytes) {
228
+ let stat;
229
+ try {
230
+ stat = await lstat(file);
231
+ }
232
+ catch (e) {
233
+ if (e.code === "ENOENT")
234
+ return undefined;
235
+ throw e;
236
+ }
237
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid?.() || stat.size > maxBytes)
238
+ throw Error("unsafe private file");
239
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
240
+ try {
241
+ const opened = await handle.stat();
242
+ if (opened.ino !== stat.ino || opened.dev !== stat.dev)
243
+ throw Error("private file changed");
244
+ return await handle.readFile("utf8");
245
+ }
246
+ finally {
247
+ await handle.close();
248
+ }
249
+ }
250
+ async function readPrivate(file) {
251
+ const text = await readOwnerOnly(file, 16384);
252
+ if (text === undefined)
253
+ return undefined;
254
+ const value = JSON.parse(text);
255
+ // Claiming retains the key beyond the original unclaimed expiry. Only the
256
+ // API can decide whether a saved key is still authorized; loading it is not
257
+ // connection verification. Never discard it or provision a replacement
258
+ // merely because the original anonymous response's expiry has passed.
259
+ if (!validSavedSandbox(value))
260
+ throw Error("invalid private configuration");
261
+ return value;
262
+ }
263
+ async function readEnteredKey(file) {
264
+ const text = await readOwnerOnly(file, 4096);
265
+ if (text === undefined)
266
+ return undefined;
267
+ const value = JSON.parse(text);
268
+ const key = value && typeof value === "object" && value.object === TEST_KEY_OBJECT
269
+ ? usableTestKey(value.restrictedKey) : undefined;
270
+ if (!key)
271
+ throw Error("invalid private configuration");
272
+ return key;
273
+ }
274
+ /** Writes a new owner-only file atomically (temp file, then rename). */
275
+ async function writePrivateFile(dir, name, content, replace) {
276
+ const temp = path.join(dir, `.${name}.${randomBytes(6).toString("hex")}.tmp`);
277
+ const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
278
+ try {
279
+ try {
280
+ await handle.writeFile(content);
281
+ await handle.sync();
282
+ }
283
+ finally {
284
+ await handle.close();
285
+ }
286
+ if (replace)
287
+ await rename(temp, path.join(dir, name));
288
+ else
289
+ await link(temp, path.join(dir, name)); // Atomic, never overwrites.
290
+ }
291
+ finally {
292
+ await unlink(temp).catch(() => { });
293
+ }
294
+ }
295
+ /** The private key: the merchant-entered one wins over the provisioned sandbox key. */
296
+ async function privateKey(dir) {
297
+ return await readEnteredKey(path.join(dir, ENTERED_KEY_FILE)) ?? (await readPrivate(path.join(dir, SANDBOX_FILE)))?.restrictedKey;
298
+ }
299
+ // ---- .env handling -------------------------------------------------------
300
+ /** A dotenv assignment line for one variable name (`NAME=value`, optional `export`). */
301
+ const envLineFor = (name) => new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*(.*)$`);
302
+ const ENV_LINE = envLineFor("RELYON_API_KEY");
303
+ function envValue(raw) {
304
+ const value = raw.trim();
305
+ const quoted = /^(["'])(.*)\1(?:\s+#.*)?$/.exec(value);
306
+ if (quoted)
307
+ return quoted[2];
308
+ return value.replace(/\s+#.*$/, "").trim();
309
+ }
310
+ /** Every usable RELYON_API_KEY assignment in a dotenv text, in order (placeholders count as none). */
311
+ export function dotenvApiKeys(text) {
312
+ const keys = [];
313
+ for (const line of text.split(/\r?\n/)) {
314
+ const match = ENV_LINE.exec(line);
315
+ if (match) {
316
+ const key = usableApiKey(envValue(match[1]));
317
+ if (key)
318
+ keys.push(key);
319
+ }
320
+ }
321
+ return keys;
322
+ }
323
+ /** The usable RELYON_API_KEY in a dotenv text, if any (placeholders count as none). */
324
+ export function dotenvApiKey(text) {
325
+ let found;
326
+ for (const line of text.split(/\r?\n/)) {
327
+ const match = ENV_LINE.exec(line);
328
+ if (match)
329
+ found = usableApiKey(envValue(match[1]));
330
+ }
331
+ return found;
332
+ }
333
+ /** Reads a project dotenv file when it is a small regular file (never a link). */
334
+ async function readDotenv(file) {
335
+ let stat;
336
+ try {
337
+ stat = await lstat(file);
338
+ }
339
+ catch {
340
+ return undefined;
341
+ }
342
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536)
343
+ return undefined;
344
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
345
+ try {
346
+ return await handle.readFile("utf8");
347
+ }
348
+ finally {
349
+ await handle.close();
350
+ }
351
+ }
352
+ /** The project's dotenv files that can hold a secret (.env, .env.local, …), sorted; never examples or templates. */
353
+ async function dotenvFileNames(project) {
354
+ try {
355
+ return (await readdir(project)).filter((name) => name === ".env" || (name.startsWith(".env.") && !/\.(?:example|sample|template|dist)$/.test(name))).sort();
356
+ }
357
+ catch {
358
+ return [];
359
+ }
360
+ }
361
+ /** A usable key already in one of the project's dotenv files, with the file holding it. */
362
+ async function dotenvKeyInProject(project) {
363
+ for (const name of await dotenvFileNames(project)) {
364
+ const text = await readDotenv(path.join(project, name)).catch(() => undefined);
365
+ const key = text === undefined ? undefined : dotenvApiKey(text);
366
+ if (key)
367
+ return { name, key };
368
+ }
369
+ return undefined;
370
+ }
371
+ function git(project, args) {
372
+ const run = spawnSync("git", args, { cwd: project, encoding: "utf8", env: { PATH: process.env.PATH }, timeout: 10_000 });
373
+ return { status: run.status, ...(run.error ? { error: run.error } : {}) };
374
+ }
375
+ /** True when .gitignore patterns already ignore `.env` at the project root. */
376
+ function ignoresEnv(text) {
377
+ let ignored = false;
378
+ for (const raw of text.split(/\r?\n/)) {
379
+ const line = raw.trim();
380
+ if (!line || line.startsWith("#"))
381
+ continue;
382
+ // Any later negation might re-include .env (for example "!*"), so only an
383
+ // ignore rule after the last negation counts. Patterns ending in "/" match
384
+ // directories only, so they don't count.
385
+ if (line.startsWith("!")) {
386
+ ignored = false;
387
+ continue;
388
+ }
389
+ const pattern = line.replace(/^\//, "");
390
+ if (pattern === ".env" || pattern === ".env*" || pattern === "*.env" || pattern === ".env**" || pattern === "**/.env")
391
+ ignored = true;
392
+ }
393
+ return ignored;
394
+ }
395
+ /** True when `dir` or one of its ancestors holds a `.git` entry. */
396
+ async function insideGitTree(dir) {
397
+ for (let current = dir;; current = path.dirname(current)) {
398
+ try {
399
+ await lstat(path.join(current, ".git"));
400
+ return true;
401
+ }
402
+ catch { /* keep walking */ }
403
+ if (path.dirname(current) === current)
404
+ return false;
405
+ }
406
+ }
407
+ /**
408
+ * When the project has the given ignore file, makes sure it lists the pattern
409
+ * that keeps `.env` out. Returns why it couldn't, or undefined. Init never
410
+ * creates an ignore file of its own.
411
+ */
412
+ async function ensureIgnoreFileListsEnv(root, name, pattern, problem) {
413
+ const file = path.join(root, name);
414
+ let text;
415
+ try {
416
+ const stat = await lstat(file);
417
+ if (!stat.isFile() || stat.isSymbolicLink())
418
+ return `${name} is a link or not a regular file, so init can't make sure ${problem} leave .env out`;
419
+ text = await readDotenv(file);
420
+ if (text === undefined)
421
+ return `${name} is too large for init to edit`;
422
+ }
423
+ catch (error) {
424
+ if (error.code === "ENOENT")
425
+ return undefined;
426
+ return `${name} can't be read`;
427
+ }
428
+ if (ignoresEnv(text))
429
+ return undefined;
430
+ const next = `${text}${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}# Local secrets (Relyon store kit)\n${pattern}\n`;
431
+ try {
432
+ const temp = path.join(root, `${name}.relyon-${randomBytes(6).toString("hex")}`);
433
+ const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o644);
434
+ try {
435
+ await handle.writeFile(next);
436
+ }
437
+ finally {
438
+ await handle.close();
439
+ }
440
+ try {
441
+ await rename(temp, file);
442
+ }
443
+ finally {
444
+ await unlink(temp).catch(() => { });
445
+ }
446
+ }
447
+ catch {
448
+ return `${name} couldn't be updated to list ${pattern}`;
449
+ }
450
+ return undefined;
451
+ }
452
+ /**
453
+ * When the project has a `.dockerignore`, makes sure it lists `.env` (so an
454
+ * image build never copies the key). Returns why it couldn't, or undefined.
455
+ */
456
+ const ensureDockerignoreListsEnv = (root) => ensureIgnoreFileListsEnv(root, ".dockerignore", ".env", "image builds");
457
+ /** The .env variables the kit writes, with the comment each assignment carries. */
458
+ export const ENV_FILE_VALUES = {
459
+ RELYON_API_KEY: "# Relyon Test key, set by npx @relyon/store-kit init (never commit this file)",
460
+ RELYON_WEBHOOK_SECRET: "# Relyon webhook signing secret, set by npx @relyon/store-kit webhook (never commit this file)",
461
+ RELYON_WEBHOOK_ENDPOINT_ID: "# Relyon webhook endpoint the signing secret belongs to, set by npx @relyon/store-kit webhook (never commit this file)",
462
+ };
463
+ /**
464
+ * Reads one kit-written variable from the project's `.env`: undefined when the
465
+ * file is absent, unreadable or carries no usable assignment. Never throws.
466
+ */
467
+ export async function readEnvValue(project, name) {
468
+ let root;
469
+ try {
470
+ root = await realpath(project);
471
+ }
472
+ catch {
473
+ return undefined;
474
+ }
475
+ let text;
476
+ try {
477
+ text = await readDotenv(path.join(root, ".env"));
478
+ }
479
+ catch {
480
+ return undefined;
481
+ }
482
+ if (text === undefined)
483
+ return undefined;
484
+ const NAME_LINE = envLineFor(name);
485
+ let found;
486
+ for (const line of text.split(/\r?\n/)) {
487
+ const match = NAME_LINE.exec(line);
488
+ if (match)
489
+ found = envValue(match[1]);
490
+ }
491
+ const value = found?.trim();
492
+ return value ? value : undefined;
493
+ }
494
+ /**
495
+ * Sets one variable (RELYON_API_KEY, RELYON_WEBHOOK_SECRET or
496
+ * RELYON_WEBHOOK_ENDPOINT_ID) in the project's
497
+ * `.env`: makes sure `.gitignore` (and an existing `.dockerignore`) lists
498
+ * `.env` first, refuses when `.env` is tracked by git (with the reason),
499
+ * keeps every other line, and leaves the file 0600. Never prints or returns
500
+ * the value. With preflight=true, checks storage without changing dotenv or
501
+ * ignore files; callers must still repeat the checks when actually writing.
502
+ */
503
+ export async function writeEnvValue(project, name, value, env, preflight = false) {
504
+ // An environment key is authoritative on every host; never copy a key to disk.
505
+ if (name === "RELYON_API_KEY" && usableApiKey((env ?? process.env).RELYON_API_KEY))
506
+ return { status: "unchanged" };
507
+ // A value with a line break or NUL can't be one .env assignment; storing it
508
+ // would corrupt the file or smuggle extra variables in. Refuse it outright.
509
+ if (/[\r\n\0]/.test(value))
510
+ return { status: "refused", reason: `the value for ${name} contains a line break or NUL character, so it can't be written to .env` };
511
+ const root = await realpath(project);
512
+ if (((await lstat(root)).mode & 0o300) !== 0o300)
513
+ return { status: "refused", reason: "the project directory isn't writable" };
514
+ const envFile = path.join(root, ".env");
515
+ // Tracked .env: never write a secret into a committed file.
516
+ // Fail closed: write only when git confirms .env is untracked, or when no
517
+ // git tree holds the project at all.
518
+ const tracked = git(root, ["ls-files", "--error-unmatch", "--", ".env"]);
519
+ if (!tracked.error && tracked.status === 0) {
520
+ return { status: "refused", reason: ".env is tracked by git, so init won't put a key in it. Stop tracking it (git rm --cached .env), then rerun init" };
521
+ }
522
+ const inRepo = !tracked.error && tracked.status === 1;
523
+ if (!inRepo && await insideGitTree(root)) {
524
+ return { status: "refused", reason: "git couldn't confirm that .env is untracked, so init won't put a key in it" };
525
+ }
526
+ let existing;
527
+ try {
528
+ const stat = await lstat(envFile);
529
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
530
+ return { status: "refused", reason: ".env is a link or not a regular file, so init won't change it" };
531
+ if (stat.uid !== process.getuid?.())
532
+ return { status: "refused", reason: ".env belongs to another user, so init won't change it" };
533
+ if (!(stat.mode & 0o200))
534
+ return { status: "refused", reason: ".env isn't writable" };
535
+ existing = await readDotenv(envFile);
536
+ if (existing === undefined)
537
+ return { status: "refused", reason: ".env is too large for init to edit" };
538
+ }
539
+ catch (error) {
540
+ if (error.code !== "ENOENT")
541
+ return { status: "refused", reason: ".env can't be read" };
542
+ }
543
+ // .gitignore must list .env before the key is written.
544
+ const ignoreFile = path.join(root, ".gitignore");
545
+ let ignore = "";
546
+ try {
547
+ const stat = await lstat(ignoreFile);
548
+ if (!stat.isFile() || stat.isSymbolicLink())
549
+ return { status: "refused", reason: ".gitignore is a link or not a regular file, so init can't make sure .env is ignored" };
550
+ ignore = (await readDotenv(ignoreFile)) ?? "";
551
+ }
552
+ catch (error) {
553
+ if (error.code !== "ENOENT")
554
+ return { status: "refused", reason: ".gitignore can't be read" };
555
+ }
556
+ if (preflight) {
557
+ // Probe the directory without changing dotenv/ignore contents. The same
558
+ // refusal checks run again at write time after the remote operation.
559
+ for (const name of [".gitignore", ".dockerignore"]) {
560
+ try {
561
+ const stat = await lstat(path.join(root, name));
562
+ if (!stat.isFile() || stat.isSymbolicLink() || !(stat.mode & 0o200)) {
563
+ return { status: "refused", reason: `${name} is linked or unwritable` };
564
+ }
565
+ }
566
+ catch (error) {
567
+ if (error.code !== "ENOENT")
568
+ return { status: "refused", reason: `${name} can't be checked` };
569
+ }
570
+ }
571
+ const probe = path.join(root, `.relyon-write-check-${randomBytes(6).toString("hex")}`);
572
+ try {
573
+ const handle = await open(probe, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
574
+ await handle.close();
575
+ }
576
+ catch {
577
+ return { status: "refused", reason: "the project directory isn't writable" };
578
+ }
579
+ finally {
580
+ await unlink(probe).catch(() => { });
581
+ }
582
+ return { status: "unchanged" };
583
+ }
584
+ // In a repository, git itself has the last word on whether .env is ignored.
585
+ const gitIgnores = () => git(root, ["check-ignore", "-q", "--", ".env"]);
586
+ if (!ignoresEnv(ignore) || (inRepo && gitIgnores().status !== 0)) {
587
+ const next = `${ignore}${ignore && !ignore.endsWith("\n") ? "\n" : ""}${ignore ? "\n" : ""}# Local secrets (Relyon store kit)\n.env\n`;
588
+ const temp = path.join(root, `.gitignore.relyon-${randomBytes(6).toString("hex")}`);
589
+ const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o644);
590
+ try {
591
+ await handle.writeFile(next);
592
+ }
593
+ finally {
594
+ await handle.close();
595
+ }
596
+ try {
597
+ await rename(temp, ignoreFile);
598
+ }
599
+ finally {
600
+ await unlink(temp).catch(() => { });
601
+ }
602
+ }
603
+ if (inRepo) {
604
+ const check = gitIgnores();
605
+ if (check.error || check.status !== 0)
606
+ return { status: "refused", reason: "git still doesn't ignore .env after init added it to .gitignore, so init won't put a key in it" };
607
+ }
608
+ // A project with a .dockerignore must keep .env out of its image build context too.
609
+ const dockerProblem = await ensureDockerignoreListsEnv(root);
610
+ if (dockerProblem)
611
+ return { status: "refused", reason: dockerProblem };
612
+ const lines = existing === undefined ? [] : existing.split(/\r?\n/);
613
+ if (lines.length && lines[lines.length - 1] === "")
614
+ lines.pop();
615
+ const NAME_LINE = envLineFor(name);
616
+ const index = lines.findIndex((line) => NAME_LINE.test(line));
617
+ if (index !== -1 && envValue(NAME_LINE.exec(lines[index])[1]) === value && lines.filter((line) => NAME_LINE.test(line)).length === 1) {
618
+ // Already set; still make sure only the owner can read it.
619
+ const handle = await open(envFile, constants.O_RDONLY | constants.O_NOFOLLOW);
620
+ try {
621
+ await handle.chmod(0o600);
622
+ }
623
+ finally {
624
+ await handle.close();
625
+ }
626
+ return { status: "unchanged" };
627
+ }
628
+ const assignment = `${name}=${value}`;
629
+ let out;
630
+ if (index === -1)
631
+ out = [...lines, ...(lines.length && lines[lines.length - 1].trim() ? [""] : []), ENV_FILE_VALUES[name], assignment];
632
+ else
633
+ out = lines.flatMap((line, at) => !NAME_LINE.test(line) ? [line] : at === index ? [assignment] : []);
634
+ const temp = path.join(root, `.env.relyon-${randomBytes(6).toString("hex")}`);
635
+ const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
636
+ try {
637
+ await handle.writeFile(`${out.join("\n")}\n`);
638
+ await handle.sync();
639
+ }
640
+ finally {
641
+ await handle.close();
642
+ }
643
+ try {
644
+ await rename(temp, envFile);
645
+ }
646
+ finally {
647
+ await unlink(temp).catch(() => { });
648
+ }
649
+ return { status: "written" };
650
+ }
651
+ /** Sets RELYON_API_KEY in the project's `.env`. Never prints or returns the key. */
652
+ export async function writeEnvKey(project, key, env) {
653
+ if (usableApiKey((env ?? process.env).RELYON_API_KEY))
654
+ return { status: "unchanged" };
655
+ return writeEnvValue(project, "RELYON_API_KEY", key, env);
656
+ }
657
+ // ---- runtime loader --------------------------------------------------------
658
+ /**
659
+ * Import only on the Node server; never import in client modules. Order: a
660
+ * usable RELYON_API_KEY in the environment; the private folder
661
+ * (RELYON_PRIVATE_DIR, else the default one); RELYON_API_KEY in the project's
662
+ * dotenv files (`.env`, `.env.local`, `.env.production`, … in sorted order).
663
+ * A placeholder or malformed value counts as no key. Returns `{}`
664
+ * (the kit waits for a sandbox key) rather than a fabricated credential.
665
+ * With RELYON_LIVE=true only RELYON_API_KEY in the environment is used: no
666
+ * saved Test key is read from the private folder or `.env`.
667
+ * webhookSecret resolves independently: environment first, then the project's
668
+ * dotenv files in the same sorted order. Private storage holds API keys, not
669
+ * webhook secrets; the webhook command saves its signing secret in `.env`.
670
+ */
671
+ export async function loadTestConfig(options) {
672
+ const env = options.env ?? process.env;
673
+ let apiKey = usableApiKey(env.RELYON_API_KEY);
674
+ let webhookSecret = env.RELYON_WEBHOOK_SECRET?.trim() || undefined;
675
+ if (liveRequested(env))
676
+ return { ...(apiKey ? { apiKey } : {}), ...(webhookSecret ? { webhookSecret } : {}) };
677
+ if (!apiKey)
678
+ try {
679
+ const { dir } = await resolvePrivateDir(options.project, env, false);
680
+ apiKey = dir ? await privateKey(dir) : undefined;
681
+ }
682
+ catch { /* unsafe or unreadable private storage: fall through, never guess */ }
683
+ apiKey ??= usableTestKey((await dotenvKeyInProject(options.project))?.key);
684
+ // Resolve independently: finding a key must not suppress the saved secret.
685
+ for (const name of await dotenvFileNames(options.project)) {
686
+ if (webhookSecret)
687
+ break;
688
+ const text = await readDotenv(path.join(options.project, name)).catch(() => undefined);
689
+ for (const line of (text ?? "").split(/\r?\n/)) {
690
+ const match = envLineFor("RELYON_WEBHOOK_SECRET").exec(line);
691
+ if (match)
692
+ webhookSecret = envValue(match[1]).trim() || undefined;
693
+ }
694
+ }
695
+ return { ...(apiKey ? { apiKey } : {}), ...(webhookSecret ? { webhookSecret } : {}) };
696
+ }
697
+ const liveRequested = (env) => env.RELYON_LIVE?.trim().toLowerCase() === "true";
698
+ const truthy = (value) => {
699
+ const v = value?.trim().toLowerCase();
700
+ return v !== undefined && v !== "" && v !== "0" && v !== "false" && v !== "no" && v !== "off";
701
+ };
702
+ /**
703
+ * The legacy environment variable that once opted an unattended run into
704
+ * automatic Test setup. Init never creates sandboxes anymore (creation is
705
+ * authenticated and lives on the hosted key page), so this is accepted and
706
+ * changes nothing; the name stays exported for scripts that still set it.
707
+ */
708
+ export const AUTO_TEST_KEY_ENV = "RELYON_AUTO_TEST_KEY";
709
+ /** Moves a claim link saved by kit 0.1.6 or earlier out of the key file. */
710
+ async function separateLegacyClaim(dir, saved) {
711
+ if (saved.claimUrl === undefined)
712
+ return;
713
+ try {
714
+ await writePrivateFile(dir, CLAIM_LINK_FILE, claimFileText(saved.claimUrl), false);
715
+ }
716
+ catch (error) {
717
+ if (error.code !== "EEXIST")
718
+ throw error;
719
+ }
720
+ const { claimUrl: _claim, ...keyOnly } = saved;
721
+ await writePrivateFile(dir, SANDBOX_FILE, JSON.stringify(keyOnly), true);
722
+ }
723
+ function claimFileText(claimUrl) {
724
+ return "Private ownership link for this store's Relyon Test sandbox. Only the merchant opens it; never share or paste it.\n"
725
+ + `${claimUrl}\n`;
726
+ }
727
+ async function claimPath(dir) {
728
+ try {
729
+ return (await lstat(path.join(dir, CLAIM_LINK_FILE))).isFile() ? path.join(dir, CLAIM_LINK_FILE) : undefined;
730
+ }
731
+ catch {
732
+ return undefined;
733
+ }
734
+ }
735
+ /**
736
+ * Reuses the project's existing Test key (environment, .env, or the private
737
+ * folder) and reports "waiting" when there is none. It never creates a
738
+ * sandbox: creation is authenticated and attaches to the creator's own
739
+ * workspace, so a first-time developer gets the key from the hosted key page
740
+ * and `init --key-from-stdin` (init's GET_KEY_LINES). Never provisions or
741
+ * uses a Live key: RELYON_LIVE=true turns automatic setup off. Never prints
742
+ * anything. The `fetch`/`timeoutMs`/`interactive`/`optIn`/`scratch` options
743
+ * are accepted for call-site compatibility and no longer used.
744
+ */
745
+ export async function autoTestSetup(options) {
746
+ const env = options.env ?? process.env;
747
+ if (usableApiKey(env.RELYON_API_KEY))
748
+ return { status: "existing", fromEnv: true };
749
+ if (liveRequested(env))
750
+ return { status: "waiting", reason: "live" };
751
+ try {
752
+ // Preserve existing local-dev configuration identically on every host.
753
+ const dotenv = await dotenvKeyInProject(options.project);
754
+ if (dotenv) {
755
+ return { status: "existing", fromDotenv: true, dotenvFile: dotenv.name };
756
+ }
757
+ // Only a private folder that already exists is read; none is created here
758
+ // (a folder is made when an entered key is saved, not for a network call).
759
+ let dir;
760
+ try {
761
+ dir = (await resolvePrivateDir(options.project, env, false)).dir;
762
+ }
763
+ catch {
764
+ dir = undefined;
765
+ }
766
+ if (!dir)
767
+ return { status: "waiting", reason: "hosted-signup" };
768
+ const entered = await readEnteredKey(path.join(dir, ENTERED_KEY_FILE));
769
+ const saved = await readPrivate(path.join(dir, SANDBOX_FILE));
770
+ if (entered || saved) {
771
+ if (saved)
772
+ await separateLegacyClaim(dir, saved);
773
+ const envFile = await writeEnvKey(options.project, (entered ?? saved.restrictedKey), env);
774
+ const claimFile = await claimPath(dir);
775
+ const dotenvFile = envFile.status !== "refused" ? ".env" : undefined;
776
+ return { status: "existing", envFile, ...(dotenvFile ? { dotenvFile } : {}), ...(claimFile ? { claimFile } : {}) };
777
+ }
778
+ return { status: "waiting", reason: "hosted-signup" };
779
+ }
780
+ catch {
781
+ return { status: "waiting", reason: "hosted-signup" };
782
+ }
783
+ }
784
+ /** Why a key entered for init can't be saved, without repeating it; null when it is a Test key. */
785
+ export function enteredKeyProblem(value) {
786
+ const key = value.trim();
787
+ if (!key)
788
+ return "No key was entered. Nothing was saved.";
789
+ if (usableTestKey(key))
790
+ return null;
791
+ if (usableApiKey(key))
792
+ return "That is a Live key. Init saves Test keys only; Live keys go into the host's secret settings by the merchant. Nothing was saved.";
793
+ return "That isn't a Relyon Test key (copy the whole Test key from the get-key page). Nothing was saved.";
794
+ }
795
+ /**
796
+ * Saves a Test key the merchant entered (init --key-from-stdin): in the
797
+ * private folder (owner-only) and as RELYON_API_KEY in the project's .env.
798
+ * Never prints or returns the key.
799
+ */
800
+ export async function saveEnteredTestKey(options) {
801
+ const env = options.env ?? process.env;
802
+ if (usableApiKey(env.RELYON_API_KEY))
803
+ return { envFile: { status: "unchanged" } };
804
+ const key = usableTestKey(options.key.trim());
805
+ if (!key)
806
+ throw Error("not a Test key");
807
+ let privateFile;
808
+ try {
809
+ const { dir } = await resolvePrivateDir(options.project, env, true);
810
+ if (dir) {
811
+ await writePrivateFile(dir, ENTERED_KEY_FILE, JSON.stringify({ object: "test_key", livemode: false, restrictedKey: key }), true);
812
+ privateFile = path.join(dir, ENTERED_KEY_FILE);
813
+ }
814
+ }
815
+ catch {
816
+ privateFile = undefined;
817
+ }
818
+ const envFile = await writeEnvKey(options.project, key, options.env).catch(() => ({ status: "refused", reason: ".env couldn't be written" }));
819
+ return { ...(privateFile ? { privateFile } : {}), envFile };
820
+ }