@waffo/pancake-cli 0.0.1-rc.2 → 0.0.1-rc.4

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 (37) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -13
  3. package/SKILL.md +8 -4
  4. package/dist/adapters/browser-login.js +1 -13
  5. package/dist/adapters/config.js +1 -1
  6. package/dist/adapters/operations.js +60 -2
  7. package/dist/adapters/pancake/client.js +48 -22
  8. package/dist/adapters/pancake/listener-http-error.js +43 -0
  9. package/dist/adapters/pancake/retry-after.js +46 -0
  10. package/dist/application/api-reads.js +1 -1
  11. package/dist/application/diagnostics.js +2 -1
  12. package/dist/application/dispatch.js +6 -2
  13. package/dist/application/listen-history.js +41 -0
  14. package/dist/application/listen-resend.js +101 -0
  15. package/dist/application/listen.js +23 -18
  16. package/dist/application/listener-context.js +11 -0
  17. package/dist/application/listener-signature.js +24 -0
  18. package/dist/application/local.js +1 -1
  19. package/dist/application/read-operation.js +15 -7
  20. package/dist/cli/human-output.js +7 -0
  21. package/dist/cli/listen-history-output.js +29 -0
  22. package/dist/cli/listen-output.js +2 -2
  23. package/dist/cli/output.js +1 -1
  24. package/dist/cli/run.js +10 -0
  25. package/dist/commands/api-coverage.js +7 -0
  26. package/dist/commands/listen-definitions.js +14 -0
  27. package/dist/commands/listen-input.js +6 -2
  28. package/dist/commands/listen-response.js +47 -0
  29. package/dist/commands/read-definitions.js +9 -1
  30. package/dist/commands/registry.js +5 -3
  31. package/dist/contracts/action-routes.js +14 -0
  32. package/dist/contracts/listen-replay.js +20 -0
  33. package/dist/contracts/listener-protocol.js +12 -0
  34. package/dist/contracts/listener-routes.js +11 -0
  35. package/docs/api-coverage.md +7 -4
  36. package/docs/usage.md +49 -7
  37. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  import { productPreview } from "../commands/product-preview.js";
2
2
  import { webhookPreview } from "../commands/webhook-preview.js";
3
3
  import { operationImpact } from "../commands/operation-impact.js";
4
+ import { readListenHistory } from "./listen-history.js";
5
+ import { resendListenerRecord } from "./listen-resend.js";
4
6
  import { listen } from "./listen.js";
5
7
  import { validateDiscountInput } from "../commands/discount-validation.js";
6
8
  import { argumentError } from "../contracts/errors.js";
@@ -38,9 +40,11 @@ export function createApplication(services) {
38
40
  }
39
41
  }]));
