@getpara/rest-sdk 3.22.0 → 3.24.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/dist/cjs/index.js CHANGED
@@ -49,6 +49,7 @@ var import_permissions = require("./permissions.js");
49
49
  var import_validation = require("./validation.js");
50
50
  __reExport(index_exports, require("./permissions.js"), module.exports);
51
51
  __reExport(index_exports, require("./webhooks.js"), module.exports);
52
+ __reExport(index_exports, require("./webhookVerification.js"), module.exports);
52
53
  var import_validation2 = require("./validation.js");
53
54
  class ParaRestError extends Error {
54
55
  constructor({
@@ -56,7 +57,8 @@ class ParaRestError extends Error {
56
57
  code,
57
58
  requestId,
58
59
  body,
59
- message
60
+ message,
61
+ affectedCaseIds
60
62
  }) {
61
63
  var _a;
62
64
  super((_a = message != null ? message : code) != null ? _a : `Para REST request failed with status ${status}`);
@@ -65,6 +67,7 @@ class ParaRestError extends Error {
65
67
  this.code = code;
66
68
  this.requestId = requestId;
67
69
  this.body = body;
70
+ this.affectedCaseIds = affectedCaseIds;
68
71
  }
69
72
  }
70
73
  class ParaRestSerializationError extends Error {
@@ -273,12 +276,14 @@ class ParaRestClient extends import_permissions.RestPermissionsClient {
273
276
  const parsed = yield parseBody(response);
274
277
  if (!response.ok || expectedStatus != null && response.status !== expectedStatus) {
275
278
  const responseBody = isRecord(parsed) ? parsed : {};
279
+ const affectedCaseIds = responseBody.affectedCaseIds;
276
280
  throw new ParaRestError({
277
281
  status: response.status,
278
282
  code: stringField(responseBody.code),
279
283
  requestId: (_a = response.headers.get("x-request-id")) != null ? _a : requestId,
280
284
  body: parsed,
281
- message: stringField(responseBody.message)
285
+ message: stringField(responseBody.message),
286
+ affectedCaseIds: Array.isArray(affectedCaseIds) && affectedCaseIds.every((caseId) => typeof caseId === "string") ? affectedCaseIds : void 0
282
287
  });
283
288
  }
284
289
  return parsed;
@@ -344,5 +349,6 @@ function stringField(value) {
344
349
  ParaRestValidationError,
345
350
  toRestJson,
346
351
  ...require("./permissions.js"),
347
- ...require("./webhooks.js")
352
+ ...require("./webhooks.js"),
353
+ ...require("./webhookVerification.js")
348
354
  });
@@ -135,8 +135,13 @@ class RestPermissionsClient {
135
135
  updateApprovalConfiguration(reference, body, options) {
136
136
  return this.request("PUT", `${requirementPath(reference)}/configuration`, { body, options });
137
137
  }
138
- resetApprovalConfiguration(reference, expectedRevision, options) {
139
- return this.updateApprovalConfiguration(reference, { expectedRevision, values: {} }, options);
138
+ resetApprovalConfiguration(reference, reset, options) {
139
+ const { expectedRevision, force } = typeof reset === "number" ? { expectedRevision: reset, force: void 0 } : reset;
140
+ return this.updateApprovalConfiguration(
141
+ reference,
142
+ __spreadValues({ expectedRevision, values: {} }, force === void 0 ? {} : { force }),
143
+ options
144
+ );
140
145
  }
141
146
  listApprovalConfigurationHistory(reference, options) {
142
147
  return this.request("GET", `${requirementPath(reference)}/configuration/history`, { options });
@@ -202,6 +207,9 @@ class RestPermissionsClient {
202
207
  getPartnerApprovalCase(caseId, options) {
203
208
  return this.request("GET", `${basePath}/approval-cases/${(0, import_validation.pathSegment)("caseId", caseId)}`, { options });
204
209
  }
210
+ cancelPartnerApprovalCase(caseId, options) {
211
+ return this.request("POST", `${basePath}/approval-cases/${(0, import_validation.pathSegment)("caseId", caseId)}/cancel`, { options });
212
+ }
205
213
  getPartnerPolicyUsage(policyId, context, options) {
206
214
  const _a = context, { userId, walletId } = _a, query = __objRest(_a, ["userId", "walletId"]);
207
215
  const subjectPath = userId ? `users/${(0, import_validation.pathSegment)("userId", userId)}` : `wallets/${(0, import_validation.pathSegment)("walletId", walletId)}`;
@@ -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
+ });
package/dist/esm/index.js CHANGED
@@ -22,6 +22,7 @@ import { RestPermissionsClient } from "./permissions.js";
22
22
  import { ParaRestValidationError, pathSegment, requireBody, requireNonEmpty } from "./validation.js";
23
23
  export * from "./permissions.js";
24
24
  export * from "./webhooks.js";
25
+ export * from "./webhookVerification.js";
25
26
  import { ParaRestValidationError as ParaRestValidationError2 } from "./validation.js";
26
27
  class ParaRestError extends Error {
27
28
  constructor({
@@ -29,7 +30,8 @@ class ParaRestError extends Error {
29
30
  code,
30
31
  requestId,
31
32
  body,
32
- message
33
+ message,
34
+ affectedCaseIds
33
35
  }) {
34
36
  var _a;
35
37
  super((_a = message != null ? message : code) != null ? _a : `Para REST request failed with status ${status}`);
@@ -38,6 +40,7 @@ class ParaRestError extends Error {
38
40
  this.code = code;
39
41
  this.requestId = requestId;
40
42
  this.body = body;
43
+ this.affectedCaseIds = affectedCaseIds;
41
44
  }
42
45
  }
43
46
  class ParaRestSerializationError extends Error {
@@ -246,12 +249,14 @@ class ParaRestClient extends RestPermissionsClient {
246
249
  const parsed = yield parseBody(response);
247
250
  if (!response.ok || expectedStatus != null && response.status !== expectedStatus) {
248
251
  const responseBody = isRecord(parsed) ? parsed : {};
252
+ const affectedCaseIds = responseBody.affectedCaseIds;
249
253
  throw new ParaRestError({
250
254
  status: response.status,
251
255
  code: stringField(responseBody.code),
252
256
  requestId: (_a = response.headers.get("x-request-id")) != null ? _a : requestId,
253
257
  body: parsed,
254
- message: stringField(responseBody.message)
258
+ message: stringField(responseBody.message),
259
+ affectedCaseIds: Array.isArray(affectedCaseIds) && affectedCaseIds.every((caseId) => typeof caseId === "string") ? affectedCaseIds : void 0
255
260
  });
256
261
  }
257
262
  return parsed;
@@ -115,8 +115,13 @@ class RestPermissionsClient {
115
115
  updateApprovalConfiguration(reference, body, options) {
116
116
  return this.request("PUT", `${requirementPath(reference)}/configuration`, { body, options });
117
117
  }
118
- resetApprovalConfiguration(reference, expectedRevision, options) {
119
- return this.updateApprovalConfiguration(reference, { expectedRevision, values: {} }, options);
118
+ resetApprovalConfiguration(reference, reset, options) {
119
+ const { expectedRevision, force } = typeof reset === "number" ? { expectedRevision: reset, force: void 0 } : reset;
120
+ return this.updateApprovalConfiguration(
121
+ reference,
122
+ __spreadValues({ expectedRevision, values: {} }, force === void 0 ? {} : { force }),
123
+ options
124
+ );
120
125
  }
121
126
  listApprovalConfigurationHistory(reference, options) {
122
127
  return this.request("GET", `${requirementPath(reference)}/configuration/history`, { options });
@@ -182,6 +187,9 @@ class RestPermissionsClient {
182
187
  getPartnerApprovalCase(caseId, options) {
183
188
  return this.request("GET", `${basePath}/approval-cases/${pathSegment("caseId", caseId)}`, { options });
184
189
  }
190
+ cancelPartnerApprovalCase(caseId, options) {
191
+ return this.request("POST", `${basePath}/approval-cases/${pathSegment("caseId", caseId)}/cancel`, { options });
192
+ }
185
193
  getPartnerPolicyUsage(policyId, context, options) {
186
194
  const _a = context, { userId, walletId } = _a, query = __objRest(_a, ["userId", "walletId"]);
187
195
  const subjectPath = userId ? `users/${pathSegment("userId", userId)}` : `wallets/${pathSegment("walletId", walletId)}`;
@@ -0,0 +1,132 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { ParaRestValidationError, requireNonEmpty } from "./validation.js";
22
+ const DEFAULT_TOLERANCE_IN_SECONDS = 300;
23
+ const SIGNATURE_PREFIX = "v1,";
24
+ const SECRET_PREFIX = /^whsec_/;
25
+ const WHOLE_SECONDS = /^\d+$/;
26
+ class ParaWebhookVerificationError extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = "ParaWebhookVerificationError";
30
+ }
31
+ }
32
+ function verifyParaWebhook(options) {
33
+ return __async(this, null, function* () {
34
+ var _a;
35
+ requireNonEmpty(options.secret, "secret");
36
+ const toleranceInSeconds = requireValidTolerance((_a = options.toleranceInSeconds) != null ? _a : DEFAULT_TOLERANCE_IN_SECONDS);
37
+ const id = requireHeader(options.headers, "webhook-id");
38
+ const timestamp = requireHeader(options.headers, "webhook-timestamp");
39
+ const signatureHeader = requireHeader(options.headers, "webhook-signature");
40
+ assertTimestampWithinTolerance(timestamp, toleranceInSeconds);
41
+ const body = typeof options.body === "string" ? options.body : new TextDecoder().decode(options.body);
42
+ const expectedSignatures = yield signDelivery({ id, timestamp, body }, options.secret);
43
+ const receivedSignatures = signatureHeader.split(" ").filter((entry) => entry.startsWith(SIGNATURE_PREFIX)).map((entry) => entry.slice(SIGNATURE_PREFIX.length));
44
+ const matches = receivedSignatures.some(
45
+ (received) => expectedSignatures.some((expected) => equalsInConstantTime(expected, received))
46
+ );
47
+ if (!matches) {
48
+ throw new ParaWebhookVerificationError("No matching webhook signature");
49
+ }
50
+ return JSON.parse(body);
51
+ });
52
+ }
53
+ function requireValidTolerance(toleranceInSeconds) {
54
+ if (!Number.isFinite(toleranceInSeconds) || toleranceInSeconds < 0) {
55
+ throw new ParaRestValidationError("toleranceInSeconds must be a finite, non-negative number");
56
+ }
57
+ return toleranceInSeconds;
58
+ }
59
+ function requireHeader(headers, name) {
60
+ var _a;
61
+ const value = isHeaderGetter(headers) ? headers.get(name) : headers[(_a = findHeaderKey(headers, name)) != null ? _a : name];
62
+ if (typeof value !== "string" || value === "") {
63
+ throw new ParaWebhookVerificationError(`Missing ${name} header`);
64
+ }
65
+ return value;
66
+ }
67
+ function isHeaderGetter(headers) {
68
+ return typeof headers.get === "function";
69
+ }
70
+ function findHeaderKey(headers, name) {
71
+ return Object.keys(headers).find((key) => key.toLowerCase() === name);
72
+ }
73
+ function assertTimestampWithinTolerance(timestamp, toleranceInSeconds) {
74
+ if (!WHOLE_SECONDS.test(timestamp)) {
75
+ throw new ParaWebhookVerificationError("Invalid webhook-timestamp header");
76
+ }
77
+ const ageInSeconds = Math.floor(Date.now() / 1e3) - Number(timestamp);
78
+ if (ageInSeconds > toleranceInSeconds) {
79
+ throw new ParaWebhookVerificationError("Webhook timestamp is too old");
80
+ }
81
+ if (-ageInSeconds > toleranceInSeconds) {
82
+ throw new ParaWebhookVerificationError("Webhook timestamp is too new");
83
+ }
84
+ }
85
+ function signDelivery(_0, _1) {
86
+ return __async(this, arguments, function* ({ id, timestamp, body }, secret) {
87
+ const originalSignature = yield signHmacSha256(new TextEncoder().encode(secret), `${timestamp}.${body}`);
88
+ const standardKey = decodeStandardSigningKey(secret);
89
+ if (!standardKey) {
90
+ return [originalSignature];
91
+ }
92
+ return [originalSignature, yield signHmacSha256(standardKey, `${id}.${timestamp}.${body}`)];
93
+ });
94
+ }
95
+ function decodeStandardSigningKey(secret) {
96
+ try {
97
+ const key = Uint8Array.from(atob(secret.replace(SECRET_PREFIX, "")), (character) => character.charCodeAt(0));
98
+ return key.length > 0 ? key : null;
99
+ } catch (e) {
100
+ return null;
101
+ }
102
+ }
103
+ function signHmacSha256(key, message) {
104
+ return __async(this, null, function* () {
105
+ const subtle = requireSubtleCrypto();
106
+ const cryptoKey = yield subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
107
+ const signature = new Uint8Array(yield subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(message)));
108
+ return btoa(String.fromCharCode(...signature));
109
+ });
110
+ }
111
+ function requireSubtleCrypto() {
112
+ var _a;
113
+ const subtle = (_a = globalThis.crypto) == null ? void 0 : _a.subtle;
114
+ if (!subtle) {
115
+ throw new ParaRestValidationError("Web Crypto is required in this runtime to verify webhooks");
116
+ }
117
+ return subtle;
118
+ }
119
+ function equalsInConstantTime(expected, received) {
120
+ if (expected.length !== received.length) {
121
+ return false;
122
+ }
123
+ let difference = 0;
124
+ for (let index = 0; index < expected.length; index++) {
125
+ difference |= expected.charCodeAt(index) ^ received.charCodeAt(index);
126
+ }
127
+ return difference === 0;
128
+ }
129
+ export {
130
+ ParaWebhookVerificationError,
131
+ verifyParaWebhook
132
+ };
@@ -1,7 +1,8 @@
1
- import type { OnrampCompletedPayload, TPregenIdentifierType, TWalletScheme, TWalletType } from '@getpara/shared';
1
+ import type { OnrampCompletedPayload, PermissionsV2SigningInitiatorRequest, TPregenIdentifierType, TWalletScheme, TWalletType } from '@getpara/shared';
2
2
  import { RestPermissionsClient } from './permissions.js';
3
3
  export * from './permissions.js';
4
4
  export * from './webhooks.js';
5
+ export * from './webhookVerification.js';
5
6
  export { ParaRestValidationError } from './validation.js';
6
7
  export type ParaRestEnvironment = 'PROD' | 'BETA' | 'SANDBOX' | {
7
8
  baseUrl: string;
@@ -69,7 +70,8 @@ export interface WalletBalanceResponse {
69
70
  symbol: string;
70
71
  rawBalance: string;
71
72
  }
72
- export interface SignRawRequest {
73
+ export type RestSigningInitiator = PermissionsV2SigningInitiatorRequest;
74
+ export interface SignRawRequest extends RestSigningInitiator {
73
75
  data: string;
74
76
  encoding?: 'hex';
75
77
  walletType?: WalletType;
@@ -77,13 +79,13 @@ export interface SignRawRequest {
77
79
  export interface SignRawResponse {
78
80
  signature: string;
79
81
  }
80
- export interface SignMessageRequest {
82
+ export interface SignMessageRequest extends RestSigningInitiator {
81
83
  message: string;
82
84
  }
83
85
  export interface SignMessageResponse {
84
86
  signature: string;
85
87
  }
86
- export interface SignTransactionRequest {
88
+ export interface SignTransactionRequest extends RestSigningInitiator {
87
89
  transaction: EvmSignTransactionRequest | string;
88
90
  broadcast?: boolean;
89
91
  network?: SolanaNetwork | SuiNetwork;
@@ -115,13 +117,13 @@ export interface TypedDataPayload {
115
117
  primaryType: string;
116
118
  message: Record<string, unknown>;
117
119
  }
118
- export interface SignTypedDataRequest {
120
+ export interface SignTypedDataRequest extends RestSigningInitiator {
119
121
  typedData: TypedDataPayload;
120
122
  }
121
123
  export interface SignTypedDataResponse {
122
124
  signature: string;
123
125
  }
124
- export interface SignAuthorizationRequest {
126
+ export interface SignAuthorizationRequest extends RestSigningInitiator {
125
127
  authorization: SignAuthorizationPayload;
126
128
  }
127
129
  export type SignAuthorizationPayload = ({
@@ -143,7 +145,7 @@ export interface SignAuthorizationResponse {
143
145
  yParity: 0 | 1;
144
146
  signature: string;
145
147
  }
146
- export interface TransferRequest {
148
+ export interface TransferRequest extends RestSigningInitiator {
147
149
  to: string;
148
150
  value: string;
149
151
  chainId?: string | number;
@@ -294,12 +296,18 @@ export declare class ParaRestError extends Error {
294
296
  readonly code?: string;
295
297
  readonly requestId?: string;
296
298
  readonly body: unknown;
297
- constructor({ status, code, requestId, body, message, }: {
299
+ /**
300
+ * The open approval cases a change would invalidate, when the API rejects it with `APPROVAL_CASES_AFFECTED`.
301
+ * Retry the change with `force: true` to apply it anyway.
302
+ */
303
+ readonly affectedCaseIds?: string[];
304
+ constructor({ status, code, requestId, body, message, affectedCaseIds, }: {
298
305
  status: number;
299
306
  code?: string;
300
307
  requestId?: string;
301
308
  body: unknown;
302
309
  message?: string;
310
+ affectedCaseIds?: string[];
303
311
  });
304
312
  }
305
313
  export declare class ParaRestSerializationError extends Error {
@@ -1,6 +1,6 @@
1
- import type { PermissionsV2AuthoritySetHistory, PermissionsV2AuthoritySetView, PermissionsV2AuthoritySetWrite, PermissionsV2AuthorizationConfigurationHistory, PermissionsV2AuthorizationConfigurationView, PermissionsV2AuthorizationConfigurationWrite, PermissionsV2AuthorizationScopeBindingHistory, PermissionsV2AuthorizationScopeBindingView, PermissionsV2AuthorizationScopeBindingWrite, PermissionsV2AuthorizationScopeMembers, PermissionsV2ConditionalApprovalCaseView, PermissionsV2ConditionalApprovalPartnerCaseList, PermissionsV2ConditionalRequirementList, PermissionsV2ConditionalRequirementView, PermissionsV2DelegationConsentDiscoveryResponse, PermissionsV2DelegationConsentView, PermissionsV2EffectiveAuthorizationConfiguration, PermissionsV2PolicyListResponse, PermissionsV2PolicyResponse, PermissionsV2PolicyUsage, PermissionsV2PolicyVersionsResponse, PermissionsV2PolicyView, PermissionsV2UserParameterHistory, PermissionsV2UserParameterView } from '@getpara/shared';
1
+ import type { PermissionsV2AuthoritySetHistory, PermissionsV2AuthoritySetView, PermissionsV2AuthoritySetWrite, PermissionsV2AuthorizationConfigurationHistory, PermissionsV2AuthorizationConfigurationView, PermissionsV2AuthorizationConfigurationWrite, PermissionsV2AuthorizationScopeBindingHistory, PermissionsV2AuthorizationScopeBindingView, PermissionsV2AuthorizationScopeBindingWrite, PermissionsV2AuthorizationScopeMembers, PermissionsV2ConditionalApprovalCaseSummary, PermissionsV2ConditionalApprovalCaseView, PermissionsV2ConditionalApprovalPartnerCaseList, PermissionsV2ConditionalRequirementList, PermissionsV2ConditionalRequirementView, PermissionsV2DelegationConsentDiscoveryResponse, PermissionsV2DelegationConsentView, PermissionsV2EffectiveAuthorizationConfiguration, PermissionsV2PolicyListResponse, PermissionsV2PolicyResponse, PermissionsV2PolicyUsage, PermissionsV2PolicyVersionsResponse, PermissionsV2PolicyView, PermissionsV2UserParameterHistory, PermissionsV2UserParameterView } from '@getpara/shared';
2
2
  import type { ParaRestCallOptions } from './index.js';
3
- export type { PermissionsV2AuthoritySetHistory, PermissionsV2AuthoritySetWrite, PermissionsV2AuthorizationConfigurationHistory, PermissionsV2AuthorizationConfigurationWrite, PermissionsV2AuthorizationScopeBindingHistory, PermissionsV2AuthorizationScopeBindingWrite, PermissionsV2AuthorizationScopeMembers, PermissionsV2ConditionalApprovalPartnerCaseList, PermissionsV2ConditionalRequirementList, PermissionsV2ConditionalRequirementView, PermissionsV2EffectiveAuthorizationConfiguration, PermissionsV2PolicyListResponse, PermissionsV2PolicyResponse, PermissionsV2PolicyUsage, PermissionsV2PolicyUsageMeter, PermissionsV2PolicyVersionsResponse, PermissionsV2PolicyView, } from '@getpara/shared';
3
+ export type { PermissionsV2AuthoritySetHistory, PermissionsV2AuthoritySetWrite, PermissionsV2AuthorizationConfigurationHistory, PermissionsV2AuthorizationConfigurationWrite, PermissionsV2AuthorizationScopeBindingHistory, PermissionsV2AuthorizationScopeBindingWrite, PermissionsV2AuthorizationScopeMembers, PermissionsV2ConditionalApprovalCaseSummary, PermissionsV2ConditionalApprovalPartnerCaseList, PermissionsV2ConditionalRequirementList, PermissionsV2ConditionalRequirementView, PermissionsV2EffectiveAuthorizationConfiguration, PermissionsV2PolicyListResponse, PermissionsV2PolicyResponse, PermissionsV2PolicyUsage, PermissionsV2PolicyUsageMeter, PermissionsV2PolicyVersionsResponse, PermissionsV2PolicyView, } from '@getpara/shared';
4
4
  type PermissionsRequestOptions = {
5
5
  body?: unknown;
6
6
  options?: ParaRestCallOptions;
@@ -13,6 +13,7 @@ export interface PermissionsV2ApprovalRequirementReference {
13
13
  policyVersion: string;
14
14
  requirementId: string;
15
15
  }
16
+ export type PermissionsV2ApprovalConfigurationReset = Omit<PermissionsV2AuthorizationConfigurationWrite, 'values'>;
16
17
  export interface PermissionsV2WalletContext {
17
18
  walletId: string;
18
19
  }
@@ -34,6 +35,7 @@ export interface PermissionsV2PartnerUsageContext extends PermissionsV2WalletCon
34
35
  userId?: string;
35
36
  chainId?: string;
36
37
  tokenAddress?: string;
38
+ safeAddress?: string;
37
39
  }
38
40
  export interface PermissionsV2UserAdjustablePolicyListResponse {
39
41
  policies: PermissionsV2UserParameterView[];
@@ -54,7 +56,7 @@ export declare abstract class RestPermissionsClient {
54
56
  getApprovalConfiguration(reference: PermissionsV2ApprovalRequirementReference, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationConfigurationView>;
55
57
  getEffectiveApprovalConfiguration(reference: PermissionsV2ApprovalRequirementReference, options?: ParaRestCallOptions): Promise<PermissionsV2EffectiveAuthorizationConfiguration>;
56
58
  updateApprovalConfiguration(reference: PermissionsV2ApprovalRequirementReference, body: PermissionsV2AuthorizationConfigurationWrite, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationConfigurationView>;
57
- resetApprovalConfiguration(reference: PermissionsV2ApprovalRequirementReference, expectedRevision: number, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationConfigurationView>;
59
+ resetApprovalConfiguration(reference: PermissionsV2ApprovalRequirementReference, reset: number | PermissionsV2ApprovalConfigurationReset, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationConfigurationView>;
58
60
  listApprovalConfigurationHistory(reference: PermissionsV2ApprovalRequirementReference, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationConfigurationHistory>;
59
61
  getUserApprovalAssignments(authorizationScopeId: string, userId: string, options?: ParaRestCallOptions): Promise<PermissionsV2AuthoritySetView>;
60
62
  listAuthorizationScopeMembers(authorizationScopeId: string, query?: PermissionsV2AuthorizationScopeMemberListOptions, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationScopeMembers>;
@@ -65,5 +67,6 @@ export declare abstract class RestPermissionsClient {
65
67
  listWalletAuthorizationScopeHistory(walletId: string, query?: PermissionsV2HistoryOptions, options?: ParaRestCallOptions): Promise<PermissionsV2AuthorizationScopeBindingHistory>;
66
68
  listPartnerApprovalCases(query?: PermissionsV2CaseListOptions, options?: ParaRestCallOptions): Promise<PermissionsV2ConditionalApprovalPartnerCaseList>;
67
69
  getPartnerApprovalCase(caseId: string, options?: ParaRestCallOptions): Promise<Omit<PermissionsV2ConditionalApprovalCaseView, 'decision'>>;
70
+ cancelPartnerApprovalCase(caseId: string, options?: ParaRestCallOptions): Promise<PermissionsV2ConditionalApprovalCaseSummary>;
68
71
  getPartnerPolicyUsage(policyId: string, context: PermissionsV2PartnerUsageContext, options?: ParaRestCallOptions): Promise<PermissionsV2PolicyUsage>;
69
72
  }
@@ -0,0 +1,42 @@
1
+ import type { WebhookPayloadVersion } from '@getpara/shared';
2
+ import type { RestHeaders } from './index.js';
3
+ import type { ParaWebhookEvent } from './webhooks.js';
4
+ export declare class ParaWebhookVerificationError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /** A Fetch `Headers` object, or a header record such as Node's `IncomingHttpHeaders`. */
8
+ export type ParaWebhookHeaders = RestHeaders | Record<string, string | string[] | undefined>;
9
+ export interface VerifyParaWebhookOptions {
10
+ /** The request body exactly as received, before any JSON parsing. */
11
+ body: string | Uint8Array;
12
+ headers: ParaWebhookHeaders;
13
+ /** The endpoint's signing secret, starting with `whsec_`. */
14
+ secret: string;
15
+ /** How far `webhook-timestamp` may be from the current time, in either direction. Defaults to 300. */
16
+ toleranceInSeconds?: number;
17
+ }
18
+ /**
19
+ * Verifies a webhook delivery from Para and returns its event.
20
+ *
21
+ * Accepts Para's original signature and the Standard Webhooks signature. After a secret rotation, deliveries are
22
+ * signed with both the new and the previous secret for 24 hours, so either secret verifies them.
23
+ *
24
+ * ```ts
25
+ * import { verifyParaWebhook } from '@getpara/rest-sdk';
26
+ *
27
+ * const event = await verifyParaWebhook({
28
+ * body: await request.text(),
29
+ * headers: request.headers,
30
+ * secret: process.env.PARA_WEBHOOK_SECRET!,
31
+ * });
32
+ * if (event.version === 2) {
33
+ * // event.data is a version 2 payload
34
+ * }
35
+ * ```
36
+ *
37
+ * @throws {ParaWebhookVerificationError} when a `webhook-*` header is missing or malformed, the timestamp is outside
38
+ * the tolerance, or no signature matches the secret.
39
+ * @throws {ParaRestValidationError} when the secret is empty, `toleranceInSeconds` is not a finite, non-negative
40
+ * number, or the runtime has no Web Crypto.
41
+ */
42
+ export declare function verifyParaWebhook(options: VerifyParaWebhookOptions): Promise<ParaWebhookEvent<WebhookPayloadVersion>>;
@@ -1,6 +1,6 @@
1
1
  export { WebhookEventType } from '@getpara/shared';
2
- export type { WebhookEvent, WebhookEventPayload, WebhookEventPayloadMap, UserCreatedPayload, WalletCreatedPayload, TransactionSignedPayload, SendBroadcastedPayload, SendConfirmedPayload, SendFailedPayload, RestTransactionConfirmedPayload, RestTransactionFailedPayload, WalletPregenClaimedPayload, UserExternalWalletVerifiedPayload, OnrampCompletedPayload, UserTwoFactorResetPayload, FundsReceivedPayload, TestPingPayload, } from '@getpara/shared';
3
- import type { WebhookEventPayloadMap } from '@getpara/shared';
2
+ export type { WebhookEvent, WebhookEventPayload, WebhookEventPayloadMap, WebhookPayloadVersion, WebhookEventPayloadV2, WebhookEventPayloadMapV2, WebhookError, CaipNetwork, UserCreatedPayload, WalletCreatedPayload, TransactionSignedPayload, SendBroadcastedPayload, SendConfirmedPayload, SendFailedPayload, RestTransactionConfirmedPayload, RestTransactionFailedPayload, WalletPregenClaimedPayload, UserExternalWalletVerifiedPayload, OnrampCompletedPayload, UserTwoFactorResetPayload, FundsReceivedPayload, TestPingPayload, UserCreatedPayloadV2, WalletCreatedPayloadV2, TransactionSignedPayloadV2, SendBroadcastedPayloadV2, SendConfirmedPayloadV2, SendFailedPayloadV2, RestTransactionConfirmedPayloadV2, RestTransactionFailedPayloadV2, WalletPregenClaimedPayloadV2, UserExternalWalletVerifiedPayloadV2, OnrampCompletedPayloadV2, UserTwoFactorResetPayloadV2, FundsReceivedPayloadV2, TestPingPayloadV2, } from '@getpara/shared';
3
+ import type { WebhookEventPayloadMap, WebhookEventPayloadMapV2, WebhookPayloadVersion } from '@getpara/shared';
4
4
  /**
5
5
  * A received webhook, as a discriminated union over the event type.
6
6
  *
@@ -8,7 +8,9 @@ import type { WebhookEventPayloadMap } from '@getpara/shared';
8
8
  * uncorrelated, so `data` stays the union of every payload no matter what `type` says. This maps each event type to
9
9
  * its own payload, so a `switch` on `event.type` narrows `event.data` to the matching shape.
10
10
  *
11
- * Derived from `WebhookEventPayloadMap`, so it picks up new event types automatically.
11
+ * Derived from `WebhookEventPayloadMap` and `WebhookEventPayloadMapV2`, so it picks up new event types automatically.
12
+ * It describes version 1 payloads by default. Use `ParaWebhookEvent<2>` for an endpoint set to payload version 2, or
13
+ * `ParaWebhookEvent<1 | 2>` and check `event.version` when either can arrive.
12
14
  *
13
15
  * ```ts
14
16
  * import { WebhookEventType, type ParaWebhookEvent } from '@getpara/rest-sdk';
@@ -25,18 +27,39 @@ import type { WebhookEventPayloadMap } from '@getpara/shared';
25
27
  * }
26
28
  * ```
27
29
  */
28
- export type ParaWebhookEvent = {
29
- [K in keyof WebhookEventPayloadMap]: {
30
- /** Unique event id, prefixed with `evt_`. */
31
- id: string;
32
- type: K;
33
- /** ISO 8601 timestamp of when the event was created. */
34
- createdAt: string;
35
- data: WebhookEventPayloadMap[K];
36
- };
37
- }[keyof WebhookEventPayloadMap];
30
+ export type ParaWebhookEvent<Version extends WebhookPayloadVersion = 1> = ParaWebhookEventsByVersion[Version];
38
31
  /**
39
32
  * The payload for a given event type — e.g. `ParaWebhookPayload<WebhookEventType.ONRAMP_COMPLETED>`. Useful for
40
- * typing a per-event handler without restating the payload interface's name.
33
+ * typing a per-event handler without restating the payload interface's name. Pass `2` as the second argument for an
34
+ * endpoint that receives version 2 payloads.
41
35
  */
42
- export type ParaWebhookPayload<K extends keyof WebhookEventPayloadMap> = WebhookEventPayloadMap[K];
36
+ export type ParaWebhookPayload<K extends keyof WebhookEventPayloadMap, Version extends WebhookPayloadVersion = 1> = WebhookPayloadMapsByVersion[Version][K];
37
+ interface WebhookPayloadMapsByVersion {
38
+ 1: WebhookEventPayloadMap;
39
+ 2: WebhookEventPayloadMapV2;
40
+ }
41
+ interface ParaWebhookEventsByVersion {
42
+ 1: {
43
+ [K in keyof WebhookEventPayloadMap]: {
44
+ /** Unique event id, prefixed with `evt_`. */
45
+ id: string;
46
+ type: K;
47
+ /** ISO 8601 timestamp of when the event was created. */
48
+ createdAt: string;
49
+ /** Absent on deliveries sent before payload versions existed. */
50
+ version?: 1;
51
+ data: WebhookEventPayloadMap[K];
52
+ };
53
+ }[keyof WebhookEventPayloadMap];
54
+ 2: {
55
+ [K in keyof WebhookEventPayloadMapV2]: {
56
+ /** Unique event id, prefixed with `evt_`. */
57
+ id: string;
58
+ type: K;
59
+ /** ISO 8601 timestamp of when the event was created. */
60
+ createdAt: string;
61
+ version: 2;
62
+ data: WebhookEventPayloadMapV2[K];
63
+ };
64
+ }[keyof WebhookEventPayloadMapV2];
65
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getpara/rest-sdk",
3
- "version": "3.22.0",
3
+ "version": "3.24.0",
4
4
  "description": "Typed server-side SDK for Para REST wallet management and signing",
5
5
  "author": "Para Team <hello@getpara.com> (https://getpara.com)",
6
6
  "homepage": "https://docs.getpara.com/v3/rest/sdk",
@@ -27,7 +27,7 @@
27
27
  "vitest": "^3.2.4"
28
28
  },
29
29
  "dependencies": {
30
- "@getpara/shared": "^1.35.0"
30
+ "@getpara/shared": "^1.38.0"
31
31
  },
32
32
  "exports": {
33
33
  ".": {
@@ -111,5 +111,5 @@
111
111
  }
112
112
  },
113
113
  "typings": "dist/types/index.d.ts",
114
- "gitHead": "4ca50a0fc70e11370595f16daad0f1ac4da0edbc"
114
+ "gitHead": "205cf865b2dff48339a919ecaa46aab3da211218"
115
115
  }