@waffo/pancake-cli 0.0.0-stage → 0.0.1-rc.2

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 (75) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/CONTRIBUTING.md +38 -0
  3. package/LICENSE +21 -0
  4. package/README.md +230 -2
  5. package/SECURITY.md +23 -0
  6. package/SKILL.md +110 -0
  7. package/dist/adapters/browser-login.js +210 -0
  8. package/dist/adapters/config.js +180 -0
  9. package/dist/adapters/files.js +222 -0
  10. package/dist/adapters/loopback-forward.js +33 -0
  11. package/dist/adapters/operations.js +89 -0
  12. package/dist/adapters/pancake/client.js +235 -0
  13. package/dist/adapters/pancake/conflict-error.js +18 -0
  14. package/dist/adapters/pancake/graphql-errors.js +41 -0
  15. package/dist/adapters/pancake/http-error-reason.js +12 -0
  16. package/dist/adapters/pancake/queries.js +9 -0
  17. package/dist/adapters/pancake/safe-reason.js +23 -0
  18. package/dist/adapters/system-process.js +12 -0
  19. package/dist/application/action-auth.js +7 -0
  20. package/dist/application/action-result.js +40 -0
  21. package/dist/application/api-actions.js +80 -0
  22. package/dist/application/api-reads.js +56 -0
  23. package/dist/application/auth-context.js +34 -0
  24. package/dist/application/auth.js +115 -0
  25. package/dist/application/confirmation.js +14 -0
  26. package/dist/application/diagnostics.js +48 -0
  27. package/dist/application/dispatch.js +109 -0
  28. package/dist/application/idempotency.js +8 -0
  29. package/dist/application/listen.js +147 -0
  30. package/dist/application/local.js +35 -0
  31. package/dist/application/product-verification.js +96 -0
  32. package/dist/application/products.js +70 -0
  33. package/dist/application/queries.js +26 -0
  34. package/dist/application/read-handlers.js +30 -0
  35. package/dist/application/read-operation.js +30 -0
  36. package/dist/application/webhooks.js +56 -0
  37. package/dist/application/write-operation.js +26 -0
  38. package/dist/cli/guidance.js +29 -0
  39. package/dist/cli/human-output.js +44 -0
  40. package/dist/cli/input.js +62 -0
  41. package/dist/cli/listen-output.js +10 -0
  42. package/dist/cli/login-prompt.js +66 -0
  43. package/dist/cli/output.js +43 -0
  44. package/dist/cli/run.js +128 -0
  45. package/dist/commands/action-definitions.js +100 -0
  46. package/dist/commands/action-previews.js +12 -0
  47. package/dist/commands/action-schemas.js +47 -0
  48. package/dist/commands/action-values.js +11 -0
  49. package/dist/commands/api-coverage.js +25 -0
  50. package/dist/commands/checkout-action-schema.js +25 -0
  51. package/dist/commands/discount-definitions.js +47 -0
  52. package/dist/commands/discount-preview.js +17 -0
  53. package/dist/commands/discount-schemas.js +39 -0
  54. package/dist/commands/discount-validation.js +17 -0
  55. package/dist/commands/listen-input.js +12 -0
  56. package/dist/commands/operation-impact.js +16 -0
  57. package/dist/commands/product-action-schemas.js +26 -0
  58. package/dist/commands/product-preview.js +5 -0
  59. package/dist/commands/read-definitions.js +92 -0
  60. package/dist/commands/read-query.js +49 -0
  61. package/dist/commands/read-schemas.js +17 -0
  62. package/dist/commands/registry.js +45 -0
  63. package/dist/commands/schemas.js +94 -0
  64. package/dist/commands/webhook-preview.js +3 -0
  65. package/dist/contracts/action-routes.js +7 -0
  66. package/dist/contracts/command.js +1 -0
  67. package/dist/contracts/errors.js +26 -0
  68. package/dist/contracts/impact.js +1 -0
  69. package/dist/contracts/listen.js +1 -0
  70. package/dist/contracts/loopback-target.js +14 -0
  71. package/dist/contracts/types.js +1 -0
  72. package/dist/index.js +20 -0
  73. package/docs/api-coverage.md +154 -0
  74. package/docs/usage.md +458 -0
  75. package/package.json +60 -4
