@waffo/pancake-cli 0.0.1-rc.1 → 0.0.1-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -3
- package/README.md +30 -16
- package/SKILL.md +11 -7
- package/dist/adapters/browser-login.js +1 -13
- package/dist/adapters/config.js +68 -21
- package/dist/adapters/pancake/client.js +29 -18
- package/dist/adapters/pancake/retry-after.js +46 -0
- package/dist/application/action-auth.js +7 -0
- package/dist/application/action-result.js +2 -3
- package/dist/application/api-actions.js +17 -19
- package/dist/application/api-reads.js +1 -1
- package/dist/application/auth.js +8 -5
- package/dist/application/dispatch.js +3 -1
- package/dist/application/idempotency.js +8 -0
- package/dist/application/products.js +11 -13
- package/dist/application/read-operation.js +15 -7
- package/dist/application/webhooks.js +12 -15
- package/dist/application/write-operation.js +26 -0
- package/dist/cli/output.js +1 -1
- package/dist/commands/action-definitions.js +26 -1
- package/dist/commands/action-previews.js +12 -0
- package/dist/commands/api-coverage.js +5 -4
- package/dist/commands/discount-definitions.js +4 -0
- package/dist/commands/discount-preview.js +17 -0
- package/dist/commands/product-preview.js +5 -0
- package/dist/commands/read-definitions.js +9 -1
- package/dist/commands/registry.js +1 -1
- package/dist/commands/webhook-preview.js +3 -0
- package/dist/contracts/action-routes.js +21 -0
- package/docs/api-coverage.md +4 -4
- package/docs/usage.md +16 -11
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.0.1-rc.3
|
|
4
|
+
|
|
5
|
+
Release candidate for npm’s `next` channel. No stable release.
|
|
6
|
+
|
|
7
|
+
- Point the packaged CLI agent reference to the official Docs page while retaining the bundled offline `SKILL.md`.
|
|
8
|
+
- Add `graphql query --background` for recurring reads that skip local operation records while retaining authenticated context and private response export.
|
|
9
|
+
- Pass an explicit local archive path to the manual npm publishing command.
|
|
10
|
+
|
|
11
|
+
## 0.0.1-rc.2
|
|
12
|
+
|
|
13
|
+
Release candidate for npm’s `next` channel. No stable release.
|
|
14
|
+
|
|
15
|
+
- Record full write intent, including product-create endpoint and API origin, before sending a business request; retain known result IDs when verification, private export or record completion fails. Unknown writes are never replayed.
|
|
16
|
+
- Preserve confirmed-rejection exit codes across product, webhook and API actions; unknown outcomes remain `OUTCOME_UNKNOWN` with exit 1.
|
|
17
|
+
- Correct action target/result identities, including checkout sessions and promotion-code batches; exclude tokens and content request IDs from resource IDs.
|
|
18
|
+
- Show discount terms, scope, limits and batch settings in offline previews while keeping nested customer email restrictions redacted.
|
|
19
|
+
- Return `CONFIG_CHANGED` for concurrent login/logout/environment changes and preserve newer saved configuration, including during invalid-config recovery.
|
|
20
|
+
|
|
21
|
+
- Refresh installation and acceptance documentation, including manual candidate publication and the remaining stable-release gates.
|
|
22
|
+
|
|
3
23
|
## 0.0.1-rc.1
|
|
4
24
|
|
|
5
|
-
|
|
25
|
+
Published on 2026-11-17 to npm's `next` channel. Production service deployment and acceptance are separate from package publication.
|
|
6
26
|
|
|
7
27
|
### Added
|
|
8
28
|
|
|
@@ -33,5 +53,5 @@ Release candidate for UAT acceptance on npm's `next` channel. Production service
|
|
|
33
53
|
### Release requirements
|
|
34
54
|
|
|
35
55
|
- Browser authorization, verified environment headers and webhook listening require separately deployed compatible services.
|
|
36
|
-
- Production
|
|
37
|
-
- npm
|
|
56
|
+
- Follow-up acceptance verified production login and logout revocation, selected Test/Production business operations, Test sandbox-payment forwarding, and Production listener startup, polling and cleanup. Real Production payment delivery and actual Windows console Ctrl+C remain pending.
|
|
57
|
+
- Published npm/npx installation passed. Registry-to-Homebrew delivery remains pending the first stable release.
|
package/README.md
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
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
|
-
**
|
|
5
|
+
**Release candidate: 0.0.1-rc.3, using npm’s `next` channel. No stable release yet.** Implemented: 62 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
|
|
|
9
|
-
Install the project's pinned package manager once: `npm install -g pnpm@11.25.0`. Use pnpm for repository development; the published
|
|
9
|
+
Install the project's pinned package manager once: `npm install -g pnpm@11.25.0`. Use pnpm for repository development; the published candidate can be installed with npm or npx. Homebrew installation becomes available after the first stable release.
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
12
|
pnpm install --frozen-lockfile
|
|
@@ -20,9 +20,9 @@ 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.3/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.3/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
|
|
|
27
27
|
CLI prompts and help use concise English. In a terminal, `pnpm cli` shows the first-use steps, `commands` prints a compact command list, and `whoami` explains how to log in when no credentials are present. Use `--json` (or pipe stdout) for the complete machine envelope. Local pnpm/npm script help uses the corresponding local command; installed CLI help uses `pancake`.
|
|
28
28
|
|
|
@@ -55,7 +55,7 @@ Automation can inject `WAFFO_MERCHANT_ID` plus exactly one of `WAFFO_PRIVATE_KEY
|
|
|
55
55
|
|
|
56
56
|
The backend determines test or production from the matching RSA key. The CLI reads `X-Waffo-Environment: test|prod` from the authenticated gateway response, records it per request, and shows `Environment: Test` or `Environment: Production`. Login and whoami expose the same evidence; doctor passes the environment check only when verified. RSA environments cannot be selected locally. Browser sessions send the chosen `X-Environment`; only the authenticated response header verifies it.
|
|
57
57
|
|
|
58
|
-
**Deployment dependency:** Browser login requires the Dashboard authorization page, user-service device authorization endpoints and gateway routes/header changes. They
|
|
58
|
+
**Deployment dependency:** Browser login requires the Dashboard authorization page, user-service device authorization endpoints and gateway routes/header changes. They are deployed separately from the CLI. Production browser login, environment verification and listener connections were verified with the published candidate on 2026-11-17; live payment delivery remains pending. Until the gateway returns the header, results remain `Environment: Unknown (unverified)` and doctor reports the missing evidence. Missing or invalid headers never reuse an older request's environment. JSON keeps `meta.actualEnvironment` and `meta.environmentVerified`; a verified merchant identity alone does not verify its environment.
|
|
59
59
|
|
|
60
60
|
Writes require `--yes` and a verified environment. Production writes and Test→Production publication also require `--confirm-production`. Store and notification-recipient changes affect shared Test/Production resources and require `--confirm-shared`; when executed in Production, both flags are required. These confirmations do not change server permissions or require another browser login. Unknown outcomes are never automatically retried. Webhook writes remain Test-only.
|
|
61
61
|
|
|
@@ -69,24 +69,37 @@ pnpm cli products create --type onetime --file product.json --yes --idempotency-
|
|
|
69
69
|
|
|
70
70
|
This performs a real write and may affect production. Subscription input also needs `billingPeriod`. Every write requires a durable local intent and is attempted once; keep its operation ID and idempotency key. If the result is unknown or verification is pending, inspect the operation and query the product (or find it in the merchant dashboard if no ID was returned). Never repeat creation to recover a missing response. Product creation results omit metadata, descriptions and URLs; warnings go to stderr while stdout retains one JSON envelope.
|
|
71
71
|
|
|
72
|
+
Write intents record the merchant, input fingerprint, impact, API origin and exact endpoint before the business request; known targets and browser-selected environments are included when available. RSA credentials have no local environment selection. Checkout records distinguish the product target (`targetResourceId`) from the returned session (`resourceId`); promotion-code batches use `batchId` as their result ID. Session tokens and content-check request IDs are not resource IDs. Accepted changes retain their returned resource ID in recovery errors if verification, private export or record completion fails. If local record updates remain unavailable, the original intent stays available for investigation. Confirmed rejections preserve their original exit code, including 2 for input/authentication restrictions; unknown outcomes use `OUTCOME_UNKNOWN` and exit 1.
|
|
73
|
+
|
|
72
74
|
The expanded action commands use `--file input.json`, require `--yes`, and support `--idempotency-key`. Use `schema <command.id>` and `--dry-run` before execution. `products publish` and `groups publish` explicitly copy test data to production. New actions report `response_only` verification, or `acknowledgement_only` for group deletion/publication; they do not claim a resource read-back. Product creation and test-webhook configuration retain read-back verification. Browser login can read Webhook addresses but cannot read `secret`. Secret changes use server acknowledgement (`verification: response_only`), without a secret read-back or an extra Dashboard step.
|
|
73
75
|
|
|
74
76
|
Checkout and customer-session creation require `--output` to a new private file. Customer-session issuance requires RSA login; browser login is unsupported for this command. It is not CLI login. Arbitrary `graphql query` and `analytics query` also require private output for execution; their parser rejects mutations, subscriptions and multiple operations before credentials or network access. There is no raw REST passthrough. Customer-token-only order cancellation/reactivation is outside merchant coverage. Product create/update rejects `taxIncluded`; webhook writes remain test-only. No real merchant acceptance or release is implied by route coverage.
|
|
75
77
|
|
|
76
|
-
|
|
78
|
+
For recurring read-only queries, `pancake graphql query --background --file query.json --output ./query-result.json --json` skips the local operation record for that invocation. Use a fresh private output path for each call. The gateway must verify the environment before the response can be exported, and a browser session must match its selected environment. Authenticated results include the effective `meta.apiOrigin` and set `meta.operationId` to `null`.
|
|
79
|
+
|
|
80
|
+
Configuration uses version 2. Legacy version 1 is not migrated: run `logout`, then `login` with your existing key. Unknown future versions are never overwritten, including by logout. Concurrent login, environment selection or logout returns `CONFIG_CHANGED` if another command replaced or cleared its saved configuration; the newer configuration is preserved. Inspect `whoami` before starting another login or environment change.
|
|
77
81
|
|
|
78
82
|
## Install the release candidate
|
|
79
83
|
|
|
80
|
-
|
|
84
|
+
Version `0.0.1-rc.3` uses npm's `next` channel. Use the explicit channel or version while evaluating the candidate:
|
|
81
85
|
|
|
82
86
|
```sh
|
|
83
87
|
npm install -g @waffo/pancake-cli@next
|
|
84
88
|
pancake --version
|
|
85
89
|
# Or run the exact candidate without a global installation:
|
|
86
|
-
npx @waffo/pancake-cli@0.0.1-rc.
|
|
90
|
+
npx @waffo/pancake-cli@0.0.1-rc.3 --help
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
For the hosted service, no URL overrides are needed:
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
pancake login
|
|
97
|
+
pancake whoami
|
|
98
|
+
pancake env test
|
|
99
|
+
pancake stores list
|
|
87
100
|
```
|
|
88
101
|
|
|
89
|
-
For UAT acceptance, get
|
|
102
|
+
For UAT acceptance only, get both origins from your team. The selected API origin is saved for later commands.
|
|
90
103
|
|
|
91
104
|
```sh
|
|
92
105
|
pancake login --dashboard-url <uat-dashboard-origin> --api-url <uat-api-origin>
|
|
@@ -95,7 +108,7 @@ pancake env test
|
|
|
95
108
|
pancake stores list
|
|
96
109
|
```
|
|
97
110
|
|
|
98
|
-
Check the merchant and environment before business operations. Default URLs target production; npm installation does not deploy the hosted services. Production browser login and
|
|
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 have passed; real Production payment delivery remains pending. Automated Windows package checks pass; a real Windows console Ctrl+C listener walkthrough remains pending.
|
|
99
112
|
|
|
100
113
|
To update within the candidate channel, run `npm install -g @waffo/pancake-cli@next`. Stable Homebrew does not install prereleases.
|
|
101
114
|
|
|
@@ -164,13 +177,14 @@ Package smoke tests install the actual tarball in isolated directories and exerc
|
|
|
164
177
|
## CI/CD
|
|
165
178
|
|
|
166
179
|
- PR/main: type checking, tests, build, audit, archive allowlist and npx/global installation on macOS/Linux/Windows with Node 22 and 24, plus installation checks on the minimum runtime, Node 22.14.0.
|
|
167
|
-
-
|
|
180
|
+
- Manual candidate releases: publish the reviewed and tested archive from main with maintainer authentication and 2FA; verify registry integrity and npm/npx installation.
|
|
181
|
+
- Optional version-tag workflow: validate tag/version/changelog and main ancestry, rerun checks, publish the tested archive via npm OIDC, verify registry integrity, create a GitHub release with the same archive/checksum.
|
|
168
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.
|
|
169
183
|
- Weekly Dependabot updates cover dependencies and pinned Actions.
|
|
170
184
|
|
|
171
|
-
See the [agent reference](https://
|
|
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.3/CHANGELOG.md). Maintainer release instructions are in `docs/release/README.md` in the source repository and require repository access.
|
|
172
186
|
|
|
173
|
-
Internal planning documents are maintained outside the source repository.
|
|
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, Test sandbox-payment forwarding, signature verification, retry and cleanup were also verified. 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.
|
|
174
188
|
|
|
175
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.
|
|
176
190
|
|
|
@@ -199,9 +213,9 @@ Overrides accept HTTPS, or HTTP on `127.0.0.1` only. No URL credentials, paths,
|
|
|
199
213
|
|
|
200
214
|
## Contributing and security
|
|
201
215
|
|
|
202
|
-
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.3/CONTRIBUTING.md) for development and validation, and [SECURITY.md](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/SECURITY.md) for handling credentials and reporting vulnerabilities. Licensed under [MIT](https://cdn.jsdelivr.net/npm/@waffo/pancake-cli@0.0.1-rc.3/LICENSE).
|
|
203
217
|
|
|
204
|
-
Discount commands support listing, coupon details, creation, coupon renaming, permanent deactivation and promotion-code batches (1–500). 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.3/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.
|
|
205
219
|
|
|
206
220
|
## Listen to merchant events locally
|
|
207
221
|
|
|
@@ -216,4 +230,4 @@ The CLI preserves the exact event body and existing webhook signature, forwards
|
|
|
216
230
|
|
|
217
231
|
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. Delivery metadata includes 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.
|
|
218
232
|
|
|
219
|
-
Isolated Test acceptance verified a sandbox payment event reaching localhost, valid signatures on both attempts, retry after HTTP 500 followed by HTTP 200, and Ctrl+C cleanup. Production
|
|
233
|
+
Isolated Test acceptance verified a sandbox payment event reaching localhost, valid signatures on both attempts, retry after HTTP 500 followed by HTTP 200, and Ctrl+C cleanup. On the production deployment, Test sandbox-payment delivery passed, and Production listener startup, polling, mode isolation and cleanup passed. Real Production payment delivery remains pending.
|
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.3`, using the `next` channel. Install with `npm install -g @waffo/pancake-cli@next`, or use `npx @waffo/pancake-cli@0.0.1-rc.3`. 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
|
|
|
@@ -17,7 +17,7 @@ pnpm cli schema webhook.add --json
|
|
|
17
17
|
pnpm cli webhook add --help
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
Local examples use `pnpm cli`; the executable is named `pancake
|
|
20
|
+
Local examples use `pnpm cli`; the installed executable is named `pancake`. The official TypeScript compiler emits a complete ESM module tree in `dist/`; `pnpm cli` runs `node dist/index.js`. Commander handles commands, arguments and help. `pnpm dev` watches and recompiles; run commands in a second terminal after compilation succeeds. After renaming or deleting source files, restart `pnpm dev` or run `pnpm run build` to remove old output. `pnpm run pack:release` starts with a clean build. Do not invent commands from the roadmap. Temporary local webhook listening is implemented for browser sessions; simulated event sending and MCP are not implemented. `products create` supports offline preview and real onetime/subscription creation with `--yes`.
|
|
21
21
|
|
|
22
22
|
## Authentication
|
|
23
23
|
|
|
@@ -65,17 +65,21 @@ Production writes require `--yes --confirm-production`. `products publish` and `
|
|
|
65
65
|
|
|
66
66
|
`graphql query` and `analytics query` accept a JSON file containing `query` and optional `variables`. A real parser rejects mutations, subscriptions and multiple operations before credentials/network, including dry-run. Real execution requires private `--output` because arbitrary aliases/fragments can contain secrets. There is no raw REST passthrough. Group query fields must be confirmed using official documentation/introspection before use; do not invent a group root field. Customer-token-only onetime cancellation, customer subscription cancellation and reactivation are excluded from merchant scope.
|
|
67
67
|
|
|
68
|
+
For recurring reads, opt into `graphql query --background` to skip the local operation record for that call. Supply a fresh private `--output` for every execution. Responses are exported only after the gateway verifies the environment, which must match the selection for browser sessions. Authenticated responses include the effective `meta.apiOrigin` and a null `meta.operationId`. When a `RATE_LIMITED` error has `error.details.retryAfterMs`, wait at least that many milliseconds before the next request.
|
|
69
|
+
|
|
68
70
|
## Remote changes
|
|
69
71
|
|
|
70
72
|
`products create --type onetime|subscription --file product.json --yes --idempotency-key KEY` creates a real product using the effective credential environment. Review the merchant, store, name and prices before confirming. The CLI requires verified environment evidence before writing and requires explicit production confirmation for Production. Subscription input requires `billingPeriod`; trial prices require positive `metadata.trialDays`. For product creation or updates, do not supply `taxIncluded`: the backend fixes tax-exclusive pricing and this CLI rejects that option. Results contain safe product fields; descriptions, metadata and URLs are omitted.
|
|
71
73
|
|
|
72
74
|
`webhook add/update/remove` also perform remote changes. Add requires `testMode:true`. Update/remove require an accessible existing test webhook in the selected store. Channel and test mode cannot be updated. Listing shows Webhook addresses and omits secrets. Configuring a webhook does not verify event delivery.
|
|
73
75
|
|
|
74
|
-
Use a reviewed input and `--yes`; this confirms intent without bypassing checks. Preserve the operation ID and idempotency key. A write is attempted once, with a persisted local intent before sending. Reusing a locally recorded key is blocked; this is not a distributed or permanent deduplication guarantee.
|
|
76
|
+
Use a reviewed input and `--yes`; this confirms intent without bypassing checks. Preserve the operation ID and idempotency key. A write is attempted once, with a persisted local intent before sending. Reusing a locally recorded key is blocked; this is not a distributed or permanent deduplication guarantee. Before the business request, the intent includes merchant, input fingerprint, impact, exact endpoint and API origin, plus known target/store IDs and the selected environment for browser credentials. RSA credentials do not have a local environment selection.
|
|
75
77
|
|
|
76
78
|
## Results and recovery
|
|
77
79
|
|
|
78
|
-
`--json` and non-TTY output produce one JSON object on stdout (except `listen`, which streams NDJSON): `schemaVersion`, `ok`, `data`, `error`, `meta`. Logs go to stderr. Non-interactive calls never prompt. Exit codes: 0 success; 1 execution/verification failure; 2 invalid input/configuration; 130 interruption. Always check `ok` and `meta.outcome`. Authenticated success and error metadata includes `merchantId`, `source`, `actualEnvironment` (`test`, `prod` or `null`) and `environmentVerified`; human output also shows this context and available operation/request IDs. A selected environment alone is not verified evidence.
|
|
80
|
+
`--json` and non-TTY output produce one JSON object on stdout (except `listen`, which streams NDJSON): `schemaVersion`, `ok`, `data`, `error`, `meta`. Logs go to stderr. Non-interactive calls never prompt. Exit codes: 0 success; 1 execution/verification failure; 2 invalid input/configuration; 130 interruption. Always check `ok` and `meta.outcome`. Authenticated success and error metadata includes `merchantId`, `source`, `actualEnvironment` (`test`, `prod` or `null`) and `environmentVerified`; human output also shows this context and available operation/request IDs. A selected environment alone is not verified evidence. Confirmed write rejections preserve their original exit code; unknown write outcomes always use `OUTCOME_UNKNOWN` and exit 1. `CONFIG_CHANGED` means a concurrent login, environment selection or logout found replaced/cleared configuration and preserved the newer state; inspect `whoami` before making another change.
|
|
81
|
+
|
|
82
|
+
Checkout `targetResourceId` identifies the product; its `resourceId` identifies the returned session. Promotion-code batch results use `batchId`; session tokens and content-check request IDs are never resource IDs. Accepted-write recovery errors retain a known result ID even when private export or record completion fails. If record updates remain unavailable, inspect the retained initial intent and merchant dashboard.
|
|
79
83
|
|
|
80
84
|
- `completed`: the command finished; a dry-run still has `data.executed:false`.
|
|
81
85
|
- `rejected`: the requested operation was not completed; inspect the error.
|
|
@@ -91,11 +95,11 @@ pnpm cli doctor --debug --json
|
|
|
91
95
|
|
|
92
96
|
Diagnostics are local, redacted and never automatically uploaded. Ask before sharing them with another party. No request ID from the server means `requestId:null`; local operation IDs are not server audit IDs. Records are capped at 1000; resolved records older than 30 days are pruned on the next operation. Unresolved records are retained.
|
|
93
97
|
|
|
94
|
-
|
|
98
|
+
For repeatable automation use a fixed published version, such as `npx @waffo/pancake-cli@VERSION ...`. Update via the original package manager outside active tasks; do not mutate the running CLI or overwrite unknown config/record versions.
|
|
95
99
|
|
|
96
100
|
## Discounts
|
|
97
101
|
|
|
98
|
-
Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create|generate|deactivate`. Coupon lists require storeId; promotion-code lists require couponId in a JSON file. Coupon update changes only name; deactivation is permanent. Generate accepts 1–500 codes. Schema and dry-run validate offline;
|
|
102
|
+
Use `coupons list|get|create|update|deactivate` and `promotion-codes list|create|generate|deactivate`. Coupon lists require storeId; promotion-code lists require couponId in a JSON file. Coupon update changes only name; deactivation is permanent. Generate accepts 1–500 codes. Schema and dry-run validate offline. Discount previews show amounts/percentages, duration, product scope, limits, couponId and batch count/length; customerEmails stay redacted in nested promotion codes too. Execute writes with --yes and an explicit idempotency key. Browser sessions and RSA keys are accepted by gateway source with server-enforced store permissions. Results expose codes and IDs, omit customer restrictions from write summaries, and omit customerEmails from named reads. Use private --output on writes or an explicit arbitrary GraphQL query to export sensitive details. All nine discount commands have isolated Test-environment acceptance evidence, including deactivation read-back; selected Production discount operations also passed, while full stable-release acceptance remains pending.
|
|
99
103
|
|
|
100
104
|
## Temporary local listener
|
|
101
105
|
|
|
@@ -103,6 +107,6 @@ Use `pancake listen --store-id STO_example --forward-to http://localhost:3000/we
|
|
|
103
107
|
|
|
104
108
|
## Service and verification boundaries
|
|
105
109
|
|
|
106
|
-
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. Browser login, environment headers and listener relay support must be deployed separately from the CLI.
|
|
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. Browser login, environment headers and listener relay support must be deployed separately from the 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. Production listener startup, polling, isolation and cleanup passed; real Production payment delivery and actual Windows console Ctrl+C remain pending. These checks do not establish acceptance of every command.
|
|
107
111
|
|
|
108
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.
|
|
@@ -3,20 +3,8 @@ import { execFile } from 'node:child_process';
|
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
4
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
5
|
import pkg from '../../package.json' with { type: 'json' };
|
|
6
|
+
import { serviceOrigin } from "../contracts/action-routes.js";
|
|
6
7
|
import { CliError } from "../contracts/errors.js";
|
|
7
|
-
export function serviceOrigin(value) {
|
|
8
|
-
let url;
|
|
9
|
-
try {
|
|
10
|
-
url = new URL(value);
|
|
11
|
-
}
|
|
12
|
-
catch {
|
|
13
|
-
throw new CliError('INVALID_ARGUMENT', 'Provide a valid API or Dashboard origin.', { exitCode: 2 });
|
|
14
|
-
}
|
|
15
|
-
if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1'))) {
|
|
16
|
-
throw new CliError('INVALID_ARGUMENT', 'Service URLs must be HTTPS origins, or explicit http://127.0.0.1:<port> origins for local testing.', { exitCode: 2 });
|
|
17
|
-
}
|
|
18
|
-
return url.origin;
|
|
19
|
-
}
|
|
20
8
|
async function openBrowser(url) {
|
|
21
9
|
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? windowsSystemTool('browser') : 'xdg-open';
|
|
22
10
|
const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
|
package/dist/adapters/config.js
CHANGED
|
@@ -3,7 +3,7 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
|
3
3
|
import { atomicJson, readJson, protectDirectory, withDirectoryLock, exportPrivateFile, hasCode } from "./files.js";
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
5
|
import { lstat, unlink } from 'node:fs/promises';
|
|
6
|
-
import { serviceOrigin } from "
|
|
6
|
+
import { serviceOrigin } from "../contracts/action-routes.js";
|
|
7
7
|
import { CliError } from "../contracts/errors.js";
|
|
8
8
|
export function configDirectory(env = process.env) {
|
|
9
9
|
if (env.WAFFO_CONFIG_DIR)
|
|
@@ -27,6 +27,25 @@ function unsupportedVersion(legacy) {
|
|
|
27
27
|
exitCode: 2, recovery: legacy ? 'Run pancake logout to clear the legacy configuration, then pancake login with your existing key file.' : 'Use a CLI version that supports this configuration.',
|
|
28
28
|
});
|
|
29
29
|
}
|
|
30
|
+
function parseConfig(raw) {
|
|
31
|
+
if (raw === undefined)
|
|
32
|
+
return { configVersion: 2 };
|
|
33
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
34
|
+
throw new CliError('INVALID_CONFIG', 'Invalid local configuration.', { exitCode: 2, recovery: 'Run pancake logout, then pancake login.' });
|
|
35
|
+
const config = raw;
|
|
36
|
+
if (config.configVersion !== 2)
|
|
37
|
+
throw unsupportedVersion(Number(config.configVersion) === 1);
|
|
38
|
+
if (config.credential !== undefined)
|
|
39
|
+
checkCredential(config.credential);
|
|
40
|
+
return { configVersion: 2, ...(config.revision ? { revision: config.revision } : {}), ...(config.credential ? { credential: config.credential } : {}) };
|
|
41
|
+
}
|
|
42
|
+
function configChanged() {
|
|
43
|
+
return new CliError('CONFIG_CHANGED', 'Your saved login changed during this command. Run the command again.', { stage: 'credentials' });
|
|
44
|
+
}
|
|
45
|
+
function protectFutureVersion(raw) {
|
|
46
|
+
if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion !== 1 && raw.configVersion !== 2)
|
|
47
|
+
throw unsupportedVersion(false);
|
|
48
|
+
}
|
|
30
49
|
export class ConfigStore {
|
|
31
50
|
directory;
|
|
32
51
|
constructor(directory) { this.directory = directory; }
|
|
@@ -52,22 +71,13 @@ export class ConfigStore {
|
|
|
52
71
|
}
|
|
53
72
|
async read() {
|
|
54
73
|
await protectDirectory(this.directory);
|
|
55
|
-
|
|
56
|
-
if (raw === undefined)
|
|
57
|
-
return { configVersion: 2 };
|
|
58
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
59
|
-
throw new CliError('INVALID_CONFIG', 'Invalid local configuration.', { exitCode: 2, recovery: 'Run pancake logout, then pancake login.' });
|
|
60
|
-
if (raw.configVersion !== 2)
|
|
61
|
-
throw unsupportedVersion(Number(raw.configVersion) === 1);
|
|
62
|
-
if (raw.credential !== undefined)
|
|
63
|
-
checkCredential(raw.credential);
|
|
64
|
-
return { configVersion: 2, ...(raw.revision ? { revision: raw.revision } : {}), ...(raw.credential ? { credential: raw.credential } : {}) };
|
|
74
|
+
return parseConfig(await readJson(join(this.directory, 'config.json')));
|
|
65
75
|
}
|
|
66
|
-
async save(credential,
|
|
76
|
+
async save(credential, expected, signal) {
|
|
67
77
|
await withDirectoryLock(this.directory, async () => {
|
|
68
78
|
const snapshot = await this.read();
|
|
69
|
-
if (
|
|
70
|
-
throw
|
|
79
|
+
if (snapshot.revision !== expected.revision)
|
|
80
|
+
throw configChanged();
|
|
71
81
|
const previous = snapshot.credential;
|
|
72
82
|
if (signal?.aborted)
|
|
73
83
|
throw new CliError('INTERRUPTED', 'Cancelled.', { exitCode: 130 });
|
|
@@ -94,10 +104,39 @@ export class ConfigStore {
|
|
|
94
104
|
await this.removeManagedKey(previous, 'saved');
|
|
95
105
|
});
|
|
96
106
|
}
|
|
107
|
+
async persistClearedConfig(raw) {
|
|
108
|
+
await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID() });
|
|
109
|
+
if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion === 2 && 'credential' in raw)
|
|
110
|
+
await this.removeManagedKey(raw.credential, 'cleared');
|
|
111
|
+
}
|
|
97
112
|
async clear(expected) {
|
|
98
113
|
await withDirectoryLock(this.directory, async () => {
|
|
99
|
-
|
|
100
|
-
|
|
114
|
+
let raw;
|
|
115
|
+
try {
|
|
116
|
+
raw = await readJson(join(this.directory, 'config.json'));
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (error instanceof CliError && error.code === 'INVALID_CONFIG')
|
|
120
|
+
throw configChanged();
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
protectFutureVersion(raw);
|
|
124
|
+
let snapshot;
|
|
125
|
+
try {
|
|
126
|
+
snapshot = parseConfig(raw);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (error instanceof CliError && ['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
|
|
130
|
+
throw configChanged();
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
if (snapshot.revision !== expected.revision)
|
|
134
|
+
throw configChanged();
|
|
135
|
+
await this.persistClearedConfig(raw);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
async clearInvalid() {
|
|
139
|
+
await withDirectoryLock(this.directory, async () => {
|
|
101
140
|
let raw;
|
|
102
141
|
try {
|
|
103
142
|
raw = await readJson(join(this.directory, 'config.json'));
|
|
@@ -105,12 +144,20 @@ export class ConfigStore {
|
|
|
105
144
|
catch (error) {
|
|
106
145
|
if (!(error instanceof CliError) || error.code !== 'INVALID_CONFIG')
|
|
107
146
|
throw error;
|
|
147
|
+
await this.persistClearedConfig(undefined);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
protectFutureVersion(raw);
|
|
151
|
+
try {
|
|
152
|
+
parseConfig(raw);
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (!(error instanceof CliError) || !['INVALID_CONFIG', 'CONFIG_VERSION_UNSUPPORTED'].includes(error.code))
|
|
156
|
+
throw error;
|
|
157
|
+
await this.persistClearedConfig(raw);
|
|
158
|
+
return;
|
|
108
159
|
}
|
|
109
|
-
|
|
110
|
-
throw unsupportedVersion(false);
|
|
111
|
-
await atomicJson(join(this.directory, 'config.json'), { configVersion: 2, revision: randomUUID() });
|
|
112
|
-
if (raw && typeof raw === 'object' && 'configVersion' in raw && raw.configVersion === 2 && 'credential' in raw)
|
|
113
|
-
await this.removeManagedKey(raw.credential, 'cleared');
|
|
160
|
+
throw configChanged();
|
|
114
161
|
});
|
|
115
162
|
}
|
|
116
163
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { createHash, createPrivateKey, randomUUID, sign } from 'node:crypto';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { DEFAULT_API_ORIGIN, productCreateEndpoint, serviceOrigin, webhookEndpoint } from "../../contracts/action-routes.js";
|
|
3
4
|
import { CliError } from "../../contracts/errors.js";
|
|
4
|
-
import { serviceOrigin } from "../browser-login.js";
|
|
5
5
|
import { readPrivateKey } from "../files.js";
|
|
6
6
|
import { ME_QUERY, PRODUCT_QUERIES, STORES_QUERY, WEBHOOKS_QUERY, WEBHOOK_SECRETS_QUERY } from "./queries.js";
|
|
7
7
|
import { graphqlValidationError } from "./graphql-errors.js";
|
|
8
8
|
import { conflictError } from "./conflict-error.js";
|
|
9
9
|
import { httpErrorReason } from "./http-error-reason.js";
|
|
10
|
+
import { parseRetryAfter } from "./retry-after.js";
|
|
10
11
|
export function parsePrivateKey(raw) {
|
|
11
12
|
let value = raw.trim().replace(/\\n/g, '\n');
|
|
12
13
|
if (!value.startsWith('-----BEGIN'))
|
|
@@ -21,12 +22,12 @@ export function parsePrivateKey(raw) {
|
|
|
21
22
|
throw new CliError('INVALID_KEY', 'A valid RSA private key in PKCS#8 or PKCS#1 format is required.', { exitCode: 2, stage: 'credentials' });
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
|
-
function apiError(status, write, reason, requestId, session = false) {
|
|
25
|
+
function apiError(status, write, reason, requestId, session = false, retryAfterMs) {
|
|
25
26
|
const codes = { 400: 'INVALID_REQUEST', 401: 'AUTH_FAILED', 403: 'PERMISSION_DENIED', 404: 'NOT_FOUND', 429: 'RATE_LIMITED' };
|
|
26
27
|
const unknown = write && (status >= 500 || status === 409 || (status >= 200 && status < 300));
|
|
27
28
|
const message = unknown ? 'The write result is unknown; do not create a new operation to retry it.' : status === 401 && session ? 'Your login was not accepted. Run login again.' : 'The API rejected or could not complete the request.';
|
|
28
29
|
return new CliError(unknown ? 'OUTCOME_UNKNOWN' : codes[status] ?? 'REMOTE_ERROR', reason ? `${message} Server reason: ${reason}` : message, {
|
|
29
|
-
stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}) },
|
|
30
|
+
stage: 'api', outcome: unknown ? 'unknown' : 'rejected', details: { status, ...(requestId ? { requestId } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) },
|
|
30
31
|
recovery: unknown ? 'Inspect the operation record and query the affected resource before taking further action.' : 'Check credentials, store access and command input. Run doctor for connection checks.',
|
|
31
32
|
});
|
|
32
33
|
}
|
|
@@ -62,14 +63,14 @@ function requestId(response) {
|
|
|
62
63
|
export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
63
64
|
if (!/^MER_[A-Za-z0-9]+$/.test(credentials.merchantId))
|
|
64
65
|
throw new CliError('INVALID_CONFIG', 'Invalid Merchant ID.', { exitCode: 2 });
|
|
65
|
-
const apiUrl = serviceOrigin(credentials.apiUrl ??
|
|
66
|
+
const apiUrl = serviceOrigin(credentials.apiUrl ?? DEFAULT_API_ORIGIN);
|
|
66
67
|
if (credentials.sessionToken && !['test', 'prod'].includes(credentials.environment ?? ''))
|
|
67
68
|
throw new CliError('INVALID_CONFIG', 'Select a valid session environment.', { exitCode: 2 });
|
|
68
69
|
const raw = credentials.privateKey ?? (credentials.privateKeyFile ? await readPrivateKey(credentials.privateKeyFile) : '');
|
|
69
70
|
const key = credentials.sessionToken ? undefined : parsePrivateKey(raw);
|
|
70
|
-
async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal,
|
|
71
|
+
async function post(path, body, idempotencyKey, acknowledgementOnly = false, signal, options = {}) {
|
|
71
72
|
const serialized = JSON.stringify(body);
|
|
72
|
-
const write = idempotencyKey !== undefined || singleAttempt;
|
|
73
|
+
const write = idempotencyKey !== undefined || options.singleAttempt === true;
|
|
73
74
|
const deadline = Date.now() + 20000;
|
|
74
75
|
for (let index = 0;; index++) {
|
|
75
76
|
const started = Date.now(), timestamp = Math.floor(started / 1000).toString();
|
|
@@ -110,8 +111,9 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
110
111
|
if (!response.ok) {
|
|
111
112
|
const retryable = response.status === 429 || response.status >= 500;
|
|
112
113
|
const retryHeader = response.headers.get('retry-after');
|
|
113
|
-
const
|
|
114
|
-
|
|
114
|
+
const retryAfterMs = retryHeader ? parseRetryAfter(retryHeader) : undefined;
|
|
115
|
+
const retryMs = retryHeader ? retryAfterMs : 100 * (index + 1);
|
|
116
|
+
if (!signal?.aborted && !write && retryable && index < 2 && retryMs !== undefined && Date.now() + retryMs < deadline) {
|
|
115
117
|
await delay(retryMs);
|
|
116
118
|
continue;
|
|
117
119
|
}
|
|
@@ -121,7 +123,8 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
121
123
|
throw conflict;
|
|
122
124
|
}
|
|
123
125
|
const reason = httpErrorReason(response.status, envelope, [credentials.sessionToken ?? '', raw, headers['X-Signature'] ?? '']);
|
|
124
|
-
|
|
126
|
+
const retryHint = options.includeRetryAfter && response.status === 429 ? retryAfterMs : undefined;
|
|
127
|
+
throw apiError(response.status, write, reason, attempt.requestId, Boolean(credentials.sessionToken), retryHint);
|
|
125
128
|
}
|
|
126
129
|
if (Array.isArray(envelope.errors) && envelope.errors.length > 0) {
|
|
127
130
|
if (!write && path === '/v1/graphql' && response.status === 200 && 'query' in body && typeof body.query === 'string') {
|
|
@@ -142,7 +145,19 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
142
145
|
return { data: envelope.data, environment: attempt.environment };
|
|
143
146
|
}
|
|
144
147
|
}
|
|
145
|
-
async
|
|
148
|
+
const query = async (query, variables = {}, options) => {
|
|
149
|
+
const { data, environment } = await post('/v1/graphql', { query, variables }, undefined, false, undefined, { includeRetryAfter: options?.background });
|
|
150
|
+
if (options?.background) {
|
|
151
|
+
if (!environment)
|
|
152
|
+
throw new CliError('ENVIRONMENT_UNVERIFIED', 'The gateway did not verify the credential environment. No result was exported.', { stage: 'api' });
|
|
153
|
+
if (credentials.sessionToken && environment !== credentials.environment) {
|
|
154
|
+
throw new CliError('ENVIRONMENT_MISMATCH', 'The gateway did not confirm the selected environment. No result was exported.', {
|
|
155
|
+
stage: 'api', details: { selectedEnvironment: credentials.environment },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return data;
|
|
160
|
+
};
|
|
146
161
|
return {
|
|
147
162
|
query,
|
|
148
163
|
async revokeSession() {
|
|
@@ -158,7 +173,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
158
173
|
if (typeof payload.jti !== 'string' || !/^mer_[A-Za-z0-9_-]{16}$/.test(payload.jti))
|
|
159
174
|
throw new CliError('INVALID_CONFIG', 'Saved session ID is invalid. Revoke it in Dashboard Security.');
|
|
160
175
|
try {
|
|
161
|
-
const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, true);
|
|
176
|
+
const result = await post('/v1/actions/merchant/sign-out-session', { jti: payload.jti }, undefined, false, undefined, { singleAttempt: true });
|
|
162
177
|
if (result.data.success !== true)
|
|
163
178
|
throw new Error('Revocation not confirmed');
|
|
164
179
|
return true;
|
|
@@ -173,7 +188,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
173
188
|
if (!['start', 'poll', 'ack', 'stop'].includes(action))
|
|
174
189
|
throw new CliError('INVALID_ARGUMENT', 'Invalid listener action.', { exitCode: 2 });
|
|
175
190
|
try {
|
|
176
|
-
return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, true)).data;
|
|
191
|
+
return (await post(`/v1/actions/notification/cli-listen-${action}`, body, undefined, false, signal, { singleAttempt: true })).data;
|
|
177
192
|
}
|
|
178
193
|
catch (error) {
|
|
179
194
|
if (error instanceof CliError && error.code === 'OUTCOME_UNKNOWN')
|
|
@@ -184,10 +199,6 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
184
199
|
async action(path, body, key, acknowledgementOnly = false) {
|
|
185
200
|
if (!/^\/v1\/actions\/[a-z-]+\/[a-z-]+$/.test(path))
|
|
186
201
|
throw new CliError('INVALID_ARGUMENT', 'Invalid action endpoint.', { exitCode: 2 });
|
|
187
|
-
if (credentials.sessionToken && path === '/v1/actions/auth/issue-session-token')
|
|
188
|
-
throw new CliError('AUTH_METHOD_UNSUPPORTED', 'sessions create requires RSA API-key login; browser login cannot issue customer session tokens.', {
|
|
189
|
-
exitCode: 2, stage: 'credentials', recovery: 'Run login --key-login with a merchant RSA API key, then run sessions create again.',
|
|
190
|
-
});
|
|
191
202
|
return (await post(path, body, key, acknowledgementOnly)).data;
|
|
192
203
|
},
|
|
193
204
|
async me(signal) {
|
|
@@ -212,7 +223,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
212
223
|
return data.product;
|
|
213
224
|
},
|
|
214
225
|
async createProduct(type, body, idempotencyKey) {
|
|
215
|
-
const { data } = await post(
|
|
226
|
+
const { data } = await post(productCreateEndpoint(type), body, idempotencyKey);
|
|
216
227
|
const product = data.product;
|
|
217
228
|
if (!product || typeof product !== 'object' || Array.isArray(product) || typeof product.id !== 'string' || !/^PROD_[A-Za-z0-9]+$/.test(product.id))
|
|
218
229
|
throw apiError(200, true);
|
|
@@ -228,7 +239,7 @@ export async function createGateway(credentials, observer, fetchImpl = fetch) {
|
|
|
228
239
|
return store.storeWebhooks;
|
|
229
240
|
},
|
|
230
241
|
async mutateWebhook(action, body, idempotencyKey) {
|
|
231
|
-
const { data } = await post(
|
|
242
|
+
const { data } = await post(webhookEndpoint(action), body, idempotencyKey);
|
|
232
243
|
const webhook = data.webhook;
|
|
233
244
|
if (!webhook || typeof webhook.id !== 'string' || typeof webhook.testMode !== 'boolean' || !Array.isArray(webhook.events))
|
|
234
245
|
throw apiError(200, true);
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
2
|
+
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
3
|
+
const imfFixdate = /^(?<weekday>[A-Z][a-z]{2}), (?<day>\d{2}) (?<month>[A-Z][a-z]{2}) (?<year>\d{4}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
|
|
4
|
+
const rfc850Date = /^(?<weekday>[A-Z][a-z]{5,8}), (?<day>\d{2})-(?<month>[A-Z][a-z]{2})-(?<year>\d{2}) (?<time>\d{2}:\d{2}:\d{2}) GMT$/;
|
|
5
|
+
const asctimeDate = /^(?<weekday>[A-Z][a-z]{2}) (?<month>[A-Z][a-z]{2}) (?<day>\d{2}| \d) (?<time>\d{2}:\d{2}:\d{2}) (?<year>\d{4})$/;
|
|
6
|
+
function httpDate(value, now) {
|
|
7
|
+
const parts = imfFixdate.exec(value)?.groups ?? rfc850Date.exec(value)?.groups ?? asctimeDate.exec(value)?.groups;
|
|
8
|
+
if (!parts)
|
|
9
|
+
return;
|
|
10
|
+
const month = months.indexOf(parts.month) + 1;
|
|
11
|
+
if (!month)
|
|
12
|
+
return;
|
|
13
|
+
const leapSecond = parts.time === '23:59:60';
|
|
14
|
+
const time = leapSecond ? '23:59:59' : parts.time;
|
|
15
|
+
const dateAndTime = `${String(month).padStart(2, '0')}-${parts.day.trimStart().padStart(2, '0')}T${time}`;
|
|
16
|
+
const shortYear = parts.year.length === 2;
|
|
17
|
+
let year = Number(parts.year);
|
|
18
|
+
if (shortYear) {
|
|
19
|
+
// Resolve the latest matching year no more than 50 years in the future.
|
|
20
|
+
const limit = new Date(now);
|
|
21
|
+
limit.setUTCFullYear(limit.getUTCFullYear() + 50);
|
|
22
|
+
year += Math.floor(limit.getUTCFullYear() / 100) * 100;
|
|
23
|
+
const candidate = new Date(`${year}-${dateAndTime}Z`).getTime();
|
|
24
|
+
if (candidate + (leapSecond ? 1000 : 0) > limit.getTime())
|
|
25
|
+
year -= 100;
|
|
26
|
+
}
|
|
27
|
+
if (year < 1900)
|
|
28
|
+
return;
|
|
29
|
+
const normalized = `${String(year).padStart(4, '0')}-${dateAndTime}`;
|
|
30
|
+
const date = new Date(`${normalized}Z`);
|
|
31
|
+
if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 19) !== normalized)
|
|
32
|
+
return;
|
|
33
|
+
const weekday = weekdays[date.getUTCDay()];
|
|
34
|
+
if (parts.weekday !== (shortYear ? weekday : weekday.slice(0, 3)))
|
|
35
|
+
return;
|
|
36
|
+
return date.getTime() + (leapSecond ? 1000 : 0);
|
|
37
|
+
}
|
|
38
|
+
/** Parse RFC 9110 delay-seconds and HTTP-date without permissive date coercion. */
|
|
39
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
40
|
+
if (/^\d+$/.test(value)) {
|
|
41
|
+
const milliseconds = Number(value) * 1000;
|
|
42
|
+
return Number.isSafeInteger(milliseconds) ? milliseconds : undefined;
|
|
43
|
+
}
|
|
44
|
+
const timestamp = httpDate(value, now);
|
|
45
|
+
return timestamp === undefined ? undefined : Math.max(0, timestamp - now);
|
|
46
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { CliError } from "../contracts/errors.js";
|
|
2
|
+
export function requireActionAuthentication(authentication, hasSession) {
|
|
3
|
+
if (authentication === 'merchant-rsa' && hasSession)
|
|
4
|
+
throw new CliError('AUTH_METHOD_UNSUPPORTED', 'This command requires RSA API-key login; browser login cannot issue customer session tokens.', {
|
|
5
|
+
exitCode: 2, stage: 'credentials', recovery: 'Run login --key-login with a merchant RSA API key, then run sessions create again.',
|
|
6
|
+
});
|
|
7
|
+
}
|