@waffo/pancake-cli 0.0.1-rc.3 → 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.
- package/CHANGELOG.md +5 -0
- package/README.md +29 -12
- package/SKILL.md +6 -4
- package/dist/adapters/operations.js +60 -2
- package/dist/adapters/pancake/client.js +25 -13
- package/dist/adapters/pancake/listener-http-error.js +43 -0
- package/dist/application/diagnostics.js +2 -1
- package/dist/application/dispatch.js +6 -2
- package/dist/application/listen-history.js +41 -0
- package/dist/application/listen-resend.js +101 -0
- package/dist/application/listen.js +23 -18
- package/dist/application/listener-context.js +11 -0
- package/dist/application/listener-signature.js +24 -0
- package/dist/application/local.js +1 -1
- package/dist/cli/human-output.js +7 -0
- package/dist/cli/listen-history-output.js +29 -0
- package/dist/cli/listen-output.js +2 -2
- package/dist/cli/run.js +10 -0
- package/dist/commands/api-coverage.js +7 -0
- package/dist/commands/listen-definitions.js +14 -0
- package/dist/commands/listen-input.js +6 -2
- package/dist/commands/listen-response.js +47 -0
- package/dist/commands/registry.js +4 -2
- package/dist/contracts/listen-replay.js +20 -0
- package/dist/contracts/listener-protocol.js +12 -0
- package/dist/contracts/listener-routes.js +11 -0
- package/docs/api-coverage.md +6 -3
- package/docs/usage.md +47 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.0.1-rc.4
|
|
4
|
+
|
|
5
|
+
- Verify local deliveries and resends with a new RSA key for each listener session. The ready event includes the public PEM for the local receiver. The CLI requests protocol 2 at startup. Notify requires clients to declare support before creating a listener. The CLI reports older deployments before listening or submitting a replay.
|
|
6
|
+
- Add browser-session listener history, private payload export and confirmed resend to an active listener. Stream delivery records now include their history record ID and original event ID.
|
|
7
|
+
|
|
3
8
|
## 0.0.1-rc.3
|
|
4
9
|
|
|
5
10
|
Release candidate for npm’s `next` channel. No stable release.
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Developer CLI for Waffo Pancake, built with TypeScript, Node.js and Commander. The official TypeScript compiler builds the CLI.
|
|
4
4
|
|
|
5
|
-
**Release candidate
|
|
5
|
+
**Release candidate 0.0.1-rc.4 uses npm’s `next` channel.** It adds local webhook delivery history, replay and per-listener signatures. The CLI provides 65 commands covering merchant authentication, resource queries, 33 supported merchant API-Key REST action routes within the scope below, read-only GraphQL, offline previews, operation records and redacted diagnostics. Manage stores, products, subscription groups, checkout sessions, subscription cancellation, refund tickets, customer session tokens, notification recipients, content-safety checks, coupons, promotion codes and test webhooks. Temporary local webhook listening is available for browser sessions; event triggering is not implemented. This is separate from the Pancake migration CLI.
|
|
6
6
|
|
|
7
7
|
## Try locally without publishing
|
|
8
8
|
|
|
@@ -20,7 +20,7 @@ JSON
|
|
|
20
20
|
pnpm cli products create --type onetime --file product.json --dry-run --json
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.
|
|
23
|
+
See the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/usage.md) for input examples and safe operations, and the [API coverage matrix](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/api-coverage.md) for every command, endpoint and authentication boundary. `commands`, `schema` and supported `--dry-run` options work offline without credentials. Pipe output or use `--json` for one JSON envelope (`listen` streams NDJSON envelopes); debugging goes to stderr. Monetary amounts are decimal strings.
|
|
24
24
|
|
|
25
25
|
The agent reference is hosted on official Docs and identifies the release it documents; use the bundled `SKILL.md` for your installed CLI. Other documentation links serve the published npm package through jsDelivr; no GitHub access is needed. They are versioned snapshots, so later repository edits appear only in a new package release. The same Markdown guides ship in the package for offline reading. For a global npm installation, run `npm root -g` and open `@waffo/pancake-cli/docs/usage.md` under that directory. In a source checkout, open `docs/usage.md` directly.
|
|
26
26
|
|
|
@@ -81,13 +81,13 @@ Configuration uses version 2. Legacy version 1 is not migrated: run `logout`, th
|
|
|
81
81
|
|
|
82
82
|
## Install the release candidate
|
|
83
83
|
|
|
84
|
-
Version `0.0.1-rc.
|
|
84
|
+
Version `0.0.1-rc.4` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
|
|
85
85
|
|
|
86
86
|
```sh
|
|
87
87
|
npm install -g @waffo/pancake-cli@next
|
|
88
88
|
pancake --version
|
|
89
89
|
# Or run the exact candidate without a global installation:
|
|
90
|
-
npx @waffo/pancake-cli@0.0.1-rc.
|
|
90
|
+
npx @waffo/pancake-cli@0.0.1-rc.4 --help
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
For the hosted service, no URL overrides are needed:
|
|
@@ -108,7 +108,7 @@ pancake env test
|
|
|
108
108
|
pancake stores list
|
|
109
109
|
```
|
|
110
110
|
|
|
111
|
-
Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. Production browser login and listener startup, polling and cleanup
|
|
111
|
+
Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. An earlier candidate passed Production browser login and listener startup, polling and cleanup with its original listener signing scheme; real Production payment delivery remains pending. Automated Windows package checks pass; a real Windows console Ctrl+C listener walkthrough remains pending.
|
|
112
112
|
|
|
113
113
|
To update within the candidate channel, run `npm install -g @waffo/pancake-cli@next`. Stable Homebrew does not install prereleases.
|
|
114
114
|
|
|
@@ -182,9 +182,9 @@ Package smoke tests install the actual tarball in isolated directories and exerc
|
|
|
182
182
|
- Homebrew: CLI CI installs the tested package artifact on macOS/Linux using pinned public tap tooling, without publishing it. The [tap](https://github.com/waffo-com/homebrew-pancake) detects stable npm versions, verifies integrity and tests installation before updating.
|
|
183
183
|
- Weekly Dependabot updates cover dependencies and pinned Actions.
|
|
184
184
|
|
|
185
|
-
See the [agent reference](https://docs.waffo.ai/waffo-pancake-cli-skill) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.
|
|
185
|
+
See the [agent reference](https://docs.waffo.ai/waffo-pancake-cli-skill) and [changelog](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
|
|
186
186
|
|
|
187
|
-
Internal planning documents are maintained outside the source repository. The published `0.0.1-rc.1` candidate passed npm/npx installation checks and selected business operations in Test and Production. Production login and logout revocation
|
|
187
|
+
Internal planning documents are maintained outside the source repository. The published `0.0.1-rc.1` candidate passed npm/npx installation checks and selected business operations in Test and Production. Production login and logout revocation also passed. The original listener signing scheme passed Test sandbox-payment forwarding, signature verification, retry and cleanup. This is not blanket acceptance of every command: real Production payment delivery and actual Windows console Ctrl+C remain pending. Local tests use simulated API responses.
|
|
188
188
|
|
|
189
189
|
Using or contributing to this open-source client does not require private service source code. Remote commands require credentials and access to a compatible hosted API; browser login also requires a compatible Dashboard. Offline discovery and previews need neither service source nor a running API.
|
|
190
190
|
|
|
@@ -213,9 +213,9 @@ Overrides accept HTTPS, or HTTP on `127.0.0.1` only. No URL credentials, paths,
|
|
|
213
213
|
|
|
214
214
|
## Contributing and security
|
|
215
215
|
|
|
216
|
-
See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.
|
|
216
|
+
See [CONTRIBUTING.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/LICENSE).
|
|
217
217
|
|
|
218
|
-
Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.
|
|
218
|
+
Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). Offline previews show discount amounts or percentages, duration, product scope, redemption limits, coupon IDs and batch count/length. Customer email restrictions remain redacted, including inside nested promotion codes. See the Discounts section in the [usage guide](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.4/docs/usage.md). Gateway source permits browser sessions and RSA keys; merchant/store permissions still apply. Discount writes have response-only verification; the nine discount commands passed isolated Test-environment merchant acceptance, including final deactivation read-back. Selected coupon and promotion-code operations also passed Production acceptance; this does not establish coverage of every discount operation or full stable-release acceptance.
|
|
219
219
|
|
|
220
220
|
## Listen to merchant events locally
|
|
221
221
|
|
|
@@ -226,8 +226,25 @@ pnpm cli listen --store-id STO_example --forward-to http://localhost:3000/webhoo
|
|
|
226
226
|
|
|
227
227
|
Requires browser login and access to the store. Listening always starts in Test, even if your saved selection is Production. Use `--live` to explicitly listen in Production; this does not change your saved environment. Each API response must verify the requested environment. RSA credentials are unsupported. The receiver must use HTTP(S) on localhost, 127.0.0.1 or [::1]; redirects are not followed.
|
|
228
228
|
|
|
229
|
-
|
|
229
|
+
At startup the CLI prints an RSA public key for this listener session. Set your local receiver to verify each request with that key, including Production events received via `--live`. Update the receiver key every time you start a listener. Permanent webhook endpoints continue to use their configured platform keys. See the local verification example in `docs/usage.md`.
|
|
230
230
|
|
|
231
|
-
|
|
231
|
+
The CLI verifies the listener signature before forwarding the exact event body and the Content-Type, X-Waffo-Signature and X-Waffo-Event headers. Only 2xx succeeds. Network failures are reported as null. Delivery allows up to three attempts with the same event ID. Deduplicate by event ID. Event bodies and signatures stay out of CLI output.
|
|
232
232
|
|
|
233
|
-
|
|
233
|
+
With `--json` or piped stdout, `listen` emits one standard JSON envelope per line: `data.type` is `ready`, `delivery` or `stopped`, followed by an error envelope if listening fails. The ready event includes `data.listenerProtocol` (2) and `data.signingPublicKey` (PEM). Delivery metadata includes recordId, deliveryId, eventId, eventType, attempt and httpStatus. Ctrl+C and SIGTERM stop and clean up the session before exiting (130); cleanup failure exits nonzero and reports the 90-second expiry fallback. Abrupt process termination leaves only a temporary session that expires within 90 seconds of its last successful poll. No permanent webhook is changed. Listening requires separately deployed relay/gateway support.
|
|
234
|
+
|
|
235
|
+
During the upgrade to listener protocol 2, temporary listeners pause while permanent webhook endpoints continue delivering. If `pancake --version` shows `0.0.1-rc.2` or `0.0.1-rc.3`, starting a listener against the upgraded service returns HTTP 400 before creating a session. Those versions can display `INVALID_REQUEST` for that response. To upgrade to protocol 2, run `npm install -g @waffo/pancake-cli@next` and verify that `pancake --version` shows `0.0.1-rc.4`. Restart `pancake listen` and configure your local receiver with the new session’s public key.
|
|
236
|
+
|
|
237
|
+
The earlier published candidate passed Test sandbox-payment delivery and Production listener startup, polling, mode isolation and cleanup on the production deployment with its original signing scheme. Live Production payment delivery and production-deployment acceptance of protocol 2 are pending.
|
|
238
|
+
|
|
239
|
+
### Inspect and resend a captured delivery
|
|
240
|
+
|
|
241
|
+
Listener history and resend are available in this source checkout and require a compatible API deployment. Browser login is required. All listener commands default to Test. Pass `--live` for Production. History keeps the latest 100 captured deliveries for up to 24 hours per account, store and environment. It also lists your active listener sessions.
|
|
242
|
+
|
|
243
|
+
```sh
|
|
244
|
+
pancake listen history --store-id STO_example --limit 20
|
|
245
|
+
pancake listen show <recordId> --store-id STO_example
|
|
246
|
+
pancake listen show <recordId> --store-id STO_example --output ./delivery.json
|
|
247
|
+
pancake listen resend <recordId> --session <sessionId> --store-id STO_example --yes --idempotency-key <uuid>
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
Show prints metadata and attempts. A new private output file includes the original payload. Resend enqueues it for the selected active listener matching the event filter. The target listener signs the replay and preserves the original `eventId` for receiver deduplication. The receipt includes a fresh delivery ID and history record ID. It creates no payment and does not retry a permanent webhook. Production resend also requires `--confirm-production`. If admission is uncertain, repeat the exact command with the same UUID within 24 hours to recover the receipt.
|
package/SKILL.md
CHANGED
|
@@ -5,7 +5,7 @@ description: Discover and use the Waffo Pancake CLI for merchant API operations,
|
|
|
5
5
|
|
|
6
6
|
# Waffo Pancake CLI
|
|
7
7
|
|
|
8
|
-
Release candidate: `0.0.1-rc.
|
|
8
|
+
Release candidate: `0.0.1-rc.4`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.4`. In a source checkout, use `pnpm cli` after `pnpm install --frozen-lockfile && pnpm run build`. Runtime and development require Node.js >=22.14; Node.js 24 LTS is recommended for development. Use the pinned pnpm 11.25.0.
|
|
9
9
|
|
|
10
10
|
For UAT, pass team-provided `--dashboard-url <origin>` and `--api-url <origin>` to login; default URLs target production. Check `whoami` and select `env test` before UAT business operations. Package installation does not deploy compatible hosted services or prove production readiness.
|
|
11
11
|
|
|
@@ -53,7 +53,7 @@ Read the command schema to construct JSON files. `--file -` reads one JSON objec
|
|
|
53
53
|
|
|
54
54
|
## Expanded merchant coverage
|
|
55
55
|
|
|
56
|
-
There are
|
|
56
|
+
There are 65 registered commands and 33 supported merchant API-Key REST action routes. Run discovery for exact flags and schemas; do not invent `orders get`, `subscriptions get`, or group read commands. Resource lists cover products, versions, orders, subscriptions, payments, refunds, refund tickets, notification recipients and merchants. Product/order variants require `--type onetime|subscription` where documented. Read one page at a time; a full page means `hasMore:"unknown"`.
|
|
57
57
|
|
|
58
58
|
New actions manage stores, product updates/publication/status, subscription groups, checkout, merchant subscription cancellation, refund tickets, customer session tokens, notification recipients and content scans. Use `--file input.json`, `--dry-run`, explicit `--yes`, and preferably an explicit `--idempotency-key`. Without a key the CLI generates one and returns it. These actions use ID fields inside the input file, not invented positional arguments. Read each schema before constructing input.
|
|
59
59
|
|
|
@@ -103,10 +103,12 @@ Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create
|
|
|
103
103
|
|
|
104
104
|
## Temporary local listener
|
|
105
105
|
|
|
106
|
-
Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook [--events event.name] [--live] [--json]` for actual merchant events. Browser session only; Test default even when saved mode is Production; only explicit `--live` enables Production. `listen` is a streaming exception to one-result output: standard NDJSON envelopes with data.type ready/delivery/stopped, plus terminal failure when needed. Never expect event bodies or signatures in output. Forwarding is loopback-only, redirects fail, only 2xx is success. Stable eventId identifies duplicates/retries. SIGINT/SIGTERM stop the session; abrupt termination uses the 90-second TTL. No permanent endpoint mutation or synthetic trigger.
|
|
106
|
+
Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook [--events event.name] [--live] [--json]` for actual merchant events. Browser session only; Test default even when saved mode is Production; only explicit `--live` enables Production. `listen` is a streaming exception to one-result output: standard NDJSON envelopes with data.type ready/delivery/stopped, plus terminal failure when needed. Read `data.signingPublicKey` (PEM) from the protocol 2 ready event. Use that key only for this session's local receiver, including `--live` and resends. Refresh it whenever the listener restarts. Never expect event bodies or signatures in output. Forwarding is loopback-only, redirects fail, only 2xx is success. Stable eventId identifies duplicates/retries. SIGINT/SIGTERM stop the session; abrupt termination uses the 90-second TTL. No permanent endpoint mutation or synthetic trigger.
|
|
107
107
|
|
|
108
108
|
## Service and verification boundaries
|
|
109
109
|
|
|
110
|
-
Private service source is not required to use or develop the open-source client. Remote commands require credentials and a reachable compatible hosted API; browser authorization also needs a compatible Dashboard.
|
|
110
|
+
Private service source is not required to use or develop the open-source client. Remote commands require credentials and a reachable compatible hosted API; browser authorization also needs a compatible Dashboard. For listener protocol 2, shift all listener traffic to upgraded Notify first, then deploy Resource, Auth, Dashboard and finally the npm CLI. The published candidate passed npm/npx installation, production browser login and logout revocation, selected business operations in Test and Production, and Test sandbox-payment forwarding. The original signing scheme passed Production listener startup, polling, isolation and cleanup; real Production payment delivery and actual Windows console Ctrl+C remain pending. These checks do not establish acceptance of every command.
|
|
111
111
|
|
|
112
112
|
Browser login grants supported business operations in Test and Production within existing merchant/store permissions. Server policy denies account, API Key, payout/bank, other-device, further authorization and API credential, Webhook `secret` and identity-document access. No `--scope` option is needed. Use `logout` only for the current CLI session. RSA permissions are unchanged. Webhook addresses remain readable. Browser secret writes use server acknowledgement (`verification: response_only`); do not claim the secret was read back.
|
|
113
|
+
|
|
114
|
+
Use `listen history --store-id <store>` for captured metadata and active sessions. `listen show <recordId> --store-id <store>` prints attempts. Add `--output <new-file>` only when the original payload is needed. To enqueue the event for an active listener, use `listen resend <recordId> --store-id <store> --session <uuid> --yes --idempotency-key <uuid>`. Production requires `--live --confirm-production`. The CLI checks protocol 2 support using a read-only history request before enqueueing a replay. If an upgrade is required, update the listener services. Explicit recovery repeats the same command and UUID within 24 hours. Resend preserves eventId for receiver deduplication.
|
|
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
|
|
|
2
2
|
import { readdir, unlink } from 'node:fs/promises';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { atomicJson, hasCode, readJson, protectDirectory, privateDirectory, withDirectoryLock } from "./files.js";
|
|
5
|
+
import { requireReplayWindow, sameReplayIntent } from "../contracts/listen-replay.js";
|
|
5
6
|
import { argumentError, CliError } from "../contracts/errors.js";
|
|
6
7
|
export function inputFingerprint(input) {
|
|
7
8
|
const canonical = (value) => {
|
|
@@ -53,11 +54,23 @@ export class OperationStore {
|
|
|
53
54
|
}
|
|
54
55
|
async list(limit = 20) { return (await this.all()).slice(0, limit); }
|
|
55
56
|
async begin(input) {
|
|
57
|
+
return this.reserve(input);
|
|
58
|
+
}
|
|
59
|
+
async beginListenReplay(input) {
|
|
60
|
+
return this.reserve(input, true);
|
|
61
|
+
}
|
|
62
|
+
async reserve(input, recoverReplay = false) {
|
|
56
63
|
await privateDirectory(this.root);
|
|
57
64
|
return withDirectoryLock(this.directory, async () => {
|
|
58
65
|
const records = await this.all();
|
|
59
66
|
if (input.idempotencyKey) {
|
|
60
|
-
const
|
|
67
|
+
const key = input.idempotencyKey;
|
|
68
|
+
const existing = records.find(record => record.idempotencyKey === key
|
|
69
|
+
|| ((recoverReplay || record.command === 'listen.resend') && record.idempotencyKey?.toLowerCase() === key.toLowerCase()));
|
|
70
|
+
if (existing && recoverReplay && sameReplayIntent(existing, input)) {
|
|
71
|
+
requireReplayWindow(existing);
|
|
72
|
+
return existing;
|
|
73
|
+
}
|
|
61
74
|
if (existing)
|
|
62
75
|
throw new CliError('OPERATION_EXISTS', 'This idempotency key already has a local operation. It will not be replayed.', { details: { operationId: existing.operationId }, recovery: 'Inspect operations show, then query the remote resource. Do not create a new key to retry an unknown result.' });
|
|
63
76
|
}
|
|
@@ -72,15 +85,60 @@ export class OperationStore {
|
|
|
72
85
|
await unlink(join(this.directory, `${record.operationId}.json`));
|
|
73
86
|
if (retained.length - rotated.length >= 1000)
|
|
74
87
|
throw new CliError('OPERATION_STORAGE_FULL', 'Operation storage reached 1000 records; unresolved records are retained.', { recovery: 'Export needed diagnostics and resolve pending operations before explicitly archiving local records.' });
|
|
75
|
-
const record = { operationRecordVersion: 1, operationId: randomUUID(), ...input, startedAt: new Date().toISOString(), outcome: 'unknown', attempts: [] };
|
|
88
|
+
const record = { operationRecordVersion: 1, operationId: randomUUID(), ...input, startedAt: new Date().toISOString(), outcome: 'unknown', attempts: [], ...(recoverReplay ? { unconfirmedReplaySubmissions: 0 } : {}) };
|
|
76
89
|
await atomicJson(join(this.directory, `${record.operationId}.json`), record);
|
|
77
90
|
return record;
|
|
78
91
|
});
|
|
79
92
|
}
|
|
93
|
+
async updateListenReplay(id, event) {
|
|
94
|
+
await protectDirectory(this.root);
|
|
95
|
+
return withDirectoryLock(this.directory, async () => {
|
|
96
|
+
const record = await this.readRecord(id);
|
|
97
|
+
if (record.command !== 'listen.resend')
|
|
98
|
+
throw argumentError('A listener replay operation is required.');
|
|
99
|
+
if (event.kind === 'submitting')
|
|
100
|
+
requireReplayWindow(record);
|
|
101
|
+
if (record.outcome === 'completed')
|
|
102
|
+
return record;
|
|
103
|
+
// A retained unknown operation without a counter may already have reached the server.
|
|
104
|
+
const pending = record.unconfirmedReplaySubmissions ?? (record.outcome === 'unknown' ? 1 : 0);
|
|
105
|
+
if (event.kind === 'submitting') {
|
|
106
|
+
record.unconfirmedReplaySubmissions = pending + 1;
|
|
107
|
+
record.outcome = 'unknown';
|
|
108
|
+
delete record.finishedAt;
|
|
109
|
+
if (pending === 0)
|
|
110
|
+
delete record.errorCode;
|
|
111
|
+
}
|
|
112
|
+
else if (event.kind === 'accepted') {
|
|
113
|
+
record.unconfirmedReplaySubmissions = 0;
|
|
114
|
+
record.outcome = 'completed';
|
|
115
|
+
record.resourceId = event.resourceId;
|
|
116
|
+
record.attempts = event.attempts;
|
|
117
|
+
record.finishedAt = new Date().toISOString();
|
|
118
|
+
delete record.errorCode;
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
const outstanding = event.kind === 'rejected' ? pending - 1 : pending;
|
|
122
|
+
if (outstanding < 0)
|
|
123
|
+
throw new CliError('INVALID_CONFIG', 'The replay has no matching local submission.');
|
|
124
|
+
record.unconfirmedReplaySubmissions = outstanding;
|
|
125
|
+
record.outcome = outstanding > 0 ? 'unknown' : 'rejected';
|
|
126
|
+
if (outstanding === 0 || event.kind === 'uncertain') {
|
|
127
|
+
record.attempts = event.attempts;
|
|
128
|
+
record.errorCode = event.errorCode;
|
|
129
|
+
record.finishedAt = new Date().toISOString();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await atomicJson(join(this.directory, `${id}.json`), record);
|
|
133
|
+
return record;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
80
136
|
async finish(id, patch) {
|
|
81
137
|
await protectDirectory(this.root);
|
|
82
138
|
return withDirectoryLock(this.directory, async () => {
|
|
83
139
|
const previous = await this.readRecord(id);
|
|
140
|
+
if (previous.command === 'listen.resend')
|
|
141
|
+
throw argumentError('Use the listener replay journal for this operation.');
|
|
84
142
|
const record = { ...previous, outcome: patch.outcome, finishedAt: new Date().toISOString(), ...(patch.resourceId ? { resourceId: patch.resourceId } : {}), ...(patch.errorCode ? { errorCode: patch.errorCode } : {}), attempts: patch.attempts ?? previous.attempts };
|
|
85
143
|
await atomicJson(join(this.directory, `${id}.json`), record);
|
|
86
144
|
return record;
|
|
@@ -2,11 +2,13 @@ import { createHash, createPrivateKey, randomUUID, sign } from 'node:crypto';
|
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
3
|
import { DEFAULT_API_ORIGIN, productCreateEndpoint, serviceOrigin, webhookEndpoint } from "../../contracts/action-routes.js";
|
|
4
4
|
import { CliError } from "../../contracts/errors.js";
|
|
5
|
+
import { listenerEndpoint } from "../../contracts/listener-routes.js";
|
|
5
6
|
import { readPrivateKey } from "../files.js";
|
|
6
7
|
import { ME_QUERY, PRODUCT_QUERIES, STORES_QUERY, WEBHOOKS_QUERY, WEBHOOK_SECRETS_QUERY } from "./queries.js";
|
|
7
8
|
import { graphqlValidationError } from "./graphql-errors.js";
|
|
8
9
|
import { conflictError } from "./conflict-error.js";
|
|
9
10
|
import { httpErrorReason } from "./http-error-reason.js";
|
|
11
|
+
import { listenerHttpError } from "./listener-http-error.js";
|
|
10
12
|
import { parseRetryAfter } from "./retry-after.js";
|
|
11
13
|
export function parsePrivateKey(raw) {
|
|
12
14
|
let value = raw.trim().replace(/\\n/g, '\n');
|
|
@@ -56,8 +58,8 @@ async function responseJson(response, maximumBytes = 2 * 1024 * 1024) {
|
|
|
56
58
|
throw new Error('Invalid response');
|
|
57
59
|
return parsed;
|
|
58
60
|
}
|
|
59
|
-
function requestId(response) {
|
|
60
|
-
const value = response.headers.get('x-request-id') ?? response.headers.get('x-context-request-id');
|
|
61
|
+
function requestId(response, listener = false) {
|
|
62
|
+
const value = response.headers.get('x-request-id') ?? (listener ? null : response.headers.get('x-context-request-id'));
|
|
61
63
|
return value && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : undefined;
|
|
62
64
|
}
|
|
63
65
|
export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
@@ -70,7 +72,9 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
70
72
|
const key = credentials.sessionToken ? undefined : parsePrivateKey(raw);
|
|
71
73
|
async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, options = {}) {
|
|
72
74
|
const serialized = JSON.stringify(body);
|
|
73
|
-
const write = idempotencyKey !== undefined || options.singleAttempt === true;
|
|
75
|
+
const write = idempotencyKey !== undefined || options.singleAttempt === true || (options.listenerAction !== undefined && !['history', 'detail'].includes(options.listenerAction));
|
|
76
|
+
const listenerRequest = options.listenerAction !== undefined || options.listenerIdentity === true;
|
|
77
|
+
const retryRead = !write && !listenerRequest;
|
|
74
78
|
const deadline = Date.now() + 20000;
|
|
75
79
|
for (let index = 0;; index++) {
|
|
76
80
|
const started = Date.now(), timestamp = Math.floor(started / 1000).toString();
|
|
@@ -84,7 +88,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
84
88
|
try {
|
|
85
89
|
response = await fetchImpl(`${apiUrl}${path}`, { method: 'POST', headers, body: serialized, redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(Math.max(1, Math.min(15000, deadline - Date.now()))) });
|
|
86
90
|
attempt.status = response.status;
|
|
87
|
-
attempt.requestId = requestId(response);
|
|
91
|
+
attempt.requestId = requestId(response, listenerRequest);
|
|
88
92
|
const environment = response.headers.get('x-waffo-environment');
|
|
89
93
|
if (environment === 'test' || environment === 'prod')
|
|
90
94
|
attempt.environment = environment;
|
|
@@ -98,7 +102,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
98
102
|
catch {
|
|
99
103
|
attempt.durationMs = Date.now() - started;
|
|
100
104
|
observer(attempt);
|
|
101
|
-
if (!signal?.aborted &&
|
|
105
|
+
if (!signal?.aborted && retryRead && index < 2 && Date.now() + 100 < deadline) {
|
|
102
106
|
await delay(50 * (index + 1));
|
|
103
107
|
continue;
|
|
104
108
|
}
|
|
@@ -113,10 +117,20 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
113
117
|
const retryHeader = response.headers.get('retry-after');
|
|
114
118
|
const retryAfterMs = retryHeader ? parseRetryAfter(retryHeader) : undefined;
|
|
115
119
|
const retryMs = retryHeader ? retryAfterMs : 100 * (index + 1);
|
|
116
|
-
if (!signal?.aborted &&
|
|
120
|
+
if (!signal?.aborted && retryRead && retryable && index < 2 && retryMs !== undefined && Date.now() + retryMs < deadline) {
|
|
117
121
|
await delay(retryMs);
|
|
118
122
|
continue;
|
|
119
123
|
}
|
|
124
|
+
if (listenerRequest) {
|
|
125
|
+
const conflict = response.status === 409 && envelope.data === null && Array.isArray(envelope.errors)
|
|
126
|
+
&& envelope.errors.some(error => error?.layer === 'notification' && typeof error.message === 'string');
|
|
127
|
+
const failure = conflict
|
|
128
|
+
? new CliError('CONFLICT', 'The listener request conflicts with the current session or replay ID.', { stage: 'listen', details: { status: 409 } })
|
|
129
|
+
: apiError(response.status, write, undefined, attempt.requestId, Boolean(credentials.sessionToken));
|
|
130
|
+
if (options.listenerAction)
|
|
131
|
+
throw listenerHttpError(options.listenerAction, response, envelope, credentials.environment, failure);
|
|
132
|
+
throw failure;
|
|
133
|
+
}
|
|
120
134
|
if (response.status === 409) {
|
|
121
135
|
const conflict = conflictError(envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
|
|
122
136
|
if (conflict)
|
|
@@ -127,7 +141,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
127
141
|
throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken), retryHint);
|
|
128
142
|
}
|
|
129
143
|
if (Array.isArray(envelope.errors) && envelope.errors.length > 0) {
|
|
130
|
-
if (!write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
|
|
144
|
+
if (!listenerRequest && !write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
|
|
131
145
|
throw graphqlValidationError(envelope.errors, body.query) ?? apiError(response.status, write);
|
|
132
146
|
}
|
|
133
147
|
throw apiError(response.status, write);
|
|
@@ -185,13 +199,11 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
185
199
|
}
|
|
186
200
|
},
|
|
187
201
|
async listen(action, body, signal) {
|
|
188
|
-
if (!['start', 'poll', 'ack', 'stop'].includes(action))
|
|
189
|
-
throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
|
|
190
202
|
try {
|
|
191
|
-
return (await post(
|
|
203
|
+
return (await post(listenerEndpoint(action), body, undefined, false, signal, { listenerAction: action })).data;
|
|
192
204
|
}
|
|
193
205
|
catch (error) {
|
|
194
|
-
if (error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
|
|
206
|
+
if (action !== 'replay' && error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
|
|
195
207
|
throw new CliError('OUTCOME_UNKNOWN', 'The temporary listener request result is unknown.', { stage: 'listen', outcome: 'unknown', recovery: 'The CLI attempts session cleanup when the session ID is known. Otherwise the session expires within 90 seconds without polling.' });
|
|
196
208
|
throw error;
|
|
197
209
|
}
|
|
@@ -201,8 +213,8 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
201
213
|
throw new CliError('INVALID_ARGUMENT', 'Invalid action endpoint.', { exitCode: 2 });
|
|
202
214
|
return (await post(path, body, key, acknowledgementOnly)).data;
|
|
203
215
|
},
|
|
204
|
-
async me(signal) {
|
|
205
|
-
const { data, environment } = await post('/v1/graphql', { query: ME_QUERY, variables: {} }, undefined, false, signal);
|
|
216
|
+
async me(signal, options) {
|
|
217
|
+
const { data, environment } = await post('/v1/graphql', { query: ME_QUERY, variables: {} }, undefined, false, signal, { listenerIdentity: options?.listener });
|
|
206
218
|
const me = data.me;
|
|
207
219
|
if (!me || me.id !== credentials.merchantId)
|
|
208
220
|
throw new CliError('AUTH_FAILED', 'The authenticated merchant could not be verified.', { stage: 'identity' });
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { CliError } from "../../contracts/errors.js";
|
|
2
|
+
import { listenerUpgradeCode, listenerUpgradeRequired } from "../../contracts/listener-protocol.js";
|
|
3
|
+
import { ConfirmedReplayRejection } from "../../contracts/listen-replay.js";
|
|
4
|
+
const gatewayDenials = new Map([
|
|
5
|
+
[401, 'The gateway did not accept your login. Run pancake login again.'],
|
|
6
|
+
[403, 'The gateway denied access to this listener. Check your store permissions.'],
|
|
7
|
+
[429, 'The gateway rate limit was reached. Wait before resending.'],
|
|
8
|
+
]);
|
|
9
|
+
function listenerDenial(envelope) {
|
|
10
|
+
if (envelope.data !== null || !Array.isArray(envelope.errors) || envelope.errors.length !== 1)
|
|
11
|
+
return;
|
|
12
|
+
const [error] = envelope.errors;
|
|
13
|
+
if (!error || typeof error.message !== 'string' || !error.message.trim())
|
|
14
|
+
return;
|
|
15
|
+
if (error.layer === 'gateway' || error.layer === 'notification')
|
|
16
|
+
return { layer: error.layer, message: error.message, code: error.code };
|
|
17
|
+
}
|
|
18
|
+
export function listenerHttpError(action, response, envelope, selectedEnvironment, failure) {
|
|
19
|
+
const contentType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
|
|
20
|
+
const denial = contentType === 'application/json' ? listenerDenial(envelope) : undefined;
|
|
21
|
+
const layer = denial?.layer;
|
|
22
|
+
const responseEnvironment = response.headers.get('x-waffo-environment');
|
|
23
|
+
const verified = selectedEnvironment !== undefined && responseEnvironment === selectedEnvironment;
|
|
24
|
+
// The gateway emits this exact envelope before selecting an environment or proxying a missing route.
|
|
25
|
+
if (response.status === 404 && responseEnvironment === null && denial?.layer === 'gateway' && denial.message === 'Route not found') {
|
|
26
|
+
const upgrade = listenerUpgradeRequired();
|
|
27
|
+
return action === 'replay' ? new ConfirmedReplayRejection(upgrade.code, upgrade.message, upgrade) : upgrade;
|
|
28
|
+
}
|
|
29
|
+
if (verified && response.status === 503 && denial?.layer === 'notification' && denial.code === listenerUpgradeCode) {
|
|
30
|
+
// A mixed deployment can discover an incompatible reply after forwarding a write.
|
|
31
|
+
return listenerUpgradeRequired();
|
|
32
|
+
}
|
|
33
|
+
if (action !== 'replay')
|
|
34
|
+
return failure;
|
|
35
|
+
// Authentication, store authorization and rate limiting can deny a request before routing to its environment.
|
|
36
|
+
const gatewayMessage = layer === 'gateway' ? gatewayDenials.get(response.status) : undefined;
|
|
37
|
+
const preProxyDenial = responseEnvironment === null && gatewayMessage !== undefined;
|
|
38
|
+
const supportedStatus = [400, 401, 403, 409, 413, 429].includes(response.status) || (response.status === 404 && layer === 'notification');
|
|
39
|
+
if (supportedStatus && layer && (verified || preProxyDenial) && failure.outcome === 'rejected') {
|
|
40
|
+
return new ConfirmedReplayRejection(failure.code, gatewayMessage ?? failure.message, failure);
|
|
41
|
+
}
|
|
42
|
+
return new CliError('OUTCOME_UNKNOWN', 'Listener replay admission could not be confirmed.', { stage: 'listen', outcome: 'unknown' });
|
|
43
|
+
}
|
|
@@ -6,7 +6,8 @@ export function diagnosticRecord(record) {
|
|
|
6
6
|
command: record.command, impact: record.impact, cliVersion: record.cliVersion, startedAt: record.startedAt,
|
|
7
7
|
finishedAt: record.finishedAt, outcome: record.outcome, merchantId: record.merchantId,
|
|
8
8
|
storeId: record.storeId, inputHash: record.inputHash, idempotencyKey: record.idempotencyKey,
|
|
9
|
-
targetResourceId: record.targetResourceId, endpoint: record.endpoint, apiOrigin: record.apiOrigin, selectedEnvironment: record.selectedEnvironment,
|
|
9
|
+
targetResourceId: record.targetResourceId, targetSessionId: record.targetSessionId, endpoint: record.endpoint, apiOrigin: record.apiOrigin, selectedEnvironment: record.selectedEnvironment,
|
|
10
|
+
...(record.unconfirmedReplaySubmissions === undefined ? {} : { unconfirmedReplaySubmissions: record.unconfirmedReplaySubmissions }),
|
|
10
11
|
resourceId: record.resourceId, errorCode: record.errorCode,
|
|
11
12
|
attempts: record.attempts.map(attempt => ({ attemptId: attempt.attemptId, endpoint: attempt.endpoint, durationMs: attempt.durationMs, status: attempt.status, requestId: attempt.requestId, environment: attempt.environment })),
|
|
12
13
|
};
|
|
@@ -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' ||
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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)' :
|
|
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),
|
package/dist/cli/human-output.js
CHANGED
|
@@ -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
|
}
|
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
|
|
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 {
|
|
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
|
+
}
|
|
@@ -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', '
|
|
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,7 +39,7 @@ 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: '
|
|
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
45
|
metaFields: ['cliVersion', 'outcome', 'operationId', 'requestId', 'merchantId', 'source', 'actualEnvironment', 'environmentVerified', 'apiOrigin', 'impact', 'impactPolicy', 'requiresProductionConfirmation', 'requiresSharedConfirmation'],
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CliError } from "./errors.js";
|
|
2
|
+
/** The replay transport received positive evidence that this submission was denied. */
|
|
3
|
+
export class ConfirmedReplayRejection extends CliError {
|
|
4
|
+
}
|
|
5
|
+
export const replayWindowMs = 24 * 60 * 60 * 1000;
|
|
6
|
+
export function requireReplayWindow({ startedAt, operationId, outcome }) {
|
|
7
|
+
const age = Date.now() - Date.parse(startedAt);
|
|
8
|
+
if (!(age >= 0 && age < replayWindowMs)) {
|
|
9
|
+
throw new CliError('REPLAY_WINDOW_EXPIRED', 'The 24-hour recovery window for this replay ID has ended.', {
|
|
10
|
+
outcome, details: { operationId }, recovery: 'Inspect the local operation and retained listener history before starting another resend.',
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function sameReplayIntent(saved, requested) {
|
|
15
|
+
return requested.command === 'listen.resend' && saved.command === requested.command
|
|
16
|
+
&& saved.merchantId === requested.merchantId && saved.apiOrigin === requested.apiOrigin
|
|
17
|
+
&& saved.selectedEnvironment === requested.selectedEnvironment && saved.storeId === requested.storeId
|
|
18
|
+
&& saved.targetResourceId === requested.targetResourceId && saved.targetSessionId === requested.targetSessionId
|
|
19
|
+
&& saved.inputHash === requested.inputHash;
|
|
20
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { CliError } from "./errors.js";
|
|
2
|
+
export const listenerProtocol = 2;
|
|
3
|
+
export const listenerUpgradeCode = 'LISTENER_UPGRADE_REQUIRED';
|
|
4
|
+
export function listenerUpgradeRequired() {
|
|
5
|
+
return new CliError(listenerUpgradeCode, 'This CLI requires listener protocol 2 for locally signed deliveries.', {
|
|
6
|
+
stage: 'listen', recovery: 'Use a compatible CLI and ask the service operator to upgrade the listener services.',
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
export function requireListenerProtocol(response) {
|
|
10
|
+
if (response.listenerProtocol !== listenerProtocol)
|
|
11
|
+
throw listenerUpgradeRequired();
|
|
12
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { CliError } from "./errors.js";
|
|
2
|
+
export const historyActions = { 'listen.history': 'history', 'listen.show': 'detail', 'listen.resend': 'replay' };
|
|
3
|
+
export function listenerEndpoint(action) {
|
|
4
|
+
if (!['start', 'poll', 'ack', 'stop', ...Object.values(historyActions)].includes(action)) {
|
|
5
|
+
throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
|
|
6
|
+
}
|
|
7
|
+
return `/v1/actions/notification/cli-listen-${action}`;
|
|
8
|
+
}
|
|
9
|
+
export const recordIdPattern = /^lhr_[0-9a-f]{40}$/;
|
|
10
|
+
export const eventIdPattern = /^[^\x00-\x1f\x7f-\x9f]{1,160}$/u;
|
|
11
|
+
export const eventTypePattern = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
|
package/docs/api-coverage.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 商户 API 覆盖矩阵
|
|
2
2
|
|
|
3
|
-
折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。
|
|
3
|
+
折扣契约核对日期:2026-11-03;其余文档快照:2026-10-26。0.0.1-rc.4 新增监听记录、详情和重发 3 条命令。**65 条命令,覆盖 33 个商户 API-Key REST action 路由**。此处“覆盖”指已提供命令入口,不表示全部字段、客户身份接口或真实商户验收完成。
|
|
4
4
|
|
|
5
5
|
本地前缀为 `pnpm cli`;安装后的命令前缀为 `pancake`;`pnpm dev` 只负责自动构建。下表商户业务 REST Actions 远端执行必须 `--yes`,新增 Actions 使用 `--file`,支持 `--idempotency-key`(未给时生成);建议显式传 key 并保留操作编号。输入以 `schema <命令 ID>` 为准。
|
|
6
6
|
|
|
@@ -48,12 +48,15 @@
|
|
|
48
48
|
|
|
49
49
|
CLI 支持商户 Session 和 RSA API Key,具体路由仍由服务端鉴权;`sessions create` 仍需要 RSA API Key。`content scan` 是无状态读取判定,但采用同样的确认、持久化记录和单次 POST 策略。新增 Actions 的响应校验不证明资源被回读。`sessions create` 只签发客户 Token,不改变 CLI 登录。
|
|
50
50
|
|
|
51
|
-
## 全部
|
|
51
|
+
## 全部 65 条命令
|
|
52
52
|
|
|
53
53
|
此表直接按注册表排列。下列选项为命令专属;全局选项有 `--json`、`--no-interactive`、`--store-id`、`--yes`、`--confirm-production`、`--confirm-shared`、`--debug`,不代表每条命令都会使用每个选项。表中 `--file` 是否必需、字段及选择器规则以 schema 为准。
|
|
54
54
|
|
|
55
55
|
| 命令 | 参数与专属选项 | API / 本地行为 |
|
|
56
56
|
| --- | --- | --- |
|
|
57
|
+
| `pnpm cli listen history` | `--store-id`, `--limit`, `--live` | POST `/v1/actions/notification/cli-listen-history`,列出记录和活跃监听会话 |
|
|
58
|
+
| `pnpm cli listen show <recordId>` | `--store-id`, `--output`, `--live` | POST `/v1/actions/notification/cli-listen-detail`,原始正文仅导出到新的私有文件 |
|
|
59
|
+
| `pnpm cli listen resend <recordId>` | `--store-id`, `--session`, `--yes`, `--idempotency-key`, 生产环境加 `--live --confirm-production` | 先通过身份验证并读取 history 确认协议版本,再 POST `/v1/actions/notification/cli-listen-replay`,入队后返回回执 |
|
|
57
60
|
| `pnpm cli listen` | `--forward-to <url>`, `--events <names>`, `--live` | `/v1/graphql` 与 4 个临时监听路由;仅浏览器会话 |
|
|
58
61
|
| `pnpm cli commands` | — | 本地;不调用业务 API |
|
|
59
62
|
| `pnpm cli schema` | `<command>` | 本地;不调用业务 API |
|
|
@@ -149,6 +152,6 @@ CLI 支持商户 Session 和 RSA API Key,具体路由仍由服务端鉴权;`
|
|
|
149
152
|
|
|
150
153
|
### Temporary event listener
|
|
151
154
|
|
|
152
|
-
`listen` verifies identity with `/v1/graphql`, then uses POST `/v1/actions/notification/cli-listen-start`, `cli-listen-poll`, `cli-listen-ack` and `cli-listen-stop`. All require merchant browser-session authorization and store access; RSA is unsupported. Test is default; production requires `--live`. Start/ACK are never retried automatically. Session TTL is 90 seconds, polling interval three seconds, delivery lease 30 seconds and maximum attempts three. No permanent webhook writes or event trigger routes are used.
|
|
155
|
+
`listen` verifies identity with `/v1/graphql`, then uses POST `/v1/actions/notification/cli-listen-start`, `cli-listen-poll`, `cli-listen-ack` and `cli-listen-stop`. All require merchant browser-session authorization and store access; RSA is unsupported. Test is default; production requires `--live`. Start/ACK are never retried automatically. Session TTL is 90 seconds, polling interval three seconds, delivery lease 30 seconds and maximum attempts three. No permanent webhook writes or event trigger routes are used. The seven browser-session-only listener routes and the three device-login routes are separate from the 33 merchant API-Key REST action routes above. The CLI sends `listenerProtocol: 2` in the public start request. Notify requires this field before creating a listener. Protocol 2 returns a dedicated public PEM in the start response, signs each delivery with the target session's private key and marks history, detail and replay responses with the supported protocol. The CLI verifies the signature before forwarding. Clients on the published `0.0.1-rc.2` and `0.0.1-rc.3` can receive `INVALID_REQUEST` when they try to start a listener against the upgraded service. For protocol 2, follow the [listener upgrade steps](usage.md#upgrade-a-listener-to-protocol-2). On the earlier listener protocol, Production listener startup, polling, mode isolation and cleanup passed with the published candidate; real Production payment delivery remains pending.
|
|
153
156
|
|
|
154
157
|
Browser sessions use the server-enforced CLI business permission preset in Test and Production. Existing merchant/store access still applies. Unlisted routes and GraphQL fields, Webhook `secret` fields, account/API Key/payout/bank operations and other-session management are denied. Own-session logout is allowed. RSA permissions are unchanged.
|
package/docs/usage.md
CHANGED
|
@@ -11,7 +11,7 @@ View CLI sessions under Dashboard → Settings → Security. With the matching s
|
|
|
11
11
|
Use `pnpm cli login --key-login` for the RSA prompt, or explicit Merchant ID/key-file flags for automation. RSA keys keep their server-assigned environment. Browser login requires the new Dashboard, gateway and user-service routes to be deployed. For local integration, pass `--dashboard-url http://127.0.0.1:3000 --api-url http://127.0.0.1:3002` to login.
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
适用版本:0.0.1-rc.
|
|
14
|
+
适用版本:0.0.1-rc.4 候选版。以下示例中的 `pnpm cli` 用于源码目录;通过 npm 安装后,替换为 `pancake`,其余参数不变。本说明随安装包提供,无需 GitHub 权限。
|
|
15
15
|
|
|
16
16
|
## 当前能力与边界
|
|
17
17
|
|
|
@@ -26,10 +26,10 @@ Use `pnpm cli login --key-login` for the RSA prompt, or explicit Merchant ID/key
|
|
|
26
26
|
| 操作记录、脱敏调试、自检、诊断导出 | 已实现 |
|
|
27
27
|
| 本地 webhook 监听 | 已实现;仅浏览器会话,需要独立部署 relay/gateway 支持 |
|
|
28
28
|
| 模拟事件发送 | 尚未实现 |
|
|
29
|
-
| npm / npx | `0.0.1-rc.
|
|
29
|
+
| npm / npx | `0.0.1-rc.4` 候选版使用 `next` 渠道 |
|
|
30
30
|
| Homebrew | 等待首个稳定版;候选版不进入正式配方 |
|
|
31
31
|
|
|
32
|
-
当前注册表共 **
|
|
32
|
+
当前注册表共 **65 条命令**,覆盖官方索引中的 **33 个商户 API-Key REST 路由**;字段和认证限制见[完整覆盖矩阵](api-coverage.md)。这不代表所有客户侧接口或所有可选字段均开放。
|
|
33
33
|
|
|
34
34
|
后端通过匹配 RSA 密钥区分测试和生产,两种密钥均可登录。CLI 已接入网关的 `X-Waffo-Environment: test|prod` 响应头,登录、查询结果和调试记录使用本次请求的环境,不需要用户手选。
|
|
35
35
|
|
|
@@ -366,7 +366,7 @@ pnpm cli diagnostics export --operation OPERATION_ID --output ./diagnostics.json
|
|
|
366
366
|
|
|
367
367
|
## 9. 发布后的安装、更新和回退
|
|
368
368
|
|
|
369
|
-
`0.0.1-rc.
|
|
369
|
+
`0.0.1-rc.4` 候选版使用 `next` 渠道,安装命令:
|
|
370
370
|
|
|
371
371
|
```sh
|
|
372
372
|
npm install -g @waffo/pancake-cli@next
|
|
@@ -406,7 +406,7 @@ CLI 不提供独立自更新器,任务执行中不自动换版本。回退前
|
|
|
406
406
|
|
|
407
407
|
## 验收尚未完成的部分
|
|
408
408
|
|
|
409
|
-
已发布候选版的 npm/npx 安装、生产登录与退出撤销、Test/Production
|
|
409
|
+
已发布候选版的 npm/npx 安装、生产登录与退出撤销、Test/Production 部分商品和折扣操作均已通过。已发布候选版使用旧监听签名协议,已验证 Test 模拟支付通知转发、签名、重试及清理,也验证了 Production 监听连接、轮询、环境隔离及清理。协议 2 的生产部署验收仍待完成。剩余:生产真实支付通知、真实 Windows 终端 Ctrl+C 和首个稳定版的 Homebrew 安装。以上不代表所有命令均完成真实业务验收。
|
|
410
410
|
|
|
411
411
|
开源客户端的使用和开发不要求取得私有服务端源码。联网命令需要可访问、兼容的托管 API 与凭证;网页登录还需要兼容的 Dashboard。离线命令发现、schema 和预览不需要运行服务端。
|
|
412
412
|
|
|
@@ -447,14 +447,54 @@ Writes return a safe summary including IDs and usable codes. Batch results inclu
|
|
|
447
447
|
|
|
448
448
|
Run `pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook` after browser login. Test is always the default; `--live` explicitly selects Production without saving that selection. Optional `--events order.completed,subscription.created` filters event names. Use event names supported by your backend. RSA keys cannot listen.
|
|
449
449
|
|
|
450
|
-
|
|
450
|
+
Start the listener, then copy its complete public PEM into `listener-public.pem` in the working directory of your local receiver. For an automated receiver, read the PEM from the `data.signingPublicKey` field of the NDJSON `ready` event. The service generates a fresh RSA-2048 key pair for every listener. The CLI verifies each delivery with this session's key before forwarding it. Use the public key from the active session for its loopback route in either Test or `--live` mode. Refresh it after each restart. Keep your permanent webhook endpoint configured with its platform verification key.
|
|
451
|
+
|
|
452
|
+
For a local receiver using the TypeScript SDK, pass the session key explicitly. The SDK checks the signature and timestamp before parsing the event. For example, this Fetch API handler returns HTTP 204 for a verified event.
|
|
453
|
+
|
|
454
|
+
```ts
|
|
455
|
+
import { readFileSync } from 'node:fs';
|
|
456
|
+
import { verifyWebhook } from '@waffo/pancake-ts';
|
|
457
|
+
|
|
458
|
+
const publicKey = readFileSync('./listener-public.pem', 'utf8').trim();
|
|
459
|
+
if (!publicKey) throw new Error('Copy the current listener public key into listener-public.pem.');
|
|
460
|
+
|
|
461
|
+
export async function POST(request: Request) {
|
|
462
|
+
const body = await request.text();
|
|
463
|
+
try {
|
|
464
|
+
verifyWebhook(body, request.headers.get('x-waffo-signature'), { publicKey });
|
|
465
|
+
} catch {
|
|
466
|
+
return new Response(null, { status: 400 });
|
|
467
|
+
}
|
|
468
|
+
return new Response(null, { status: 204 });
|
|
469
|
+
}
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
The loopback receiver receives the exact signed body and the allowlisted Content-Type, X-Waffo-Signature and X-Waffo-Event headers. Redirects count as failures. A 2xx response is acknowledged as success; other statuses and network failures retry up to three times. Deduplicate by the original eventId across attempts and resends. Each resend has its own deliveryId and recordId.
|
|
451
473
|
|
|
452
474
|
`--json` and piped output stream NDJSON standard envelopes with `ready`, `delivery`, `stopped` events and a terminal error envelope on failure. Event bodies, signatures and response bodies are omitted. Ctrl+C/SIGTERM clean up temporary sessions; kill/crash falls back to a 90-second session TTL. Polls occur every three seconds. Local forwarding times out after ten seconds. Session failures are visible and exit nonzero. The command never modifies configured webhook endpoints and provides no synthetic event trigger.
|
|
453
475
|
|
|
454
|
-
|
|
476
|
+
### Upgrade a listener to protocol 2
|
|
477
|
+
|
|
478
|
+
During the service cutover, stop the temporary listener with Ctrl+C. Permanent webhook endpoints continue receiving events. If `pancake --version` reports `0.0.1-rc.2` or `0.0.1-rc.3`, its start request omits the required protocol version. The upgraded service rejects this before creating a session (HTTP 400, `LISTENER_CLIENT_UPGRADE_REQUIRED`). The older CLI maps HTTP 400 to the generic `INVALID_REQUEST`, which can also represent other input errors.
|
|
479
|
+
|
|
480
|
+
Upgrade to the protocol 2 candidate and verify that the installed version is `0.0.1-rc.4`. Then restart your listener.
|
|
481
|
+
|
|
482
|
+
```sh
|
|
483
|
+
npm install -g @waffo/pancake-cli@next
|
|
484
|
+
pancake --version
|
|
485
|
+
pancake listen --store-id STO_example --forward-to http://localhost:3000/webhook
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
Copy the new listener's public PEM to your local receiver and reload its verification key. The previous session's key and pending local deliveries do not carry over. If the updated CLI reports `LISTENER_UPGRADE_REQUIRED`, the operator must finish the service rollout. The CLI attempts to stop a session returned by a legacy start route before polling. History, detail and resend also report an incompatible API. Resend checks support with a read-only history request before submission. Keep the original replay UUID if a prior submission is uncertain.
|
|
489
|
+
|
|
490
|
+
The earlier published candidate passed Test sandbox-payment delivery and Production listener startup, polling, isolation and cleanup on the production deployment. Real Production payment delivery remains pending.
|
|
455
491
|
|
|
456
492
|
## Browser permission limits
|
|
457
493
|
|
|
458
494
|
Browser login covers supported business commands in Test and Production within your merchant/store access. API Keys, account deletion, payout/bank changes, other devices, additional CLI authorizations, API credentials, Webhook `secret` fields and identity documents are blocked by the server. Use `logout` to revoke the current CLI session. Environment switching does not ask for another browser authorization. Re-login after the browser permission update; RSA login is unchanged.
|
|
459
495
|
|
|
460
496
|
Webhook configuration can still be changed in Test. Webhook addresses remain readable. Browser secret changes use the server success response (`verification: response_only`), without reading the secret back or requiring another Dashboard step. Raw GraphQL queries follow the same server permissions.
|
|
497
|
+
|
|
498
|
+
Use `pancake listen history --store-id STO_example [--limit 20]` to see retained records and active target sessions. Up to 100 records are kept for 24 hours per account, store and environment. `pancake listen show <recordId> --store-id STO_example` shows metadata and attempts. Add `--output ./delivery.json` to save the original body in a new private file.
|
|
499
|
+
|
|
500
|
+
Run `pancake listen resend <recordId> --store-id STO_example --session <sessionId> --yes --idempotency-key <uuid>` to enqueue the original event for an active listener matching its event type. Production requires both `--live` and `--confirm-production`. The target session signs each delivery of the replay with its own key. A receipt confirms queue admission. Resend creates no payment and does not retry a permanent webhook. To recover an uncertain resend, repeat the same command with the same UUID within 24 hours.
|