@@ -0,0 +1,210 @@
1
+ import { windowsSystemTool, systemProcessEnvironment } from "./system-process.js";
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import pkg from '../../package.json' with { type: 'json' };
6
+ import { CliError } from "../contracts/errors.js";
7
+ export function serviceOrigin(value) {
8
+ let url;
9
+ try {
10
+ url = new URL(value);
11
+ }
12
+ catch {
13
+ throw new CliError('INVALID_ARGUMENT', 'Provide a valid API or Dashboard origin.', { exitCode: 2 });
14
+ }
15
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1'))) {
16
+ throw new CliError('INVALID_ARGUMENT', 'Service URLs must be HTTPS origins, or explicit http://127.0.0.1:<port> origins for local testing.', { exitCode: 2 });
17
+ }
18
+ return url.origin;
19
+ }
20
+ async function openBrowser(url) {
21
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? windowsSystemTool('browser') : 'xdg-open';
22
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
23
+ try {
24
+ await promisify(execFile)(command, args, { timeout: 10000, env: systemProcessEnvironment() });
25
+ }
26
+ catch {
27
+ throw new CliError('BROWSER_UNAVAILABLE', 'Could not open your browser. Open the displayed login link manually.', { stage: 'browser' });
28
+ }
29
+ }
30
+ function loginTimeout() { return new CliError('LOGIN_TIMEOUT', 'Browser login timed out. Run pancake login again.', { stage: 'authorization' }); }
31
+ function invalidResponse() { return new CliError('AUTH_FAILED', 'The authorization response was invalid.', { stage: 'authorization' }); }
32
+ function savedLoginCleanupFailure(error) {
33
+ return error instanceof CliError && error.code === 'CREDENTIAL_CLEANUP_FAILED' && error.outcome === 'committed_unverified' && error.details.configUpdated === true;
34
+ }
35
+ function deviceRequest(value) {
36
+ const data = value;
37
+ if (!data || typeof data.deviceCode !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(data.deviceCode) || typeof data.userCode !== 'string' || !/^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(data.userCode) || typeof data.expiresIn !== 'number' || !Number.isInteger(data.expiresIn) || data.expiresIn <= 0 || data.expiresIn > 900 || typeof data.interval !== 'number' || !Number.isInteger(data.interval) || data.interval < 5 || data.interval > 60)
38
+ throw invalidResponse();
39
+ return data;
40
+ }
41
+ function deviceToken(value, now) {
42
+ const data = value;
43
+ if (!data || typeof data.token !== 'string' || data.token.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(data.token) || typeof data.merchantId !== 'string' || !/^MER_[A-Za-z0-9]+$/.test(data.merchantId) || data.environment !== 'test' || typeof data.expiresAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T/.test(data.expiresAt) || !(Date.parse(data.expiresAt) > now))
44
+ throw invalidResponse();
45
+ return data;
46
+ }
47
+ async function authorizationJson(response) {
48
+ if (!response.body)
49
+ throw invalidResponse();
50
+ const reader = response.body.getReader();
51
+ const chunks = [];
52
+ let size = 0;
53
+ try {
54
+ for (;;) {
55
+ const { value, done } = await reader.read();
56
+ if (done)
57
+ break;
58
+ size += value.length;
59
+ if (size > 32768)
60
+ throw invalidResponse();
61
+ chunks.push(value);
62
+ }
63
+ }
64
+ finally {
65
+ await reader.cancel().catch(() => { });
66
+ }
67
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
68
+ }
69
+ export async function browserLogin(options, complete, dependencies = {}) {
70
+ const signal = dependencies.signal ?? options.signal;
71
+ const apiUrl = serviceOrigin(options.apiUrl ?? 'https://api.waffo.ai');
72
+ const dashboardUrl = serviceOrigin(options.dashboardUrl ?? 'https://pancake.waffo.ai');
73
+ const now = dependencies.now ?? Date.now;
74
+ const notify = dependencies.notify ?? (text => process.stderr.write(text + '\n'));
75
+ let deadline = now() + Math.min(dependencies.timeoutMs ?? 900000, 900000);
76
+ function check(cancel = true) {
77
+ if (cancel && signal?.aborted)
78
+ throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
79
+ if (now() >= deadline)
80
+ throw loginTimeout();
81
+ }
82
+ async function sleep(milliseconds, cancel = true) {
83
+ check(cancel);
84
+ try {
85
+ const duration = Math.min(milliseconds, deadline - now());
86
+ if (dependencies.sleep)
87
+ await dependencies.sleep(duration, cancel ? signal : undefined);
88
+ else
89
+ await delay(duration, undefined, { signal: cancel ? signal : undefined });
90
+ }
91
+ catch {
92
+ check(cancel);
93
+ throw new CliError('AUTH_FAILED', 'Could not continue browser login.');
94
+ }
95
+ check(cancel);
96
+ }
97
+ async function request(action, body, token, cancel = true) {
98
+ check(cancel);
99
+ const remaining = deadline - now();
100
+ const timeout = AbortSignal.timeout(Math.max(1, Math.min(15000, remaining)));
101
+ const requestSignal = cancel && signal ? AbortSignal.any([timeout, signal]) : timeout;
102
+ try {
103
+ const response = await (dependencies.fetch ?? fetch)(`${apiUrl}/v1/actions/auth/cli-device-${action}`, {
104
+ method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': `Pancake CLI/${pkg.version} (${process.platform}; ${process.arch})`, ...(token ? { Authorization: `Bearer ${token}` } : {}) },
105
+ body: JSON.stringify(body), redirect: 'error', signal: requestSignal,
106
+ });
107
+ const envelope = await authorizationJson(response).catch(error => { if (requestSignal.aborted || !(error instanceof SyntaxError))
108
+ throw error; return null; });
109
+ return { status: response.status, data: envelope?.data, error: envelope?.error };
110
+ }
111
+ catch (error) {
112
+ check(cancel);
113
+ if (timeout.aborted && remaining <= 15000)
114
+ throw loginTimeout();
115
+ if (error instanceof CliError)
116
+ throw error;
117
+ return { status: 503, data: null, error: undefined };
118
+ }
119
+ }
120
+ const startedAt = now();
121
+ let start = await request('start', {});
122
+ for (let attempt = 0; start.status === 503 && attempt < 2; attempt++) {
123
+ await sleep(1000);
124
+ start = await request('start', {});
125
+ }
126
+ if (start.status !== 200)
127
+ throw new CliError('AUTH_FAILED', 'Could not start browser login. Run pancake login again.');
128
+ const device = deviceRequest(start.data);
129
+ deadline = Math.min(deadline, startedAt + device.expiresIn * 1000);
130
+ const url = new URL('/merchant/auth/cli', dashboardUrl);
131
+ url.searchParams.set('user_code', device.userCode);
132
+ notify(`Login code: ${device.userCode}\nOpen your browser and approve this matching code.\n${url.toString()}`);
133
+ check();
134
+ try {
135
+ await (dependencies.open ?? openBrowser)(url.toString());
136
+ }
137
+ catch (error) {
138
+ if (error instanceof CliError && error.code === 'BROWSER_UNAVAILABLE')
139
+ notify(error.message);
140
+ else
141
+ throw new CliError('BROWSER_UNAVAILABLE', 'Could not open your browser. Open the displayed login link manually.');
142
+ }
143
+ let interval = device.interval * 1000;
144
+ let failures = 0;
145
+ let authorized;
146
+ while (true) {
147
+ await sleep(interval);
148
+ const response = await request('token', { deviceCode: device.deviceCode });
149
+ if (response.status === 200) {
150
+ authorized = deviceToken(response.data, now());
151
+ break;
152
+ }
153
+ if (response.status === 503 && failures++ < 2)
154
+ continue;
155
+ if (response.data === null && response.status === 400 && response.error === 'authorization_pending') {
156
+ failures = 0;
157
+ continue;
158
+ }
159
+ if (response.data === null && response.status === 429 && response.error === 'slow_down') {
160
+ failures = 0;
161
+ interval += 5000;
162
+ continue;
163
+ }
164
+ const failure = response.data === null ? response.error : undefined;
165
+ if (response.status === 403 && failure === 'access_denied')
166
+ throw new CliError('AUTH_FAILED', 'Browser login was denied. Your saved login was not changed.');
167
+ if (response.status === 400 && failure === 'expired_token')
168
+ throw new CliError('LOGIN_TIMEOUT', 'Browser login expired. Run pancake login again.');
169
+ throw new CliError('AUTH_FAILED', 'Browser authorization failed. Run pancake login again.');
170
+ }
171
+ async function acknowledge(outcome) {
172
+ deadline = now() + 30000;
173
+ for (let attempt = 0; attempt < 3; attempt++) {
174
+ const response = await request('complete', { deviceCode: device.deviceCode, outcome }, authorized.token, false);
175
+ const expected = outcome === 'saved' ? 'completed' : 'failed';
176
+ if (response.status === 200 && response.data?.status === expected)
177
+ return;
178
+ if (response.status !== 503 || attempt === 2)
179
+ throw new CliError('AUTH_FAILED', 'Could not confirm browser login.');
180
+ await sleep(1000, false);
181
+ }
182
+ }
183
+ let result;
184
+ try {
185
+ check();
186
+ result = await complete({ merchantId: authorized.merchantId, sessionToken: authorized.token, environment: authorized.environment, expiresAt: authorized.expiresAt, apiUrl, source: 'login' });
187
+ }
188
+ catch (error) {
189
+ if (savedLoginCleanupFailure(error)) {
190
+ try {
191
+ await acknowledge('saved');
192
+ }
193
+ catch {
194
+ notify('Login saved, but confirmation failed. This login may expire within five minutes. Run pancake login again.');
195
+ }
196
+ }
197
+ else
198
+ await acknowledge('failed').catch(() => { });
199
+ throw error;
200
+ }
201
+ try {
202
+ await acknowledge('saved');
203
+ }
204
+ catch {
205
+ throw new CliError('LOGIN_CONFIRMATION_FAILED', 'Login saved, but confirmation failed. This login may expire within five minutes. Run pancake login again.', {
206
+ stage: 'authorization', outcome: 'committed_unverified', details: { credentialSaved: true },
207
+ });
208
+ }
209
+ return result;
210
+ }
@@ -0,0 +1,180 @@
1
+ import { homedir } from 'node:os';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { atomicJson, readJson, protectDirectory, withDirectoryLock, exportPrivateFile, hasCode } from "./files.js";
4
+ import { randomUUID } from 'node:crypto';
5
+ import { lstat, unlink } from 'node:fs/promises';
6
+ import { serviceOrigin } from "./browser-login.js";
7
+ import { CliError } from "../contracts/errors.js";
8
+ export function configDirectory(env = process.env) {
9
+ if (env.WAFFO_CONFIG_DIR)
10
+ return resolve(env.WAFFO_CONFIG_DIR);
11
+ return join(homedir(), '.waffo-pancake');
12
+ }
13
+ function validCredentialMaterial(credential) {
14
+ if (credential.sessionToken !== undefined) {
15
+ return typeof credential.sessionToken === 'string' && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(credential.sessionToken) && credential.sessionToken.length <= 16384 && credential.privateKeyFile === undefined && ['test', 'prod'].includes(credential.environment ?? '') && typeof credential.expiresAt === 'string' && Number.isFinite(Date.parse(credential.expiresAt)) && typeof credential.apiUrl === 'string' && serviceOrigin(credential.apiUrl) === credential.apiUrl;
16
+ }
17
+ return typeof credential.privateKeyFile === 'string' && isAbsolute(credential.privateKeyFile);
18
+ }
19
+ function checkCredential(value) {
20
+ const credential = value;
21
+ if (!credential || !/^MER_[A-Za-z0-9]+$/.test(credential.merchantId ?? '') || !validCredentialMaterial(credential) || (credential.storeId !== undefined && !/^STO_[A-Za-z0-9]+$/.test(credential.storeId))) {
22
+ throw new CliError('INVALID_CONFIG', 'Use a valid Merchant ID, absolute private-key path and optional Store ID.', { exitCode: 2, recovery: 'Run pancake logout to clear invalid local configuration, then pancake login.' });
23
+ }
24
+ }
25
+ function unsupportedVersion(legacy) {
26
+ return new CliError('CONFIG_VERSION_UNSUPPORTED', legacy ? 'Legacy configuration is no longer supported.' : 'Unsupported configuration version; this CLI will not overwrite it.', {
27
+ exitCode: 2, recovery: legacy ? 'Run pancake logout to clear the legacy configuration, then pancake login with your existing key file.' : 'Use a CLI version that supports this configuration.',
28
+ });
29
+ }
30
+ function parseConfig(raw) {
31
+ if (raw === undefined)
32
+ return { configVersion: 2 };
33
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
34
+ throw new CliError('INVALID_CONFIG', 'Invalid local configuration.', { exitCode: 2, recovery: 'Run pancake logout, then pancake login.' });
35
+ const config = raw;
36
+ if (config.configVersion !== 2)
37
+ throw unsupportedVersion(Number(config.configVersion) === 1);
38
+ if (config.credential !== undefined)
39
+ checkCredential(config.credential);
40
+ return { configVersion: 2, ...(config.revision ? { revision: config.revision } : {}), ...(config.credential ? { credential: config.credential } : {}) };
41
+ }
42
+ function configChanged() {
43
+ return new CliError('CONFIG_CHANGED', 'Your saved login changed during this command. Run the command again.', { stage: 'credentials' });
44
+ }
45
+ function protectFutureVersion(raw) {
46
+ if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion !== 1 && raw.configVersion !== 2)
47
+ throw unsupportedVersion(false);
48
+ }
49
+ export class ConfigStore {
50
+ directory;
51
+ constructor(directory) { this.directory = directory; }
52
+ async removeManagedKey(credential, outcome) {
53
+ if (!credential || typeof credential !== 'object' || !('privateKeyManaged' in credential) || credential.privateKeyManaged !== true || !('privateKeyFile' in credential) || typeof credential.privateKeyFile !== 'string')
54
+ return;
55
+ const path = credential.privateKeyFile;
56
+ try {
57
+ if (dirname(path) !== resolve(this.directory) || !/^key-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.pem$/.test(basename(path)))
58
+ throw new Error('Untrusted managed key path');
59
+ const stat = await lstat(path);
60
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (process.platform !== 'win32' && stat.uid !== process.getuid()))
61
+ throw new Error('Untrusted managed key file');
62
+ await unlink(path);
63
+ }
64
+ catch (error) {
65
+ if (hasCode(error, 'ENOENT'))
66
+ return;
67
+ throw new CliError('CREDENTIAL_CLEANUP_FAILED', outcome === 'saved' ? 'The new login was saved, but the previous managed private key could not be removed.' : 'The saved login was cleared, but its managed private key could not be removed.', {
68
+ stage: 'credentials', outcome: 'committed_unverified', details: { configUpdated: true }, recovery: 'Inspect the CLI configuration directory and remove the unused managed private key manually. The configuration update already completed.',
69
+ });
70
+ }
71
+ }
72
+ async read() {
73
+ await protectDirectory(this.directory);
74
+ return parseConfig(await readJson(join(this.directory, 'config.json')));
75
+ }
76
+ async save(credential, expected, signal) {
77
+ await withDirectoryLock(this.directory, async () => {
78
+ const snapshot = await this.read();
79
+ if (snapshot.revision !== expected.revision)
80
+ throw configChanged();
81
+ const previous = snapshot.credential;
82
+ if (signal?.aborted)
83
+ throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
84
+ if (credential.sessionToken && (credential.privateKey || credential.privateKeyFile))
85
+ throw new CliError('INVALID_CONFIG', 'Choose a session or an RSA credential, not both.', { exitCode: 2 });
86
+ let created;
87
+ try {
88
+ if (credential.privateKey) {
89
+ created = join(resolve(this.directory), `key-${randomUUID()}.pem`);
90
+ await exportPrivateFile(created, credential.privateKey);
91
+ }
92
+ const stored = { merchantId: credential.merchantId, ...(credential.sessionToken ? { sessionToken: credential.sessionToken, environment: credential.environment, expiresAt: credential.expiresAt, apiUrl: credential.apiUrl } : { privateKeyFile: created ?? credential.privateKeyFile }),
93
+ ...(!credential.sessionToken && (created || (previous?.privateKeyManaged && previous.privateKeyFile === credential.privateKeyFile)) ? { privateKeyManaged: true } : {}),
94
+ ...(credential.storeId ? { storeId: credential.storeId } : {}) };
95
+ checkCredential(stored);
96
+ await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID(), credential: stored }, signal);
97
+ }
98
+ catch (error) {
99
+ if (created)
100
+ await unlink(created).catch(() => { });
101
+ throw error;
102
+ }
103
+ if (previous?.privateKeyFile !== (created ?? credential.privateKeyFile))
104
+ await this.removeManagedKey(previous, 'saved');
105
+ });
106
+ }
107
+ async persistClearedConfig(raw) {
108
+ await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID() });
109
+ if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion === 2 && 'credential' in raw)
110
+ await this.removeManagedKey(raw.credential, 'cleared');
111
+ }
112
+ async clear(expected) {
113
+ await withDirectoryLock(this.directory, async () => {
114
+ let raw;
115
+ try {
116
+ raw = await readJson(join(this.directory, 'config.json'));
117
+ }
118
+ catch (error) {
119
+ if (error instanceof CliError && error.code === 'INVALID_CONFIG')
120
+ throw configChanged();
121
+ throw error;
122
+ }
123
+ protectFutureVersion(raw);
124
+ let snapshot;
125
+ try {
126
+ snapshot = parseConfig(raw);
127
+ }
128
+ catch (error) {
129
+ if (error instanceof CliError && ['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
130
+ throw configChanged();
131
+ throw error;
132
+ }
133
+ if (snapshot.revision !== expected.revision)
134
+ throw configChanged();
135
+ await this.persistClearedConfig(raw);
136
+ });
137
+ }
138
+ async clearInvalid() {
139
+ await withDirectoryLock(this.directory, async () => {
140
+ let raw;
141
+ try {
142
+ raw = await readJson(join(this.directory, 'config.json'));
143
+ }
144
+ catch (error) {
145
+ if (!(error instanceof CliError) || error.code !== 'INVALID_CONFIG')
146
+ throw error;
147
+ await this.persistClearedConfig(undefined);
148
+ return;
149
+ }
150
+ protectFutureVersion(raw);
151
+ try {
152
+ parseConfig(raw);
153
+ }
154
+ catch (error) {
155
+ if (!(error instanceof CliError) || !['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
156
+ throw error;
157
+ await this.persistClearedConfig(raw);
158
+ return;
159
+ }
160
+ throw configChanged();
161
+ });
162
+ }
163
+ }
164
+ export function hasEnvironmentCredentials(env) {
165
+ return env.WAFFO_MERCHANT_ID !== undefined || env.WAFFO_PRIVATE_KEY !== undefined || env.WAFFO_PRIVATE_KEY_FILE !== undefined;
166
+ }
167
+ export async function resolveCredentials(store, options, env) {
168
+ if (options.storeId !== undefined && !/^STO_[A-Za-z0-9]+$/.test(options.storeId))
169
+ throw new CliError('INVALID_CONFIG', 'Provide a valid Store ID.', { exitCode: 2, stage: 'credentials' });
170
+ if (hasEnvironmentCredentials(env)) {
171
+ if (!/^MER_[A-Za-z0-9]+$/.test(env.WAFFO_MERCHANT_ID ?? '') || (!env.WAFFO_PRIVATE_KEY && !env.WAFFO_PRIVATE_KEY_FILE) || (env.WAFFO_PRIVATE_KEY !== undefined && env.WAFFO_PRIVATE_KEY_FILE !== undefined)) {
172
+ throw new CliError('INVALID_CONFIG', 'Supply WAFFO_MERCHANT_ID and exactly one of WAFFO_PRIVATE_KEY or WAFFO_PRIVATE_KEY_FILE; credential sources are never combined.', { exitCode: 2, stage: 'credentials', recovery: 'Complete the environment credential pair, or unset all three WAFFO credential variables to use pancake login.' });
173
+ }
174
+ return { merchantId: env.WAFFO_MERCHANT_ID, privateKey: env.WAFFO_PRIVATE_KEY, privateKeyFile: env.WAFFO_PRIVATE_KEY_FILE ? resolve(env.WAFFO_PRIVATE_KEY_FILE) : undefined, storeId: options.storeId, source: 'environment' };
175
+ }
176
+ const { credential } = await store.read();
177
+ if (!credential)
178
+ throw new CliError('AUTH_REQUIRED', 'No saved or environment credentials.', { stage: 'credentials', recovery: 'Run pancake login --merchant-id MER_... --private-key-file /absolute/path/key.pem.' });
179
+ return { ...credential, storeId: options.storeId ?? credential.storeId, source: 'stored' };
180
+ }
@@ -0,0 +1,222 @@
1
+ import { lstat, mkdir, mkdtemp, open, chmod, rename, unlink, link, rmdir } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import lockfile from 'proper-lockfile';
8
+ import { windowsSystemTool, systemProcessEnvironment } from "./system-process.js";
9
+ import { CliError } from "../contracts/errors.js";
10
+ export function hasCode(error, code) {
11
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
12
+ }
13
+ export async function rejectSymlink(path) {
14
+ try {
15
+ if ((await lstat(path)).isSymbolicLink())
16
+ throw new CliError('UNSAFE_LOCAL_FILE', 'Symbolic links are not accepted for CLI state.');
17
+ }
18
+ catch (error) {
19
+ if (!hasCode(error, 'ENOENT'))
20
+ throw error;
21
+ }
22
+ }
23
+ export async function protectDirectory(path) {
24
+ await rejectSymlink(path);
25
+ let stat;
26
+ try {
27
+ stat = await lstat(path);
28
+ }
29
+ catch (error) {
30
+ if (hasCode(error, 'ENOENT'))
31
+ return;
32
+ throw error;
33
+ }
34
+ if (!stat.isDirectory())
35
+ throw new CliError('UNSAFE_LOCAL_FILE', 'CLI state must use a private directory.');
36
+ if (process.platform === 'win32') {
37
+ const script = `$ErrorActionPreference = 'Stop'
38
+ $PSModuleAutoLoadingPreference = 'None'
39
+ $path = $env:PANCAKE_STATE_DIRECTORY
40
+ $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
41
+ $acl = [System.IO.Directory]::GetAccessControl($path)
42
+ $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier])
43
+ if ($owner -ne $identity.User -and $owner -ne $identity.Owner) { throw 'State directory is not owned by the current user' }
44
+ $acl.SetOwner($identity.User)
45
+ $acl.SetAccessRuleProtection($true, $false)
46
+ foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) { $acl.RemoveAccessRuleSpecific($rule) }
47
+ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity.User, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
48
+ $acl.AddAccessRule($rule)
49
+ [System.IO.Directory]::SetAccessControl($path, $acl)`;
50
+ const environment = systemProcessEnvironment();
51
+ await promisify(execFile)(windowsSystemTool('powershell'), ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, env: { ...environment, PANCAKE_STATE_DIRECTORY: path } });
52
+ }
53
+ else {
54
+ if (stat.uid !== process.getuid())
55
+ throw new CliError('UNSAFE_LOCAL_FILE', 'CLI state directory is not owned by the current user.');
56
+ if ((stat.mode & 0o777) !== 0o700)
57
+ await chmod(path, 0o700);
58
+ }
59
+ }
60
+ export async function privateDirectory(path) {
61
+ await rejectSymlink(path);
62
+ await mkdir(path, { recursive: true, mode: 0o700 });
63
+ await protectDirectory(path);
64
+ }
65
+ export async function openRegularFile(path) {
66
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
67
+ try {
68
+ if (!(await handle.stat()).isFile())
69
+ throw new CliError('UNSAFE_LOCAL_FILE', 'Expected a regular file.', { exitCode: 2 });
70
+ return handle;
71
+ }
72
+ catch (error) {
73
+ await handle.close();
74
+ throw error;
75
+ }
76
+ }
77
+ export async function readJson(path) {
78
+ await rejectSymlink(path);
79
+ try {
80
+ const handle = await openRegularFile(path);
81
+ try {
82
+ if ((await handle.stat()).size > 8 * 1024 * 1024)
83
+ throw new CliError('LOCAL_STATE_TOO_LARGE', 'Local state file exceeds the supported size.', { exitCode: 2 });
84
+ return JSON.parse(await handle.readFile('utf8'));
85
+ }
86
+ finally {
87
+ await handle.close();
88
+ }
89
+ }
90
+ catch (error) {
91
+ if (hasCode(error, 'ENOENT'))
92
+ return undefined;
93
+ if (error instanceof SyntaxError)
94
+ throw new CliError('INVALID_CONFIG', 'Local state is not valid JSON.', { exitCode: 2 });
95
+ throw error;
96
+ }
97
+ }
98
+ export async function atomicJson(path, value, signal) {
99
+ await rejectSymlink(path);
100
+ const temporary = join(dirname(path), `.${randomUUID()}.tmp`);
101
+ const handle = await open(temporary, 'wx', 0o600);
102
+ try {
103
+ try {
104
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`);
105
+ await handle.sync();
106
+ }
107
+ finally {
108
+ await handle.close();
109
+ }
110
+ if (signal?.aborted)
111
+ throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
112
+ await rename(temporary, path);
113
+ }
114
+ finally {
115
+ await unlink(temporary).catch(error => { if (!hasCode(error, 'ENOENT'))
116
+ throw error; });
117
+ }
118
+ }
119
+ export async function withDirectoryLock(path, work) {
120
+ await privateDirectory(path);
121
+ const release = await lockfile.lock(path, { realpath: false, stale: 10000, retries: { retries: 20, minTimeout: 25, maxTimeout: 100 } });
122
+ try {
123
+ return await work();
124
+ }
125
+ finally {
126
+ await release();
127
+ }
128
+ }
129
+ async function reservePrivateFile(path) {
130
+ if (process.platform !== 'win32')
131
+ return open(path, 'wx', 0o600);
132
+ const staging = await mkdtemp(join(dirname(path), '.pancake-output-'));
133
+ const temporary = join(staging, 'output');
134
+ let handle;
135
+ let published = false;
136
+ try {
137
+ await protectDirectory(staging);
138
+ handle = await open(temporary, 'wx', 0o600);
139
+ await link(temporary, path);
140
+ published = true;
141
+ await unlink(temporary);
142
+ await rmdir(staging);
143
+ return handle;
144
+ }
145
+ catch (error) {
146
+ await handle?.close().catch(() => { });
147
+ if (published)
148
+ await unlink(path).catch(() => { });
149
+ await unlink(temporary).catch(() => { });
150
+ await rmdir(staging).catch(() => { });
151
+ throw error;
152
+ }
153
+ }
154
+ export async function preparePrivateOutput(path) {
155
+ await rejectSymlink(path);
156
+ let handle;
157
+ try {
158
+ handle = await reservePrivateFile(path);
159
+ }
160
+ catch (error) {
161
+ if (hasCode(error, 'EEXIST'))
162
+ throw new CliError('OUTPUT_EXISTS', 'The output file already exists. Choose a new path.', { exitCode: 2 });
163
+ throw error;
164
+ }
165
+ let closed = false;
166
+ const close = async () => { if (!closed) {
167
+ closed = true;
168
+ await handle.close();
169
+ } };
170
+ let committed = false;
171
+ return {
172
+ async commit(content) {
173
+ try {
174
+ await handle.writeFile(content);
175
+ await handle.sync();
176
+ await close();
177
+ committed = true;
178
+ }
179
+ catch (error) {
180
+ await close().catch(() => { });
181
+ await unlink(path).catch(() => { });
182
+ throw error;
183
+ }
184
+ },
185
+ async discard() { await close(); if (!committed)
186
+ await unlink(path).catch(error => { if (!hasCode(error, 'ENOENT'))
187
+ throw error; }); },
188
+ };
189
+ }
190
+ export async function exportPrivateFile(path, content) {
191
+ const output = await preparePrivateOutput(path);
192
+ try {
193
+ await output.commit(content);
194
+ }
195
+ finally {
196
+ await output.discard();
197
+ }
198
+ }
199
+ export async function readPrivateKey(path) {
200
+ try {
201
+ const handle = await openRegularFile(path);
202
+ try {
203
+ const stat = await handle.stat();
204
+ if (!stat.isFile() || stat.size > 64 * 1024)
205
+ throw new Error('Invalid key file');
206
+ if (process.platform !== 'win32' && (stat.mode & 0o077)) {
207
+ throw new CliError('INSECURE_KEY_FILE', 'Private key file is accessible to other users.', {
208
+ exitCode: 2, stage: 'credentials', recovery: 'Restrict the key file to its owner (chmod 600), then retry.',
209
+ });
210
+ }
211
+ return await handle.readFile('utf8');
212
+ }
213
+ finally {
214
+ await handle.close();
215
+ }
216
+ }
217
+ catch (error) {
218
+ if (error instanceof CliError)
219
+ throw error;
220
+ throw new CliError('KEY_UNREADABLE', 'Cannot read the private key file.', { exitCode: 2, stage: 'credentials' });
221
+ }
222
+ }
@@ -0,0 +1,33 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { loopbackTarget } from "../contracts/loopback-target.js";
4
+ const allowedHeaders = new Set(['content-type', 'x-waffo-signature', 'x-waffo-event']);
5
+ export async function forwardLoopback({ url, delivery, signal }) {
6
+ const target = new URL(loopbackTarget(url));
7
+ // Resolve the allowed localhost name to loopback ourselves; never follow DNS or redirects.
8
+ if (target.hostname === 'localhost')
9
+ target.hostname = '127.0.0.1';
10
+ const headers = Object.fromEntries(Object.entries(delivery.headers).filter(([name]) => allowedHeaders.has(name.toLowerCase())));
11
+ const timeout = AbortSignal.timeout(10000);
12
+ const requestSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
13
+ return new Promise(resolve => {
14
+ let settled = false;
15
+ const finish = (status) => { if (!settled) {
16
+ settled = true;
17
+ resolve(status);
18
+ } };
19
+ try {
20
+ const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, { method: 'POST', headers, signal: requestSignal, agent: false }, response => {
21
+ // Only the status matters. Bound memory and lifetime by discarding the response immediately.
22
+ const status = response.statusCode ?? null;
23
+ response.destroy();
24
+ finish(status);
25
+ });
26
+ request.on('error', () => finish(null));
27
+ request.end(Buffer.from(delivery.body, 'utf8'));
28
+ }
29
+ catch {
30
+ finish(null);
31
+ }
32
+ });
33
+ }