40
42
  const handlers = { ...localHandlers(services), ...readHandlers(services), ...webhookHandlers,
43
+ 'listen.history': (_input, options) => readListenHistory(undefined, options, services),
44
+ 'listen.show': (input, options) => readListenHistory(input.recordId, options, services),
45
+ 'listen.resend': (input, options) => resendListenerRecord(input.recordId, options, services),
41
46
  listen: (_input, options) => listen(options, services),
42
- 'products.create': (input, options) => createProduct(input, options, services, services.fingerprint(input)),
43
- };
47
+ 'products.create': (input, options) => createProduct(input, options, services, services.fingerprint(input)), };
44
48
  return async function execute({ id, options, input: provided }) {
45
49
  const definition = definitions.find(item => item.id === id);
46
50
  const handler = handlers[id];
@@ -0,0 +1,41 @@
1
+ import { listenerScope } from "../commands/listen-input.js";
2
+ import { historyResult, detailResult } from "../commands/listen-response.js";
3
+ import { credentialContext, contextualError } from "./auth-context.js";
4
+ import { listenerCredentials, verifyListenerEnvironment } from "./listener-context.js";
5
+ import { requireListenerProtocol } from "../contracts/listener-protocol.js";
6
+ import { pagination } from "./queries.js";
7
+ export async function readListenHistory(recordId, options, services) {
8
+ const { storeId, environment } = listenerScope(options);
9
+ const { limit } = pagination(options);
10
+ const credentials = await listenerCredentials(options, environment, services);
11
+ const attempts = [];
12
+ const gateway = await services.gateway(credentials, event => {
13
+ attempts.push(event);
14
+ if (options.debug)
15
+ services.diagnostic({ stage: 'api', ...event });
16
+ });
17
+ const meta = () => ({ ...credentialContext(credentials, attempts), storeId, requestId: attempts.at(-1)?.requestId ?? null });
18
+ const output = options.output ? await services.prepareOutput(options.output) : undefined;
19
+ try {
20
+ if (!recordId) {
21
+ const raw = await gateway.listen('history', { storeId, limit }, options.signal);
22
+ verifyListenerEnvironment(attempts.at(-1), environment);
23
+ requireListenerProtocol(raw);
24
+ return { data: historyResult(raw, environment, limit), meta: meta() };
25
+ }
26
+ const raw = await gateway.listen('detail', { storeId, recordId }, options.signal);
27
+ verifyListenerEnvironment(attempts.at(-1), environment);
28
+ requireListenerProtocol(raw);
29
+ const detail = detailResult(raw, environment, recordId);
30
+ if (output)
31
+ await output.commit(JSON.stringify(detail, null, 2) + '\n');
32
+ const { body: _privateBody, contentType: _contentType, ...record } = detail.record;
33
+ return { data: { record, ...(output ? { output: options.output } : {}) }, meta: meta() };
34
+ }
35
+ catch (error) {
36
+ throw contextualError(error, meta());
37
+ }
38
+ finally {
39
+ await output?.discard();
40
+ }
41
+ }
@@ -0,0 +1,101 @@
1
+ import { listenerScope } from "../commands/listen-input.js";
2
+ import { replayReceipt } from "../commands/listen-response.js";
3
+ import { operationImpact } from "../commands/operation-impact.js";
4
+ import { uuid } from "../commands/schemas.js";
5
+ import { DEFAULT_API_ORIGIN, serviceOrigin } from "../contracts/action-routes.js";
6
+ import { argumentError, CliError, safeError } from "../contracts/errors.js";
7
+ import { ConfirmedReplayRejection } from "../contracts/listen-replay.js";
8
+ import { listenerUpgradeCode, requireListenerProtocol } from "../contracts/listener-protocol.js";
9
+ import { listenerEndpoint } from "../contracts/listener-routes.js";
10
+ import { credentialContext, contextualError } from "./auth-context.js";
11
+ import { requireImpactConfirmation } from "./confirmation.js";
12
+ import { listenerCredentials, verifyListenerEnvironment } from "./listener-context.js";
13
+ const uuidPattern = new RegExp(uuid.pattern);
14
+ const recovery = 'Repeat the same listen resend command with the same UUID within 24 hours to recover its receipt.';
15
+ export async function resendListenerRecord(recordId, options, services) {
16
+ const { storeId, environment } = listenerScope(options);
17
+ if (!options.yes)
18
+ throw argumentError('Review the target listener and pass --yes to confirm.');
19
+ if (!options.session || !uuidPattern.test(options.session))
20
+ throw argumentError('Provide the target listener UUID with --session.');
21
+ if (!options.idempotencyKey || !uuidPattern.test(options.idempotencyKey))
22
+ throw argumentError('Provide a replay UUID with --idempotency-key.');
23
+ const impact = operationImpact({ id: 'listen.resend', effect: 'write' }, environment);
24
+ requireImpactConfirmation(impact, options);
25
+ const credentials = await listenerCredentials(options, environment, services);
26
+ const apiOrigin = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
27
+ const sessionId = options.session.toLowerCase();
28
+ const replayId = options.idempotencyKey.toLowerCase();
29
+ const body = { storeId, recordId, sessionId, replayId, live: environment === 'prod' };
30
+ const operation = await services.operations.beginListenReplay({
31
+ command: 'listen.resend', cliVersion: services.cliVersion, idempotencyKey: replayId, impact: environment,
32
+ merchantId: credentials.merchantId, storeId, selectedEnvironment: environment, apiOrigin, endpoint: listenerEndpoint('replay'),
33
+ targetResourceId: recordId, targetSessionId: sessionId, inputHash: services.fingerprint(body),
34
+ });
35
+ const attempts = [];
36
+ const observe = (attempt) => {
37
+ attempts.push(attempt);
38
+ if (options.debug)
39
+ services.diagnostic({ stage: 'api', ...attempt });
40
+ };
41
+ const { operationId } = operation;
42
+ const meta = () => ({ ...credentialContext(credentials, attempts), ...impact, apiOrigin, storeId, operationId,
43
+ idempotencyKey: replayId, requestId: attempts.at(-1)?.requestId ?? null });
44
+ let submitted = false;
45
+ let replayAttemptIndex = 0;
46
+ try {
47
+ const gateway = await services.gateway(credentials, observe);
48
+ await gateway.me(options.signal, { listener: true });
49
+ verifyListenerEnvironment(attempts.at(-1), environment);
50
+ const historyAttemptIndex = attempts.length;
51
+ const history = await gateway.listen('history', { storeId, limit: 1 }, options.signal);
52
+ verifyListenerEnvironment(attempts[historyAttemptIndex], environment);
53
+ requireListenerProtocol(history);
54
+ await services.operations.updateListenReplay(operationId, { kind: 'submitting' });
55
+ submitted = true;
56
+ replayAttemptIndex = attempts.length;
57
+ const raw = await gateway.listen('replay', body, options.signal);
58
+ verifyListenerEnvironment(attempts[replayAttemptIndex], environment);
59
+ requireListenerProtocol(raw);
60
+ const receipt = replayReceipt(raw, sessionId, recordId);
61
+ try {
62
+ await services.operations.updateListenReplay(operationId, { kind: 'accepted', resourceId: receipt.recordId, attempts });
63
+ }
64
+ catch {
65
+ throw new CliError('VERIFICATION_PENDING', 'The replay was accepted, but saving the receipt to the local operation failed.', {
66
+ stage: 'local-persistence', outcome: 'committed_unverified', recovery, details: { resourceId: receipt.recordId },
67
+ });
68
+ }
69
+ return { data: receipt, meta: { ...meta(), verification: 'response_only' } };
70
+ }
71
+ catch (error) {
72
+ const failure = safeError(error);
73
+ if (failure.outcome === 'committed_unverified')
74
+ throw contextualError(failure, meta());
75
+ const event = replayFailure(submitted, failure, attempts);
76
+ const saved = await services.operations.updateListenReplay(operationId, event).catch(() => undefined);
77
+ if (failure.code === 'REPLAY_WINDOW_EXPIRED') {
78
+ throw contextualError(new CliError(failure.code, failure.message, {
79
+ stage: failure.stage, outcome: saved?.outcome ?? failure.outcome, recovery: failure.recovery,
80
+ }), meta());
81
+ }
82
+ if (saved?.outcome === 'rejected')
83
+ throw contextualError(failure, meta());
84
+ if (saved?.outcome === 'completed') {
85
+ throw contextualError(new CliError(failure.code, failure.message, {
86
+ exitCode: failure.exitCode, stage: failure.stage, outcome: 'completed',
87
+ recovery: 'A previous call confirmed admission. Inspect the saved listener record.',
88
+ details: { ...failure.details, resourceId: saved.resourceId },
89
+ }), meta());
90
+ }
91
+ throw contextualError(new CliError('OUTCOME_UNKNOWN', 'Listener replay admission could not be confirmed.', {
92
+ stage: 'listen', outcome: 'unknown', recovery: failure.code === listenerUpgradeCode ? `${failure.recovery} ${recovery}` : recovery,
93
+ details: { cause: failure.code },
94
+ }), meta());
95
+ }
96
+ }
97
+ function replayFailure(submitted, failure, attempts) {
98
+ if (!submitted)
99
+ return { kind: 'unsent', errorCode: failure.code, attempts };
100
+ return { kind: failure instanceof ConfirmedReplayRejection ? 'rejected' : 'uncertain', errorCode: failure.code, attempts };
101
+ }
@@ -1,4 +1,8 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
+ import { eventIdPattern, eventTypePattern, recordIdPattern } from "../contracts/listener-routes.js";
3
+ import { listenerCredentials, verifyListenerEnvironment } from "./listener-context.js";
4
+ import { listenerProtocol, requireListenerProtocol } from "../contracts/listener-protocol.js";
5
+ import { listenerVerificationKey, verifyListenerSignature } from "./listener-signature.js";
2
6
  import { listenInput } from "../commands/listen-input.js";
3
7
  import { CliError, safeError } from "../contracts/errors.js";
4
8
  import { credentialContext, contextualError } from "./auth-context.js";
@@ -7,6 +11,7 @@ function invalidResponse() {
7
11
  }
8
12
  function terminalFailure(error) {
9
13
  const messages = {
14
+ LISTENER_RESTART_REQUIRED: 'This listener has expired after a service update. Start a new listener with pancake listen.',
10
15
  DELIVERY_FAILED: 'Local delivery attempts were exhausted. Check your receiver before restarting.',
11
16
  QUEUE_OVERFLOW: 'The listener queue overflowed. Restart after your receiver can keep up with events.',
12
17
  PAYLOAD_TOO_LARGE: 'An event exceeded the listener payload limit. Inspect the event before restarting.',
@@ -34,7 +39,7 @@ function deliveries(data, sessionId) {
34
39
  if (!item || typeof item !== 'object')
35
40
  throw invalidResponse();
36
41
  const value = item;
37
- if (typeof value.id !== 'string' || !/^[\x20-\x7E]{1,160}$/.test(value.id) || typeof value.eventType !== 'string' || !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(value.eventType) || typeof value.body !== 'string' || Buffer.byteLength(value.body) > 65536 || !Number.isInteger(value.attempt) || Number(value.attempt) < 1 || Number(value.attempt) > 3 || !value.headers || typeof value.headers !== 'object' || Array.isArray(value.headers))
42
+ if (typeof value.id !== 'string' || !/^[\x20-\x7E]{1,160}$/.test(value.id) || typeof value.eventId !== 'string' || !eventIdPattern.test(value.eventId) || typeof value.recordId !== 'string' || !recordIdPattern.test(value.recordId) || typeof value.eventType !== 'string' || !eventTypePattern.test(value.eventType) || typeof value.body !== 'string' || Buffer.byteLength(value.body) > 65536 || !Number.isInteger(value.attempt) || Number(value.attempt) < 1 || Number(value.attempt) > 3 || !value.headers || typeof value.headers !== 'object' || Array.isArray(value.headers))
38
43
  throw invalidResponse();
39
44
  const headers = value.headers;
40
45
  if (Object.entries(headers).some(([key, header]) => !/^[A-Za-z0-9-]+$/.test(key) || typeof header !== 'string' || header.length > 8192 || /[\r\n]/.test(header)))
@@ -42,16 +47,9 @@ function deliveries(data, sessionId) {
42
47
  return value;
43
48
  });
44
49
  }
45
- function verifyEnvironment(attempt, expected) {
46
- if (attempt?.environment !== expected)
47
- throw new CliError('ENVIRONMENT_MISMATCH', 'The API did not verify the requested listener environment.', { stage: 'listen', details: { expectedEnvironment: expected } });
48
- }
49
50
  export async function listen(options, services) {
50
51
  const input = listenInput(options);
51
- const saved = await services.credentials(options);
52
- if (!saved.sessionToken)
53
- throw new CliError('BROWSER_LOGIN_REQUIRED', 'Listening requires browser login. RSA keys are not supported.', { exitCode: 2, recovery: 'Run pancake login in a terminal.' });
54
- const credentials = { ...saved, environment: input.environment };
52
+ const credentials = await listenerCredentials(options, input.environment, services);
55
53
  const attempts = [];
56
54
  const gateway = await services.gateway(credentials, attempt => {
57
55
  // A listener can run indefinitely; retain only the latest request evidence.
@@ -72,30 +70,37 @@ export async function listen(options, services) {
72
70
  try {
73
71
  if (!services.forwardLoopback)
74
72
  throw new CliError('LOCAL_ERROR', 'Local forwarding is unavailable.');
75
- await gateway.me(options.signal);
76
- verifyEnvironment(attempts[0], input.environment);
73
+ await gateway.me(options.signal, { listener: true });
74
+ verifyListenerEnvironment(attempts[0], input.environment);
77
75
  if (options.signal?.aborted)
78
76
  return { data: { type: 'stopped', sessionId: null, cleanedUp: true } };
79
77
  startRequested = true;
80
- const started = await request('start', { storeId: input.storeId, ...(input.events ? { events: input.events } : {}), live: input.environment === 'prod' }, options.signal);
78
+ const started = await request('start', { storeId: input.storeId, listenerProtocol, ...(input.events ? { events: input.events } : {}), live: input.environment === 'prod' }, options.signal);
81
79
  if (typeof started.sessionId === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(started.sessionId))
82
80
  sessionId = started.sessionId;
83
- verifyEnvironment(attempts[0], input.environment);
81
+ verifyListenerEnvironment(attempts[0], input.environment);
84
82
  if (!sessionId || started.environment !== input.environment || started.expiresIn !== 90 || started.pollIntervalMs !== 3000 || started.maxAttempts !== 3)
85
83
  throw invalidResponse();
86
- emit({ type: 'ready', sessionId, environment: input.environment });
84
+ requireListenerProtocol(started);
85
+ const verificationKey = listenerVerificationKey(started.signingPublicKey);
86
+ const signingPublicKey = verificationKey.export({ type: 'spki', format: 'pem' }).toString();
87
+ emit({ type: 'ready', sessionId, environment: input.environment, listenerProtocol, signingPublicKey });
87
88
  while (!options.signal?.aborted) {
88
89
  const polled = await request('poll', { storeId: input.storeId, sessionId }, options.signal);
89
- verifyEnvironment(attempts[0], input.environment);
90
+ verifyListenerEnvironment(attempts[0], input.environment);
91
+ // Legacy sessions can still report a terminal restart reason during a rollout.
92
+ if (polled.status !== 'failed')
93
+ requireListenerProtocol(polled);
90
94
  for (const delivery of deliveries(polled, sessionId)) {
91
95
  if (options.signal?.aborted)
92
96
  break;
97
+ verifyListenerSignature(verificationKey, delivery);
93
98
  const httpStatus = await services.forwardLoopback({ url: input.url, delivery, signal: options.signal });
94
- emit({ type: 'delivery', sessionId, deliveryId: delivery.id, eventId: delivery.id, eventType: delivery.eventType, attempt: delivery.attempt, httpStatus });
99
+ emit({ type: 'delivery', sessionId, deliveryId: delivery.id, recordId: delivery.recordId, eventId: delivery.eventId, eventType: delivery.eventType, attempt: delivery.attempt, httpStatus });
95
100
  if (options.signal?.aborted)
96
101
  break;
97
102
  const ack = await request('ack', { storeId: input.storeId, sessionId, deliveryId: delivery.id, attempt: delivery.attempt, httpStatus }, options.signal);
98
- verifyEnvironment(attempts[0], input.environment);
103
+ verifyListenerEnvironment(attempts[0], input.environment);
99
104
  const success = httpStatus !== null && httpStatus >= 200 && httpStatus < 300;
100
105
  if (ack.status === 'failed')
101
106
  throw terminalFailure(ack.error ?? { code: 'DELIVERY_FAILED' });
@@ -122,7 +127,7 @@ export async function listen(options, services) {
122
127
  if (sessionId) {
123
128
  try {
124
129
  const stopped = await request('stop', { storeId: input.storeId, sessionId });
125
- verifyEnvironment(attempts[0], input.environment);
130
+ verifyListenerEnvironment(attempts[0], input.environment);
126
131
  if (stopped.stopped !== true)
127
132
  throw invalidResponse();
128
133
  cleanedUp = true;
@@ -0,0 +1,11 @@
1
+ import { CliError } from "../contracts/errors.js";
2
+ export async function listenerCredentials(options, environment, services) {
3
+ const saved = await services.credentials(options);
4
+ if (!saved.sessionToken)
5
+ throw new CliError('BROWSER_LOGIN_REQUIRED', 'Listener commands require browser login.', { exitCode: 2, recovery: 'Run pancake login in a terminal.' });
6
+ return { ...saved, environment };
7
+ }
8
+ export function verifyListenerEnvironment(attempt, expected) {
9
+ if (attempt?.environment !== expected)
10
+ throw new CliError('ENVIRONMENT_MISMATCH', 'The API did not verify the requested listener environment.', { stage: 'listen', details: { expectedEnvironment: expected } });
11
+ }
@@ -0,0 +1,24 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ import { CliError } from "../contracts/errors.js";
3
+ export function listenerVerificationKey(value) {
4
+ const invalidKey = () => new CliError('INVALID_RESPONSE', 'The listener returned an invalid session verification key.', { stage: 'listen' });
5
+ if (typeof value !== 'string' || value.length > 1024 || !value.startsWith('-----BEGIN PUBLIC KEY-----'))
6
+ throw invalidKey();
7
+ try {
8
+ const key = createPublicKey(value);
9
+ const pem = key.export({ type: 'spki', format: 'pem' }).toString();
10
+ if (key.asymmetricKeyType === 'rsa' && key.asymmetricKeyDetails?.modulusLength === 2048 && pem.trimEnd() === value.replaceAll('\r\n', '\n').trimEnd())
11
+ return key;
12
+ }
13
+ catch { /* Omit untrusted key material and parser diagnostics. */ }
14
+ throw invalidKey();
15
+ }
16
+ export function verifyListenerSignature(key, delivery) {
17
+ const signatures = Object.entries(delivery.headers).filter(([name]) => name.toLowerCase() === 'x-waffo-signature');
18
+ const match = signatures.length === 1 && /^t=(\d{1,16}),v1=([A-Za-z0-9+/]{342}==)$/.exec(signatures[0][1]);
19
+ if (!match || !verify('RSA-SHA256', Buffer.from(`${match[1]}.${delivery.body}`, 'utf8'), key, Buffer.from(match[2], 'base64'))) {
20
+ throw new CliError('LISTENER_SIGNATURE_INVALID', 'The delivery did not verify with this listener session’s public key.', {
21
+ stage: 'listen', recovery: 'Confirm that the listener services support protocol 2, then start a new listener.',
22
+ });
23
+ }
24
+ }
@@ -13,7 +13,7 @@ export function localHandlers(services) {
13
13
  if (!item)
14
14
  throw argumentError('Unknown command ID. Run pancake commands.');
15
15
  const api = commandApi(item.id);
16
- return { data: { id: item.id, input: item.schema, output: outputContract, effect: item.effect, ...operationImpact(item), example: item.example, api, options: item.options ?? [], globalOptions, argument: item.argument ?? null, file: item.file ? '--file <path> or --file - for stdin' : null, authentication: api?.authentication === 'merchant-rsa' ? 'merchant-rsa (not needed for offline dry-run)' : ['env', 'listen'].includes(item.id) ? 'merchant-session' : item.id === 'login' || ['read', 'write'].includes(item.effect) ? 'merchant-session or merchant-rsa (not needed for offline dry-run)' : 'none', permissions: 'server-enforced; fine-grained credential scopes are not verified', availability: 'available' } };
16
+ return { data: { id: item.id, input: item.schema, output: outputContract, effect: item.effect, ...operationImpact(item), example: item.example, api, options: item.id.startsWith('listen.') ? [...(item.options ?? []), ['--live', 'Use Production; defaults to Test']] : item.options ?? [], globalOptions, argument: item.argument ?? null, file: item.file ? '--file <path> or --file - for stdin' : null, authentication: api?.authentication === 'merchant-rsa' ? 'merchant-rsa (not needed for offline dry-run)' : (item.id === 'env' || api?.authentication === 'merchant-session only') ? 'merchant-session' : item.id === 'login' || ['read', 'write'].includes(item.effect) ? 'merchant-session or merchant-rsa (not needed for offline dry-run)' : 'none', permissions: 'server-enforced; fine-grained credential scopes are not verified', availability: 'available' } };
17
17
  },
18
18
  login: async (_input, options) => login(options, services),
19
19
  env: async (input, options) => selectEnvironment(input.environment, options, services),
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_API_ORIGIN, serviceOrigin } from "../contracts/action-routes.js";
1
2
  import { safeError } from "../contracts/errors.js";
2
3
  import { credentialContext, contextualError } from "./auth-context.js";
3
4
  export async function readOperation(id, options, services, work, suppliedCredentials) {
@@ -6,25 +7,32 @@ export async function readOperation(id, options, services, work, suppliedCredent
6
7
  }
7
8
  export async function authenticatedOperation(id, options, services, credentials, work) {
8
9
  const attempts = [];
10
+ const background = id === 'graphql.query' && options.background;
9
11
  let operationId;
10
- try {
11
- operationId = (await services.operations.begin({ command: id, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: credentials.storeId })).operationId;
12
- }
13
- catch {
14
- services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' });
12
+ let apiOrigin;
13
+ if (!background) {
14
+ try {
15
+ operationId = (await services.operations.begin({ command: id, cliVersion: services.cliVersion, merchantId: credentials.merchantId, storeId: credentials.storeId })).operationId;
16
+ }
17
+ catch {
18
+ services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' });
19
+ }
15
20
  }
21
+ const metadata = () => ({ ...credentialContext(credentials, attempts), ...(apiOrigin ? { apiOrigin } : {}), operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null });
16
22
  const observer = (event) => { attempts.push(event); if (options.debug)
17
23
  services.diagnostic({ stage: 'api', ...event }); };
18
24
  try {
25
+ if (background)
26
+ apiOrigin = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
19
27
  const data = await work(observer);
20
28
  if (operationId)
21
29
  await services.operations.finish(operationId, { outcome: 'completed', attempts }).catch(() => services.diagnostic({ level: 'warning', code: 'OPERATION_RECORD_UNAVAILABLE' }));
22
- return { data, meta: { operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null, ...credentialContext(credentials, attempts) } };
30
+ return { data, meta: metadata() };
23
31
  }
24
32
  catch (error) {
25
33
  const failure = safeError(error);
26
34
  if (operationId)
27
35
  await services.operations.finish(operationId, { outcome: failure.outcome, errorCode: failure.code, attempts }).catch(() => { });
28
- throw contextualError(failure, { ...credentialContext(credentials, attempts), operationId: operationId ?? null, requestId: attempts.at(-1)?.requestId ?? null });
36
+ throw contextualError(failure, metadata());
29
37
  }
30
38
  }
@@ -1,3 +1,4 @@
1
+ import { historyText, detailText, receiptText } from "./listen-history-output.js";
1
2
  import { localizeCommand } from "./guidance.js";
2
3
  function valueText(value) {
3
4
  if (typeof value === 'string')
@@ -21,6 +22,12 @@ export function humanData(data, id, command) {
21
22
  + `\n\nHelp: ${command} <command> --help\nJSON: ${command} commands --json\n`;
22
23
  }
23
24
  const record = data && typeof data === 'object' && !Array.isArray(data) ? data : null;
25
+ if (id === 'listen.history')
26
+ return historyText(data);
27
+ if (id === 'listen.show')
28
+ return detailText(data);
29
+ if (id === 'listen.resend')
30
+ return receiptText(data);
24
31
  if (id === 'whoami' && record) {
25
32
  return record.authenticated
26
33
  ? 'Logged in. Merchant verified.\n'
@@ -0,0 +1,29 @@
1
+ export function historyText({ records, listeners }) {
2
+ const deliveries = records.map(record => `${new Date(record.createdAt).toISOString()} ${record.status} ${record.eventType} attempts ${record.attempts.length} ${record.id}`);
3
+ const sessions = listeners.map(({ sessionId, events, expiresAt }) => `${sessionId} ${events.length ? events.join(', ') : 'All events'} expires ${new Date(expiresAt).toISOString()}`);
4
+ return `${deliveries.join('\n') || 'No captured deliveries.'}\n\nActive listeners\n${sessions.join('\n') || 'None.'}\n`;
5
+ }
6
+ export function detailText(data) {
7
+ const record = data.record;
8
+ const lines = [
9
+ `${record.eventType} ${record.status} ${new Date(record.createdAt).toISOString()}`,
10
+ `Record: ${record.id}`, `Event: ${record.eventId}`, `Listener: ${record.sessionId}`,
11
+ ];
12
+ if (record.replayOf)
13
+ lines.push(`Resent from: ${record.replayOf}`);
14
+ if (record.error)
15
+ lines.push(`Reason: ${record.error}`);
16
+ lines.push(`Attempts: ${record.attempts.length}`);
17
+ for (const attempt of record.attempts) {
18
+ const start = new Date(attempt.startedAt).toISOString();
19
+ const end = attempt.completedAt === undefined ? 'in progress' : new Date(attempt.completedAt).toISOString();
20
+ const status = attempt.httpStatus === undefined ? '' : `HTTP ${attempt.httpStatus}`;
21
+ lines.push([` ${attempt.attempt}. ${start} → ${end}`, status, attempt.error].filter(Boolean).join(' '));
22
+ }
23
+ if (data.output)
24
+ lines.push(`Exported: ${data.output.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')}`);
25
+ return lines.join('\n') + '\n';
26
+ }
27
+ export function receiptText(receipt) {
28
+ return `Queued for listener ${receipt.sessionId}\nRecord: ${receipt.recordId}\nEvent: ${receipt.eventId}\nDelivery: ${receipt.deliveryId}\n`;
29
+ }
@@ -3,8 +3,8 @@ export function renderListenEvent(event, meta, version, json) {
3
3
  if (json)
4
4
  return renderResult(successEnvelope({ data: event, meta }, version), true);
5
5
  if (event.type === 'ready')
6
- return `Listening in ${event.environment === 'prod' ? 'Production' : 'Test'} (${event.sessionId}). Press Ctrl+C to stop.\n`;
6
+ return `Listening in ${event.environment === 'prod' ? 'Production' : 'Test'} (${event.sessionId}). Press Ctrl+C to stop.\nLocal receiver verification key for this session:\n${event.signingPublicKey}`;
7
7
  if (event.type === 'delivery')
8
- return `${event.eventType} ${event.deliveryId} attempt ${event.attempt}: ${event.httpStatus ?? 'network failure'}\n`;
8
+ return `${event.eventType} ${event.eventId} (record ${event.recordId}, delivery ${event.deliveryId}) attempt ${event.attempt}: ${event.httpStatus ?? 'network failure'}\n`;
9
9
  return `Listener stopped. Cleanup ${event.cleanedUp ? 'confirmed' : 'unconfirmed'}.\n`;
10
10
  }
@@ -6,7 +6,7 @@ export function successEnvelope(result, cliVersion) {
6
6
  }
7
7
  export function failureEnvelope(error, cliVersion) {
8
8
  const failure = safeError(error);
9
- const context = Object.fromEntries(['merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'].filter(key => Object.hasOwn(failure.details, key)).map(key => [key, failure.details[key]]));
9
+ const context = Object.fromEntries(['merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'apiOrigin', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'].filter(key => Object.hasOwn(failure.details, key)).map(key => [key, failure.details[key]]));
10
10
  return { schemaVersion: 1, ok: false, data: null, error: { code: failure.code, message: failure.message, stage: failure.stage, recovery: failure.recovery, details: failure.details }, meta: { cliVersion, ...context, outcome: failure.outcome, operationId: failure.details.operationId ?? null, requestId: failure.details.requestId ?? null } };
11
11
  }
12
12
  function environmentHeading(meta) {
package/dist/cli/run.js CHANGED
@@ -57,6 +57,13 @@ export async function runCli(argv, version, execute) {
57
57
  parent = groups.get(parts[0]);
58
58
  }
59
59
  const command = configure(parent.command(parts.at(-1))).description(definition.description);
60
+ if (definition.id.startsWith('listen.')) {
61
+ command.configureHelp({ showGlobalOptions: true, visibleGlobalOptions: () => [
62
+ ...parent.options.filter(option => option.long === '--live'), ...root.options.filter(option => !option.hidden),
63
+ ] });
64
+ }
65
+ if (parts.length === 1)
66
+ groups.set(parts[0], command);
60
67
  if (definition.id === 'login')
61
68
  command.addHelpText('after', '\n' + credentialGuide('pancake'));
62
69
  if (definition.argument)
@@ -76,6 +83,9 @@ export async function runCli(argv, version, execute) {
76
83
  throw argumentError('Pagination requires whole non-negative numbers.');
77
84
  options[field] = Number(raw[field]);
78
85
  }
86
+ if (definition.id.startsWith('listen.') && (options.events !== undefined || options.forwardTo !== undefined)) {
87
+ throw argumentError('--forward-to and --events apply only when starting a listener.');
88
+ }
79
89
  if (interactive && definition.id === 'login' && (options.keyLogin || options.merchantId || options.privateKeyFile || options.key) && (!options.merchantId || (!options.privateKeyFile && !options.key))) {
80
90
  options = { ...options, ...await promptCredentials(options, commandName) };
81
91
  }
@@ -1,7 +1,14 @@
1
+ import { historyActions, listenerEndpoint } from "../contracts/listener-routes.js";
1
2
  import { productCreateEndpoint, webhookEndpoint } from "../contracts/action-routes.js";
2
3
  import { actionSpecs } from "./action-definitions.js";
3
4
  import { readSpecs } from "./read-definitions.js";
4
5
  export function commandApi(id) {
6
+ if (Object.hasOwn(historyActions, id)) {
7
+ const action = historyActions[id];
8
+ return { method: 'POST', endpoints: [...(action === 'replay' ? ['/v1/graphql'] : []), listenerEndpoint(action)],
9
+ authentication: 'merchant-session only', targetEnvironment: 'test by default; --live for prod', confirmationRequired: action === 'replay',
10
+ ...(action === 'detail' ? { privateOutput: 'Metadata on stdout; optional --output exports the original body to a new private file.' } : {}) };
11
+ }
5
12
  if (id === 'listen')
6
13
  return { method: 'POST', endpoints: ['/v1/graphql', ...['start', 'poll', 'ack', 'stop'].map(action => `/v1/actions/notification/cli-listen-${action}`)], authentication: 'merchant-session only', targetEnvironment: 'test by default; --live for prod', temporarySessionTtlSeconds: 90 };
7
14
  const action = actionSpecs.find(spec => spec.definition.id === id);
@@ -0,0 +1,14 @@
1
+ import { recordIdPattern } from "../contracts/listener-routes.js";
2
+ import { objectSchema } from "./schemas.js";
3
+ const recordArgument = objectSchema({ recordId: { type: 'string', pattern: recordIdPattern.source } }, ['recordId']);
4
+ export const listenHistoryDefinitions = [
5
+ { id: 'listen.history', path: 'listen history', description: 'List captured deliveries and active listeners for --store-id', effect: 'read',
6
+ schema: objectSchema({}), options: [['--limit <number>', 'Maximum records, 1–100 (default 20)']],
7
+ example: 'pancake listen history --store-id STO_abc --limit 10' },
8
+ { id: 'listen.show', path: 'listen show', description: 'Show delivery metadata and attempts for --store-id', effect: 'read',
9
+ argument: 'recordId', schema: recordArgument, options: [['--output <path>', 'Export the original payload and metadata to a new private JSON file']],
10
+ example: 'pancake listen show <recordId> --store-id STO_abc --output ./delivery.json' },
11
+ { id: 'listen.resend', path: 'listen resend', description: 'Enqueue a captured event for an active listener in --store-id', effect: 'write',
12
+ argument: 'recordId', schema: recordArgument, options: [['--session <uuid>', 'Owned active target listener (required)'], ['--idempotency-key <uuid>', 'Required replay UUID. Reuse for the same resend within 24 hours to recover its receipt.']],
13
+ example: 'pancake listen resend <recordId> --session <sessionId> --store-id STO_abc --yes --idempotency-key <uuid>' },
14
+ ];
@@ -1,12 +1,16 @@
1
1
  import { loopbackTarget } from "../contracts/loopback-target.js";
2
2
  import { argumentError } from "../contracts/errors.js";
3
- export function listenInput(options) {
3
+ export function listenerScope(options) {
4
4
  if (!options.storeId || !/^STO_[A-Za-z0-9]+$/.test(options.storeId))
5
5
  throw argumentError('Provide a valid --store-id.');
6
+ return { storeId: options.storeId, environment: options.live ? 'prod' : 'test' };
7
+ }
8
+ export function listenInput(options) {
9
+ const scope = listenerScope(options);
6
10
  const url = loopbackTarget(options.forwardTo);
7
11
  const events = options.events?.split(',');
8
12
  if (events && (events.length > 100 || events.some(event => !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(event)) || new Set(events).size !== events.length)) {
9
13
  throw argumentError('--events requires unique comma-separated event names.');
10
14
  }
11
- return { storeId: options.storeId, url, events, environment: options.live ? 'prod' : 'test' };
15
+ return { ...scope, url, events };
12
16
  }
@@ -0,0 +1,47 @@
1
+ import { Ajv } from 'ajv';
2
+ import { CliError } from "../contracts/errors.js";
3
+ import { eventIdPattern, eventTypePattern, recordIdPattern } from "../contracts/listener-routes.js";
4
+ import { objectSchema, uuid } from "./schemas.js";
5
+ const epoch = { type: 'integer', minimum: 0, maximum: 8640000000000000 };
6
+ const recordId = { type: 'string', pattern: recordIdPattern.source };
7
+ const eventId = { type: 'string', pattern: eventIdPattern.source };
8
+ const eventType = { type: 'string', pattern: eventTypePattern.source };
9
+ const reasons = ['HTTP_ERROR', 'LOCAL_FORWARD_FAILED', 'LEASE_EXPIRED', 'LISTENER_STOPPED', 'SESSION_EXPIRED',
10
+ 'RELAY_UNAVAILABLE', 'DELIVERY_FAILED', 'QUEUE_OVERFLOW', 'PAYLOAD_TOO_LARGE', 'SESSION_CAPACITY'];
11
+ const attempt = objectSchema({ attempt: { type: 'integer', minimum: 1, maximum: 3 }, startedAt: epoch, completedAt: epoch,
12
+ httpStatus: { type: 'integer', minimum: 100, maximum: 599 }, error: { enum: reasons } }, ['attempt', 'startedAt']);
13
+ const fields = { id: recordId, eventId, eventType, sessionId: uuid, environment: { enum: ['test', 'prod'] }, createdAt: epoch,
14
+ status: { enum: ['pending', 'delivering', 'succeeded', 'failed', 'stopped', 'expired'] }, attempts: { type: 'array', maxItems: 3, items: attempt } };
15
+ const record = { ...fields, replayOf: recordId, error: { enum: reasons } };
16
+ const listener = objectSchema({ sessionId: uuid, expiresAt: epoch, events: { type: 'array', maxItems: 100, items: eventType } }, ['sessionId', 'expiresAt', 'events']);
17
+ // Project only the documented response fields, including nested attempts and listeners.
18
+ const validator = new Ajv({ removeAdditional: true, ownProperties: true });
19
+ const isHistory = validator.compile(objectSchema({
20
+ records: { type: 'array', maxItems: 100, items: objectSchema(record, Object.keys(fields)) },
21
+ listeners: { type: 'array', maxItems: 10, items: listener }, retentionHours: { const: 24 }, maxRecords: { const: 100 },
22
+ }, ['records', 'listeners', 'retentionHours', 'maxRecords']));
23
+ const isDetail = validator.compile(objectSchema({
24
+ record: objectSchema({ ...record, body: { type: 'string', maxLength: 65536 }, contentType: { type: 'string', maxLength: 1024 } }, [...Object.keys(fields), 'body', 'contentType']),
25
+ }, ['record']));
26
+ const isReceipt = validator.compile(objectSchema({
27
+ accepted: { const: true }, recordId, deliveryId: { type: 'string', pattern: '^lrd_[0-9a-f]{40}$' }, eventId, sessionId: uuid,
28
+ }, ['accepted', 'recordId', 'deliveryId', 'eventId', 'sessionId']));
29
+ function invalidResponse() {
30
+ return new CliError('INVALID_RESPONSE', 'The listener API returned invalid delivery data.', { stage: 'listen' });
31
+ }
32
+ export function historyResult(data, environment, limit) {
33
+ if (!isHistory(data) || data.records.length > limit || data.records.some(item => item.environment !== environment))
34
+ throw invalidResponse();
35
+ return data;
36
+ }
37
+ export function detailResult(data, environment, id) {
38
+ if (!isDetail(data) || data.record.id !== id || data.record.environment !== environment
39
+ || Buffer.byteLength(data.record.body) > 65536 || !/^application\/json(?:; *charset=utf-8)?$/i.test(data.record.contentType))
40
+ throw invalidResponse();
41
+ return data;
42
+ }
43
+ export function replayReceipt(data, sessionId, sourceId) {
44
+ if (!isReceipt(data) || data.sessionId !== sessionId || data.recordId === sourceId)
45
+ throw invalidResponse();
46
+ return data;
47
+ }
@@ -86,7 +86,15 @@ export const readSpecs = [
86
86
  listSpec('merchants', 'merchants', fields('id', 'email', 'status', 'createdAt'), objectSchema({}), productDocs),
87
87
  getSpec('merchants', 'merchant', fields('id', 'email', 'status', 'createdAt', 'updatedAt'), merchantId, productDocs, 'MER_abc'),
88
88
  ...['graphql', 'analytics'].map(resource => ({
89
- definition: { id: `${resource}.query`, path: `${resource} query`, description: resource === 'analytics' ? 'Run a custom read-only analytics GraphQL document with explicit nested selections' : 'Run exactly one read-only GraphQL operation; fragments and variables are supported', effect: 'read', file: true, schema: querySchema, options: [previewOption, ['--output <path>', 'Export response to a new private file; required for arbitrary GraphQL']], example: `pancake ${resource} query --file query.json --dry-run --json` },
89
+ definition: {
90
+ id: `${resource}.query`, path: `${resource} query`, description: resource === 'analytics' ? 'Run a custom read-only analytics GraphQL document with explicit nested selections' : 'Run exactly one read-only GraphQL operation; fragments and variables are supported',
91
+ effect: 'read', file: true, schema: querySchema, options: [
92
+ previewOption,
93
+ ['--output <path>', 'Export response to a new private file; required for arbitrary GraphQL'],
94
+ ...(resource === 'graphql' ? [['--background', 'Run this read without adding a local operation record']] : []),
95
+ ],
96
+ example: `pancake ${resource} query --file query.json --dry-run --json`,
97
+ },
90
98
  sensitiveOutput: true, documentation: [`${docs}graphql/${resource === 'analytics' ? 'analytics' : 'overview'}`], request: (input) => readOnlyRequest(input),
91
99
  })),
92
100
  ];
@@ -1,3 +1,4 @@
1
+ import { listenHistoryDefinitions } from "./listen-definitions.js";
1
2
  import { actionSpecs } from "./action-definitions.js";
2
3
  import { readSpecs } from "./read-definitions.js";
3
4
  import { objectSchema, productSchema, storeId, string, webhookSchemas } from "./schemas.js";
@@ -11,7 +12,8 @@ export const globalOptions = [
11
12
  ];
12
13
  const paginationOptions = [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset (default 0)'], ['--fields <names>', 'Comma-separated top-level result fields']];
13
14
  export const definitions = [
14
- { id: 'listen', path: 'listen', description: 'Forward temporary merchant event deliveries to a loopback receiver', schema: noInput, effect: 'read', options: [['--forward-to <url>', 'HTTP(S) loopback receiver URL (required)'], ['--events <names>', 'Comma-separated event names'], ['--live', 'Explicitly listen in production; defaults to test']], example: 'pancake listen --store-id STO_abc --forward-to http://localhost:3000/webhook --json' },
15
+ { id: 'listen', path: 'listen', description: 'Forward temporary merchant event deliveries to a loopback receiver', schema: noInput, effect: 'read', options: [['--forward-to <url>', 'HTTP(S) loopback receiver URL (required)'], ['--events <names>', 'Comma-separated event names'], ['--live', 'Use Production; defaults to Test']], example: 'pancake listen --store-id STO_abc --forward-to http://localhost:3000/webhook --json' },
16
+ ...listenHistoryDefinitions,
15
17
  { id: 'commands', path: 'commands', description: 'List available commands (offline)', schema: noInput, effect: 'none', example: 'pancake commands --json' },
16
18
  { id: 'schema', path: 'schema', argument: 'command', description: 'Show command fields, output format and an example', schema: objectSchema({ command: string }, ['command']), effect: 'none', example: 'pancake schema webhook.add --json' },
17
19
  { id: 'login', path: 'login', description: 'Log in through your browser, or use an RSA key', schema: noInput, effect: 'local', options: [['--key-login', 'Enter an RSA key instead of opening a browser'], ['--api-url <origin>', 'Explicit API origin for browser login (HTTPS or local loopback)'], ['--dashboard-url <origin>', 'Explicit Dashboard origin for browser login (HTTPS or local loopback)'], ['--merchant-id <id>', 'Merchant ID for RSA login'], ['--private-key-file <path>', 'RSA private-key file path'], ['--key <value>', 'Auto-detect key or path; use the hidden prompt for secret contents']], example: 'pancake login --merchant-id MER_abc --private-key-file ./key.pem' },
@@ -37,9 +39,9 @@ export const definitions = [
37
39
  ...readSpecs.map(spec => spec.definition),
38
40
  ];
39
41
  export const outputContract = {
40
- streams: { listen: { format: 'ndjson', envelope: 'one standard envelope per event or error', eventTypes: ['ready', 'delivery', 'stopped'], eventId: 'Stable delivery ID identifies the same event across retries', authentication: 'browser session only', defaultEnvironment: 'test', production: '--live' } },
42
+ streams: { listen: { format: 'ndjson', envelope: 'one standard envelope per event or error', eventTypes: ['ready', 'delivery', 'stopped'], eventId: 'Original event ID is preserved across retries and resends', recordId: 'Use with listen show and listen resend', authentication: 'browser session only', defaultEnvironment: 'test', production: '--live' } },
41
43
  schemaVersion: 1, fields: ['schemaVersion', 'ok', 'data', 'error', 'meta'],
42
44
  errorFields: ['code', 'message', 'stage', 'recovery', 'details'],
43
- metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
45
+ metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'apiOrigin', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
44
46
  exitCodes: { success: 0, executionOrVerification: 1, argumentsOrConfiguration: 2, interrupted: 130 },
45
47
  };