@getpara/rest-sdk 3.23.0 → 3.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -108,6 +108,32 @@ await para.createWallet(
108
108
  Use an idempotency key when a retry could create duplicate state or submit duplicate signing/broadcast work. The SDK
109
109
  does not generate one for you because it does not retry requests internally.
110
110
 
111
+ ## EVM fee urgency
112
+
113
+ Set `urgency: 'normal' | 'urgent'` on a self-funded EVM `transfer`, `transferWithAutoRetry`,
114
+ `speedUpRestTransaction`, `cancelRestTransaction`, `createYieldDeposit`, or `createYieldWithdrawal` request.
115
+ Omission means normal. Para selects fresh recommended prices; the SDK forwards the choice without calculating fees.
116
+
117
+ ```ts
118
+ await para.transfer(wallet.id, {
119
+ to: '0x1111111111111111111111111111111111111111',
120
+ value: '1000000000000',
121
+ chainId: '11155111',
122
+ urgency: 'urgent',
123
+ }, { idempotencyKey: 'saved-payment-key' });
124
+ ```
125
+
126
+ Explicit initial prices, including zero, stay pinned. Urgency changes generated prices, not gas units; an inconsistent
127
+ fee pair is rejected. Urgent does not guarantee confirmation time. Sponsored transfers, non-EVM execution, and
128
+ caller-built `signTransaction`/`signTransactionWithAutoRetry` requests reject urgency. EVM fee estimates return
129
+ both options and do not take a selector. `estimateFee()` exposes typed `feeOptions.normal` and `feeOptions.urgent`,
130
+ with their fee-family fields, execution budgets, quote timestamp and block number. These optional fields are absent
131
+ on non-EVM or older responses.
132
+
133
+ Durable recovery and yield retain the choice across worker restarts and approval/action phases. Omitted and explicit
134
+ normal share the legacy durable identity; changing urgency under the same key conflicts. Replays retain prepared and
135
+ signed bytes. Fee ceilings and deadlines remain unchanged; urgent never enlarges spending authorization.
136
+
111
137
  ## Transaction History
112
138
 
113
139
  When REST broadcasts a transaction, `signTransaction(..., { broadcast: true })` and `transfer(...)` return a
@@ -135,23 +161,178 @@ methods as the read model: fetch the record immediately after a broadcast, backf
135
161
  reconcile your database against Para's persisted transaction state. See the Para webhook docs for signature
136
162
  verification and `rest.transaction.confirmed` / `rest.transaction.failed` payload examples.
137
163
 
164
+ ## Automatic retry for EVM transfers
165
+
166
+ Use `transferWithAutoRetry` for self-funded native/ERC-20 EVM transfers. Save the body and key before sending;
167
+ reuse both after a timeout. HTTP 202 means durable admission before signing or broadcast and returns the original
168
+ transaction ID and `autoRetry` state instead of signed bytes.
169
+
170
+ ```ts
171
+ const key = crypto.randomUUID();
172
+ const request = {
173
+ to: '0x1111111111111111111111111111111111111111',
174
+ value: '1000000000000',
175
+ chainId: '11155111',
176
+ urgency: 'urgent' as const,
177
+ autoRetry: {
178
+ maxExecutionFeeWei: '1000000000000000',
179
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
180
+ },
181
+ };
182
+ // Persist { key, request } before submitting. Never renew the deadline on replay.
183
+ const accepted = await para.transferWithAutoRetry(wallet.id, request, { idempotencyKey: key });
184
+ const current = await para.getRestTransaction(wallet.id, accepted.transactionId);
185
+ console.log(current.status, current.autoRetry?.state);
186
+ ```
187
+
188
+ `maxExecutionFeeWei` is the per-attempt execution-gas ceiling, excluding separate chain fees. Initial fees must fit;
189
+ later recommendations remain subject to the original ceiling and historical replacement minimum. This SDK method
190
+ supports EVM transfers; it does not add urgency to Solana recovery. See [Automatic fee retry](https://docs.getpara.com/v3/rest/automatic-retry).
191
+
192
+ ## Manual EVM recovery
193
+
194
+ For an eligible unresolved ordinary self-funded EVM transfer, use `speedUpRestTransaction` or
195
+ `cancelRestTransaction` with a new saved idempotency key and a replacement fee ceiling:
196
+
197
+ ```ts
198
+ const recovery = await para.speedUpRestTransaction(wallet.id, transactionId, {
199
+ maxExecutionFeeWei: '1000000000000000',
200
+ urgency: 'urgent',
201
+ }, { idempotencyKey: recoveryKey });
202
+ console.log(recovery.manualRecovery.state, recovery.manualRecovery.attempt.hash);
203
+ ```
204
+
205
+ Both methods return the original transaction ID and typed `manualRecovery` metadata. Read progress with
206
+ `getRestTransaction`. Use `cancelRestTransaction` with the same body shape to request cancellation. Only one manual
207
+ speed-up or cancellation is accepted per original transfer; HTTP acceptance does not prove inclusion or cancellation.
208
+ The original payment can still win. Replaying the saved key/body keeps the selected replacement bytes.
209
+ See [Manual EVM recovery](https://docs.getpara.com/v3/rest/transaction-history#manual-evm-recovery) for eligibility.
210
+
211
+ ## Automatic retry for broadcast signing
212
+
213
+ Use `signTransactionWithAutoRetry` with `autoRetry` and `broadcast: true` to authorize recovery of one EVM transaction or supported legacy Solana
214
+ transaction. Save the key and entire request before submitting; HTTP retries reuse both, including the original deadline.
215
+ The server returns HTTP 202 before signing or broadcasting, with `transactionId`, `status`, and `autoRetry` instead of signed bytes.
216
+
217
+ ```ts
218
+ const key = crypto.randomUUID();
219
+ const request = {
220
+ transaction: { ...transaction, type: 2 as const },
221
+ broadcast: true as const,
222
+ autoRetry: {
223
+ maxExecutionFeeWei: '1000000000000000',
224
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
225
+ },
226
+ };
227
+ // Persist { key, request } in your job record before this call.
228
+ const result = await para.signTransactionWithAutoRetry(wallet.id, request, { idempotencyKey: key });
229
+ const record = await para.getRestTransaction(wallet.id, result.transactionId);
230
+ console.log(record.status, record.autoRetry?.state, record.monitoring?.winningHash);
231
+ ```
232
+
233
+ EVM supports type 0 and 2 contract calls, including type 2 access lists. Fees and gas limits use decimal integer
234
+ strings. Same-nonce replacements preserve the destination, value, calldata, gas limit and access list; fee caps
235
+ increase by at least 12.5%, rounded up, at least 60 seconds after the last broadcast. There is no fixed attempt limit.
236
+ `maxExecutionFeeWei` caps each attempt's execution gas; separate chain fees are excluded.
237
+
238
+ For Solana, send an unsigned legacy transaction with the wallet as the sole signer and fee payer, a still-valid finalized
239
+ recent blockhash, exactly one 120000-unit compute limit and one compute-unit-price instruction. Use `maxExecutionFeeLamports`
240
+ instead of `maxExecutionFeeWei`; it caps base plus priority fees and excludes account rent. Versioned and durable-nonce
241
+ transactions and unsupported system/account instructions are rejected. Para must locate the original hash in its
242
+ 512-slot finalized history window; missing or older anchor history is rejected before signing. The original transaction
243
+ bytes are preserved even when a newer finalized hash exists. Solana resends exact bytes until expiry and
244
+ requires finalized non-execution proof before rebuilding with a new blockhash.
245
+
246
+ The enrolling secret key, wallet and current policies must authorize every attempt. A transaction-bound approval
247
+ does not authorize changed fees: retry requests do not accept `reviewId` or `initiatorUserId`. A stopped retry can
248
+ still have a pending on-chain transaction. Continue polling its original ID; do not submit the operation again with a
249
+ new key. Signer adapters keep their sign-only behavior. See [Automatic fee retry](https://docs.getpara.com/v3/rest/automatic-retry).
250
+
251
+ ## Yield deposits and withdrawals
252
+
253
+ Use `createYieldDeposit`, `createYieldWithdrawal` and `getYieldOperation` for the existing Aave/Morpho yield routes.
254
+ Save the complete request and idempotency key before the first call. Amounts are USDC decimal units; withdrawals
255
+ also accept `'all'`. Select a supported `marketId`, or use `chainId` to select its Aave market.
256
+
257
+ ```ts
258
+ const key = crypto.randomUUID();
259
+ const request = {
260
+ marketId: 'aave-v3:11155111:usdc',
261
+ amount: '10',
262
+ autoRetry: {
263
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
264
+ approval: { maxExecutionFeeWei: '200000000000000' },
265
+ action: { maxExecutionFeeWei: '1000000000000000' },
266
+ },
267
+ };
268
+ // Persist { key, request } before submitting; replay both unchanged.
269
+ const accepted = await para.createYieldDeposit(wallet.id, request, { idempotencyKey: key });
270
+ const operation = await para.getYieldOperation(wallet.id, accepted.id);
271
+ console.log(operation.status, operation.transactions, operation.autoRetry?.phases);
272
+ ```
273
+
274
+ `autoRetry` is optional. Its required action ceiling authorizes one deposit/withdrawal transaction, including all
275
+ same-nonce fee replacements. A needed approval requires its own explicit ceiling; Para never copies the action
276
+ ceiling or rolls unused authorization forward. Include approval authorization on deposits unless existing allowance
277
+ is known to cover the amount; withdrawals never need it. Each ceiling uses the existing
278
+ per-transaction execution-gas semantics, excluding separate chain charges. This is not a cumulative operation budget.
279
+
280
+ A missing approval ceiling or a first transaction above its ceiling cannot be fixed by replaying the same request.
281
+ Cancel the proven-unsigned operation first with
282
+ `POST /v1/wallets/{walletId}/yield/operations/{operationId}/cancel`, then use a new key and adequate ceilings.
283
+ The SDK does not wrap this cancellation route. Signed or uncertain phases remain tracked and cannot be replaced this way.
284
+
285
+ The original deadline applies across approval, action and every replay. If it expires after approval, the confirmed
286
+ approval remains visible and the unsigned action does not run. `autoRetry.phases` exposes each phase's transaction
287
+ ID, attempts and retry state. An initial reviewed transaction retains its exact bytes; replacements require a fresh
288
+ policy allow and reuse that phase's principal accounting. Current policy and accounting must be re-proven;
289
+ incompatible reuse, including unsupported approved spend overage, stops signing before MPC. A stopped retry can still
290
+ be pending on-chain: track the
291
+ same operation and transaction IDs until resolved. Omission retains existing exact-byte recovery.
292
+
138
293
  ## Sponsored Transfers
139
294
 
140
- Para enables gas sponsorship per partner through its existing admin-managed `featureFlags.restGasSponsorship` setting.
141
- For enabled partners, eligible EVM token transfers return HTTP 202 with
142
- `executionMode: 'sponsored'`, a `transactionId`, and a status. The response has no `signedTransaction`.
143
- The SDK request is unchanged. Check `executionMode` before reading legacy response fields.
295
+ Set `sponsoredGas: true` to require Para-paid gas on an eligible EVM token transfer. Para must enable your
296
+ partner's existing admin-managed `featureFlags.restGasSponsorship` setting. If sponsorship cannot be honored, the
297
+ request fails with an actionable error; it never falls back to wallet-paid gas. Accepted sponsored transfers return HTTP 202 with
298
+ `sponsoredGas: true`, a `transactionId`, and a status. The response has no `signedTransaction`.
299
+
300
+ For a common transfer, provide the recipient, amount and asset (chain and token) with `sponsoredGas: true`;
301
+ Para chooses the nonce, gas and fees. If you require an explicit nonce, fee cap or other control, the SDK forwards
302
+ it unchanged. The current sponsorship API rejects unsupported controls with an actionable error. The SDK never
303
+ drops those controls, flips `sponsoredGas` to `false`, or retries through wallet-paid execution.
304
+
305
+ Set `sponsoredGas: false` or omit it to require wallet-paid gas, regardless of partner sponsorship eligibility.
306
+ Only `sponsoredGas: true` requests Para-paid gas. Transfer responses and transaction
307
+ history/detail include `sponsoredGas: true` for Para-paid gas or `false` for wallet-paid gas. Older API versions may omit it;
308
+ the deprecated response-only `executionMode` field remains for compatibility (`'sponsored'` or `'legacy'`). Do not send
309
+ `executionMode` in requests: the API rejects it with an actionable error.
310
+
311
+ The server must support `sponsoredGas` before you use it. The SDK expects wallet-paid gas when the field is omitted
312
+ and leaves the request unchanged. If a server returns a different sponsorship choice, the SDK
313
+ throws `ParaRestSponsorshipError` and preserves the result in `error.response`. For older responses, the SDK infers
314
+ sponsorship from `executionMode === 'sponsored'`. A transaction may already have been submitted: reconcile its tracking
315
+ ID/hash before retrying. This response check cannot undo a broadcast.
316
+
317
+ Upgrading an integration that previously relied on partner enrollment alone changes its gas-payment contract:
318
+ send `sponsoredGas: true` on each new transfer that requires Para-paid gas. Omitted requests now require wallet-paid
319
+ gas, and the SDK rejects an unexpected sponsored response, including an older response without the Boolean.
320
+ Replaying an existing sponsored key requires `sponsoredGas: true` and unchanged economic intent. Replaying that key
321
+ with `false` or an omitted flag returns `409 IDEMPOTENCY_CONFLICT` without creating another transfer. Recover the
322
+ original tracking ID or replay the original sponsored request; never retry the payout with a fresh idempotency key.
144
323
 
145
324
  ```ts
325
+ import { isSponsoredTransfer } from '@getpara/rest-sdk';
326
+
146
327
  // Save this key with your payout before the request. Reuse it if the response is lost.
147
328
  const requestKey = crypto.randomUUID();
148
329
  const result = await para.transfer(
149
330
  wallet.id,
150
- { to: recipient, value: '1000000', chainId, tokenAddress, kind: 'ERC20' },
331
+ { to: recipient, value: '1000000', chainId, tokenAddress, kind: 'ERC20', sponsoredGas: true },
151
332
  { idempotencyKey: requestKey },
152
333
  );
153
334
 
154
- if (result.executionMode === 'sponsored') {
335
+ if (isSponsoredTransfer(result)) {
155
336
  // Save the tracking ID, then poll this lookup from your background job.
156
337
  const record = await para.getRestTransaction(wallet.id, result.transactionId);
157
338
  console.log(record.status, record.stage, record.hash, record.actualGasCost);
@@ -160,11 +341,18 @@ if (result.executionMode === 'sponsored') {
160
341
  }
161
342
  ```
162
343
 
344
+ `isSponsoredTransfer()` narrows the response for tracking or reading signed bytes. It uses `sponsoredGas` when present
345
+ and falls back to the older response-only `executionMode` field when the Boolean is absent.
346
+
163
347
  Sponsored requests require an idempotency key and a positive integer `value` in token base units. Sponsorship manages
164
- gas and submission: omit nonce, transaction type and gas/fee overrides; omit `broadcast` or set it to `true`.
165
- The server applies its configured supported chains and tokens. With the partner flag enabled, pausing global or
166
- chain sponsorship rejects matching transfers rather than falling back to wallet-paid gas. Turning the partner flag
167
- off routes new requests through the ordinary transfer path; existing sponsored operations retain their tracking IDs.
348
+ nonce, gas, fees and submission. The only accepted body fields are `to`, `value`, `chainId`, `tokenAddress`, `kind`, `broadcast`,
349
+ `addressScreening`, and `sponsoredGas`. All other fields are rejected, even when null or empty, including `autoRetry`,
350
+ nonce/type/fee overrides, `reviewId`, `initiatorUserId`, and `network`. The generic `TransferRequest` still exposes
351
+ initiator and network fields for legacy transfers. Omit `kind` or set it to `'ERC20'`; omit `broadcast` and
352
+ `addressScreening` or set them to `true`. Explicit sponsorship does not support Solana or disabled recipient screening.
353
+ The server enforces partner eligibility and its supported chain/token configuration.
354
+ Unavailable or paused sponsorship rejects explicit sponsored requests. The partner flag controls sponsorship eligibility;
355
+ it never selects sponsorship for requests with `sponsoredGas: false` or an omitted field. Existing sponsored operations retain their tracking IDs.
168
356
 
169
357
  Poll `getRestTransaction` until the status is `confirmed`, `reverted`, or `failed`; stop polling for policy approval when
170
358
  `stage` is `requires_action`. `submitted` with stage `included` is still awaiting receipt verification. `submission_unknown` means
package/dist/cjs/index.js CHANGED
@@ -41,7 +41,9 @@ __export(index_exports, {
41
41
  ParaRestClient: () => ParaRestClient,
42
42
  ParaRestError: () => ParaRestError,
43
43
  ParaRestSerializationError: () => ParaRestSerializationError,
44
+ ParaRestSponsorshipError: () => ParaRestSponsorshipError,
44
45
  ParaRestValidationError: () => import_validation2.ParaRestValidationError,
46
+ isSponsoredTransfer: () => isSponsoredTransfer,
45
47
  toRestJson: () => toRestJson
46
48
  });
47
49
  module.exports = __toCommonJS(index_exports);
@@ -49,7 +51,21 @@ var import_permissions = require("./permissions.js");
49
51
  var import_validation = require("./validation.js");
50
52
  __reExport(index_exports, require("./permissions.js"), module.exports);
51
53
  __reExport(index_exports, require("./webhooks.js"), module.exports);
54
+ __reExport(index_exports, require("./webhookVerification.js"), module.exports);
52
55
  var import_validation2 = require("./validation.js");
56
+ function isSponsoredTransfer(result) {
57
+ var _a;
58
+ return (_a = result.sponsoredGas) != null ? _a : result.executionMode === "sponsored";
59
+ }
60
+ class ParaRestSponsorshipError extends Error {
61
+ constructor(requestedSponsorship, response) {
62
+ super(
63
+ `Sponsorship mismatch: requested sponsoredGas: ${requestedSponsorship} but received ${isSponsoredTransfer(response)}. Reconcile the response before retrying; a transaction may already have been submitted.`
64
+ );
65
+ this.name = "ParaRestSponsorshipError";
66
+ this.response = response;
67
+ }
68
+ }
53
69
  class ParaRestError extends Error {
54
70
  constructor({
55
71
  status,
@@ -169,6 +185,17 @@ class ParaRestClient extends import_permissions.RestPermissionsClient {
169
185
  }
170
186
  return this.request("POST", `/v1/wallets/${walletPath(walletId)}/sign-transaction`, { body, options });
171
187
  }
188
+ signTransactionWithAutoRetry(walletId, body, options) {
189
+ (0, import_validation.requireNonEmpty)(walletId, "walletId");
190
+ (0, import_validation.requireBody)(body, "body");
191
+ if (body.transaction == null || body.transaction === "") {
192
+ throw new import_validation.ParaRestValidationError("transaction is required");
193
+ }
194
+ if (body.broadcast !== true) throw new import_validation.ParaRestValidationError("autoRetry requires broadcast:true");
195
+ (0, import_validation.requireBody)(body.autoRetry, "autoRetry");
196
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
197
+ return this.request("POST", `/v1/wallets/${walletPath(walletId)}/sign-transaction`, { body, options });
198
+ }
172
199
  signTypedData(walletId, body, options) {
173
200
  (0, import_validation.requireNonEmpty)(walletId, "walletId");
174
201
  (0, import_validation.requireBody)(body, "body");
@@ -199,6 +226,23 @@ class ParaRestClient extends import_permissions.RestPermissionsClient {
199
226
  (0, import_validation.requireBody)(body, "body");
200
227
  (0, import_validation.requireNonEmpty)(body.to, "to");
201
228
  (0, import_validation.requireNonEmpty)(body.value, "value");
229
+ const sponsoredGas = body.sponsoredGas === true;
230
+ return this.request("POST", `/v1/wallets/${walletPath(walletId)}/transfer`, { body, options }).then(
231
+ (result) => {
232
+ if (isSponsoredTransfer(result) !== sponsoredGas) {
233
+ throw new ParaRestSponsorshipError(sponsoredGas, result);
234
+ }
235
+ return result;
236
+ }
237
+ );
238
+ }
239
+ transferWithAutoRetry(walletId, body, options) {
240
+ (0, import_validation.requireNonEmpty)(walletId, "walletId");
241
+ (0, import_validation.requireBody)(body, "body");
242
+ (0, import_validation.requireNonEmpty)(body.to, "to");
243
+ (0, import_validation.requireNonEmpty)(body.value, "value");
244
+ (0, import_validation.requireBody)(body.autoRetry, "autoRetry");
245
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
202
246
  return this.request("POST", `/v1/wallets/${walletPath(walletId)}/transfer`, { body, options });
203
247
  }
204
248
  estimateFee(walletId, body, options) {
@@ -225,6 +269,45 @@ class ParaRestClient extends import_permissions.RestPermissionsClient {
225
269
  }
226
270
  );
227
271
  }
272
+ speedUpRestTransaction(walletId, transactionId, body, options) {
273
+ (0, import_validation.requireBody)(body, "body");
274
+ (0, import_validation.requireNonEmpty)(body.maxExecutionFeeWei, "maxExecutionFeeWei");
275
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
276
+ return this.request(
277
+ "POST",
278
+ `/v1/wallets/${walletPath(walletId)}/transactions/${(0, import_validation.pathSegment)("transactionId", transactionId)}/speed-up`,
279
+ { body, options }
280
+ );
281
+ }
282
+ cancelRestTransaction(walletId, transactionId, body, options) {
283
+ (0, import_validation.requireBody)(body, "body");
284
+ (0, import_validation.requireNonEmpty)(body.maxExecutionFeeWei, "maxExecutionFeeWei");
285
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
286
+ return this.request(
287
+ "POST",
288
+ `/v1/wallets/${walletPath(walletId)}/transactions/${(0, import_validation.pathSegment)("transactionId", transactionId)}/cancel`,
289
+ { body, options }
290
+ );
291
+ }
292
+ createYieldDeposit(walletId, body, options) {
293
+ (0, import_validation.requireBody)(body, "body");
294
+ (0, import_validation.requireNonEmpty)(body.amount, "amount");
295
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
296
+ return this.request("POST", `/v1/wallets/${walletPath(walletId)}/yield/deposits`, { body, options });
297
+ }
298
+ createYieldWithdrawal(walletId, body, options) {
299
+ (0, import_validation.requireBody)(body, "body");
300
+ (0, import_validation.requireNonEmpty)(body.amount, "amount");
301
+ (0, import_validation.requireNonEmpty)(options == null ? void 0 : options.idempotencyKey, "idempotencyKey");
302
+ return this.request("POST", `/v1/wallets/${walletPath(walletId)}/yield/withdrawals`, { body, options });
303
+ }
304
+ getYieldOperation(walletId, operationId, options) {
305
+ return this.request(
306
+ "GET",
307
+ `/v1/wallets/${walletPath(walletId)}/yield/operations/${(0, import_validation.pathSegment)("operationId", operationId)}`,
308
+ { options }
309
+ );
310
+ }
228
311
  resumeRestTransaction(walletId, transactionId, body, options) {
229
312
  (0, import_validation.requireBody)(body, "body");
230
313
  (0, import_validation.requireNonEmpty)(body.reviewId, "reviewId");
@@ -345,8 +428,11 @@ function stringField(value) {
345
428
  ParaRestClient,
346
429
  ParaRestError,
347
430
  ParaRestSerializationError,
431
+ ParaRestSponsorshipError,
348
432
  ParaRestValidationError,
433
+ isSponsoredTransfer,
349
434
  toRestJson,
350
435
  ...require("./permissions.js"),
351
- ...require("./webhooks.js")
436
+ ...require("./webhooks.js"),
437
+ ...require("./webhookVerification.js")
352
438
  });
@@ -70,13 +70,13 @@ function requirementPath(reference) {
70
70
  )}`;
71
71
  }
72
72
  class RestPermissionsClient {
73
- listPartnerPolicies(options) {
73
+ listPolicies(options) {
74
74
  return this.request("GET", `${basePath}/policies`, { options });
75
75
  }
76
- getPartnerPolicy(policyId, options) {
76
+ getPolicy(policyId, options) {
77
77
  return this.request("GET", `${basePath}/policies/${(0, import_validation.pathSegment)("policyId", policyId)}`, { options });
78
78
  }
79
- listPartnerPolicyVersions(policyId, options) {
79
+ listPolicyVersions(policyId, options) {
80
80
  return this.request("GET", `${basePath}/policies/${(0, import_validation.pathSegment)("policyId", policyId)}/versions`, { options });
81
81
  }
82
82
  listUserPolicyConsents(userId, context, options) {
@@ -201,16 +201,22 @@ class RestPermissionsClient {
201
201
  { options }
202
202
  );
203
203
  }
204
- listPartnerApprovalCases(query, options) {
204
+ listApprovalCases(query, options) {
205
205
  return this.request("GET", `${basePath}/approval-cases${queryString(query)}`, { options });
206
206
  }
207
- getPartnerApprovalCase(caseId, options) {
207
+ getApprovalCase(caseId, options) {
208
208
  return this.request("GET", `${basePath}/approval-cases/${(0, import_validation.pathSegment)("caseId", caseId)}`, { options });
209
209
  }
210
- cancelPartnerApprovalCase(caseId, options) {
210
+ cancelApprovalCase(caseId, options) {
211
211
  return this.request("POST", `${basePath}/approval-cases/${(0, import_validation.pathSegment)("caseId", caseId)}/cancel`, { options });
212
212
  }
213
- getPartnerPolicyUsage(policyId, context, options) {
213
+ approveReview(reviewId, options) {
214
+ return this.request("POST", `${basePath}/reviews/${(0, import_validation.pathSegment)("reviewId", reviewId)}/approve`, { options });
215
+ }
216
+ rejectReview(reviewId, options) {
217
+ return this.request("POST", `${basePath}/reviews/${(0, import_validation.pathSegment)("reviewId", reviewId)}/reject`, { options });
218
+ }
219
+ getPolicyUsage(policyId, context, options) {
214
220
  const _a = context, { userId, walletId } = _a, query = __objRest(_a, ["userId", "walletId"]);
215
221
  const subjectPath = userId ? `users/${(0, import_validation.pathSegment)("userId", userId)}` : `wallets/${(0, import_validation.pathSegment)("walletId", walletId)}`;
216
222
  const usageQuery = userId ? __spreadValues({ walletId }, query) : query;
@@ -0,0 +1,156 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __async = (__this, __arguments, generator) => {
19
+ return new Promise((resolve, reject) => {
20
+ var fulfilled = (value) => {
21
+ try {
22
+ step(generator.next(value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ };
27
+ var rejected = (value) => {
28
+ try {
29
+ step(generator.throw(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
35
+ step((generator = generator.apply(__this, __arguments)).next());
36
+ });
37
+ };
38
+ var webhookVerification_exports = {};
39
+ __export(webhookVerification_exports, {
40
+ ParaWebhookVerificationError: () => ParaWebhookVerificationError,
41
+ verifyParaWebhook: () => verifyParaWebhook
42
+ });
43
+ module.exports = __toCommonJS(webhookVerification_exports);
44
+ var import_validation = require("./validation.js");
45
+ const DEFAULT_TOLERANCE_IN_SECONDS = 300;
46
+ const SIGNATURE_PREFIX = "v1,";
47
+ const SECRET_PREFIX = /^whsec_/;
48
+ const WHOLE_SECONDS = /^\d+$/;
49
+ class ParaWebhookVerificationError extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = "ParaWebhookVerificationError";
53
+ }
54
+ }
55
+ function verifyParaWebhook(options) {
56
+ return __async(this, null, function* () {
57
+ var _a;
58
+ (0, import_validation.requireNonEmpty)(options.secret, "secret");
59
+ const toleranceInSeconds = requireValidTolerance((_a = options.toleranceInSeconds) != null ? _a : DEFAULT_TOLERANCE_IN_SECONDS);
60
+ const id = requireHeader(options.headers, "webhook-id");
61
+ const timestamp = requireHeader(options.headers, "webhook-timestamp");
62
+ const signatureHeader = requireHeader(options.headers, "webhook-signature");
63
+ assertTimestampWithinTolerance(timestamp, toleranceInSeconds);
64
+ const body = typeof options.body === "string" ? options.body : new TextDecoder().decode(options.body);
65
+ const expectedSignatures = yield signDelivery({ id, timestamp, body }, options.secret);
66
+ const receivedSignatures = signatureHeader.split(" ").filter((entry) => entry.startsWith(SIGNATURE_PREFIX)).map((entry) => entry.slice(SIGNATURE_PREFIX.length));
67
+ const matches = receivedSignatures.some(
68
+ (received) => expectedSignatures.some((expected) => equalsInConstantTime(expected, received))
69
+ );
70
+ if (!matches) {
71
+ throw new ParaWebhookVerificationError("No matching webhook signature");
72
+ }
73
+ return JSON.parse(body);
74
+ });
75
+ }
76
+ function requireValidTolerance(toleranceInSeconds) {
77
+ if (!Number.isFinite(toleranceInSeconds) || toleranceInSeconds < 0) {
78
+ throw new import_validation.ParaRestValidationError("toleranceInSeconds must be a finite, non-negative number");
79
+ }
80
+ return toleranceInSeconds;
81
+ }
82
+ function requireHeader(headers, name) {
83
+ var _a;
84
+ const value = isHeaderGetter(headers) ? headers.get(name) : headers[(_a = findHeaderKey(headers, name)) != null ? _a : name];
85
+ if (typeof value !== "string" || value === "") {
86
+ throw new ParaWebhookVerificationError(`Missing ${name} header`);
87
+ }
88
+ return value;
89
+ }
90
+ function isHeaderGetter(headers) {
91
+ return typeof headers.get === "function";
92
+ }
93
+ function findHeaderKey(headers, name) {
94
+ return Object.keys(headers).find((key) => key.toLowerCase() === name);
95
+ }
96
+ function assertTimestampWithinTolerance(timestamp, toleranceInSeconds) {
97
+ if (!WHOLE_SECONDS.test(timestamp)) {
98
+ throw new ParaWebhookVerificationError("Invalid webhook-timestamp header");
99
+ }
100
+ const ageInSeconds = Math.floor(Date.now() / 1e3) - Number(timestamp);
101
+ if (ageInSeconds > toleranceInSeconds) {
102
+ throw new ParaWebhookVerificationError("Webhook timestamp is too old");
103
+ }
104
+ if (-ageInSeconds > toleranceInSeconds) {
105
+ throw new ParaWebhookVerificationError("Webhook timestamp is too new");
106
+ }
107
+ }
108
+ function signDelivery(_0, _1) {
109
+ return __async(this, arguments, function* ({ id, timestamp, body }, secret) {
110
+ const originalSignature = yield signHmacSha256(new TextEncoder().encode(secret), `${timestamp}.${body}`);
111
+ const standardKey = decodeStandardSigningKey(secret);
112
+ if (!standardKey) {
113
+ return [originalSignature];
114
+ }
115
+ return [originalSignature, yield signHmacSha256(standardKey, `${id}.${timestamp}.${body}`)];
116
+ });
117
+ }
118
+ function decodeStandardSigningKey(secret) {
119
+ try {
120
+ const key = Uint8Array.from(atob(secret.replace(SECRET_PREFIX, "")), (character) => character.charCodeAt(0));
121
+ return key.length > 0 ? key : null;
122
+ } catch (e) {
123
+ return null;
124
+ }
125
+ }
126
+ function signHmacSha256(key, message) {
127
+ return __async(this, null, function* () {
128
+ const subtle = requireSubtleCrypto();
129
+ const cryptoKey = yield subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
130
+ const signature = new Uint8Array(yield subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(message)));
131
+ return btoa(String.fromCharCode(...signature));
132
+ });
133
+ }
134
+ function requireSubtleCrypto() {
135
+ var _a;
136
+ const subtle = (_a = globalThis.crypto) == null ? void 0 : _a.subtle;
137
+ if (!subtle) {
138
+ throw new import_validation.ParaRestValidationError("Web Crypto is required in this runtime to verify webhooks");
139
+ }
140
+ return subtle;
141
+ }
142
+ function equalsInConstantTime(expected, received) {
143
+ if (expected.length !== received.length) {
144
+ return false;
145
+ }
146
+ let difference = 0;
147
+ for (let index = 0; index < expected.length; index++) {
148
+ difference |= expected.charCodeAt(index) ^ received.charCodeAt(index);
149
+ }
150
+ return difference === 0;
151
+ }
152
+ // Annotate the CommonJS export names for ESM import in node:
153
+ 0 && (module.exports = {
154
+ ParaWebhookVerificationError,
155
+ verifyParaWebhook
156
+ });