@reclaimprotocol/js-sdk 1.3.11 → 2.0.1

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/index.js CHANGED
@@ -67,7 +67,9 @@ var __async = (__this, __arguments, generator) => {
67
67
  // src/index.ts
68
68
  var src_exports = {};
69
69
  __export(src_exports, {
70
- Reclaim: () => Reclaim
70
+ ReclaimProofRequest: () => ReclaimProofRequest,
71
+ transformForOnchain: () => transformForOnchain,
72
+ verifyProof: () => verifyProof
71
73
  });
72
74
  module.exports = __toCommonJS(src_exports);
73
75
 
@@ -122,16 +124,266 @@ function createSignDataForClaim(data) {
122
124
  }
123
125
 
124
126
  // src/Reclaim.ts
125
- var import_uuid = require("uuid");
126
- var import_ethers5 = require("ethers");
127
+ var import_ethers6 = require("ethers");
127
128
  var import_canonicalize2 = __toESM(require("canonicalize"));
128
129
 
129
- // src/utils.ts
130
- var import_url_parse = __toESM(require("url-parse"));
131
- var import_ethers4 = require("ethers");
130
+ // src/utils/errors.ts
131
+ function createErrorClass(name) {
132
+ return class extends Error {
133
+ constructor(message, innerError) {
134
+ super(message);
135
+ this.innerError = innerError;
136
+ this.name = name;
137
+ if (innerError) {
138
+ this.stack += `
139
+ Caused by: ${innerError.stack}`;
140
+ }
141
+ }
142
+ };
143
+ }
144
+ var TimeoutError = createErrorClass("TimeoutError");
145
+ var ProofNotVerifiedError = createErrorClass("ProofNotVerifiedError");
146
+ var SessionNotStartedError = createErrorClass("SessionNotStartedError");
147
+ var ProviderNotFoundError = createErrorClass("ProviderNotFoundError");
148
+ var BuildProofRequestError = createErrorClass("BuildProofRequestError");
149
+ var SignatureGeneratingError = createErrorClass("SignatureGeneratingError");
150
+ var SignatureNotFoundError = createErrorClass("SignatureNotFoundError");
151
+ var InvalidSignatureError = createErrorClass("InvalidSignatureError");
152
+ var UpdateSessionError = createErrorClass("UpdateSessionError");
153
+ var InitSessionError = createErrorClass("InitSessionError");
154
+ var ProviderFailedError = createErrorClass("ProviderFailedError");
155
+ var InvalidParamError = createErrorClass("InvalidParamError");
156
+ var ApplicationError = createErrorClass("ApplicationError");
157
+ var InitError = createErrorClass("InitError");
158
+ var AvailableParamsError = createErrorClass("AvailableParamsError");
159
+ var BackendServerError = createErrorClass("BackendServerError");
160
+ var GetStatusUrlError = createErrorClass("GetStatusUrlError");
161
+ var NoProviderParamsError = createErrorClass("NoProviderParamsError");
162
+ var SetParamsError = createErrorClass("SetParamsError");
163
+ var AddContextError = createErrorClass("AddContextError");
164
+ var SetSignatureError = createErrorClass("SetSignatureError");
165
+ var GetAppCallbackUrlError = createErrorClass("GetAppCallbackUrlError");
166
+ var GetRequestUrlError = createErrorClass("GetRequestUrlError");
132
167
 
133
- // src/contract-types/contracts/factories/Reclaim__factory.ts
168
+ // src/utils/logger.ts
169
+ var SimpleLogger = class {
170
+ constructor() {
171
+ this.level = "info";
172
+ }
173
+ setLevel(level) {
174
+ this.level = level;
175
+ }
176
+ shouldLog(messageLevel) {
177
+ const levels = ["error", "warn", "info", "silent"];
178
+ return levels.indexOf(this.level) >= levels.indexOf(messageLevel);
179
+ }
180
+ log(level, message, ...args) {
181
+ if (this.shouldLog(level) && this.level !== "silent") {
182
+ const logFunction = this.getLogFunction(level);
183
+ console.log("current level", this.level);
184
+ logFunction(`[${level.toUpperCase()}]`, message, ...args);
185
+ }
186
+ }
187
+ getLogFunction(level) {
188
+ switch (level) {
189
+ case "error":
190
+ return console.error;
191
+ case "warn":
192
+ return console.warn;
193
+ case "info":
194
+ return console.info;
195
+ default:
196
+ return () => {
197
+ };
198
+ }
199
+ }
200
+ info(message, ...args) {
201
+ this.log("info", message, ...args);
202
+ }
203
+ warn(message, ...args) {
204
+ this.log("warn", message, ...args);
205
+ }
206
+ error(message, ...args) {
207
+ this.log("error", message, ...args);
208
+ }
209
+ };
210
+ var logger = new SimpleLogger();
211
+ function setLogLevel(level) {
212
+ logger.setLevel(level);
213
+ }
214
+ var logger_default = {
215
+ logger,
216
+ setLogLevel
217
+ };
218
+
219
+ // src/utils/helper.ts
220
+ var logger2 = logger_default.logger;
221
+ function escapeRegExp(string) {
222
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
223
+ }
224
+ function replaceAll(str, find, replace) {
225
+ if (find === "") return str;
226
+ return str.replace(new RegExp(escapeRegExp(find), "g"), replace);
227
+ }
228
+ function scheduleIntervalEndingTask(sessionId, intervals, onFailureCallback, timeout = 1e3 * 60 * 10) {
229
+ setTimeout(() => {
230
+ if (intervals.has(sessionId)) {
231
+ const message = "Interval ended without receiving proofs";
232
+ onFailureCallback(new TimeoutError(message));
233
+ logger2.info(message);
234
+ clearInterval(intervals.get(sessionId));
235
+ intervals.delete(sessionId);
236
+ }
237
+ }, timeout);
238
+ }
239
+
240
+ // src/utils/constants.ts
241
+ var BACKEND_BASE_URL = "https://api.reclaimprotocol.org";
242
+ var constants = {
243
+ // Default callback URL for Reclaim protocol
244
+ DEFAULT_RECLAIM_CALLBACK_URL: `${BACKEND_BASE_URL}/api/sdk/callback?callbackId=`,
245
+ // Default status URL for Reclaim sessions
246
+ DEFAULT_RECLAIM_STATUS_URL: `${BACKEND_BASE_URL}/api/sdk/session/`,
247
+ // URL for sharing Reclaim templates
248
+ RECLAIM_SHARE_URL: "https://share.reclaimprotocol.org/verifier/?template="
249
+ };
250
+
251
+ // src/utils/validationUtils.ts
134
252
  var import_ethers2 = require("ethers");
253
+ var import_canonicalize = __toESM(require("canonicalize"));
254
+ var logger3 = logger_default.logger;
255
+ function validateFunctionParams(params, functionName) {
256
+ params.forEach(({ input, paramName, isString }) => {
257
+ if (input == null) {
258
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is null or undefined`);
259
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`);
260
+ }
261
+ if (isString && typeof input !== "string") {
262
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is not a string`);
263
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`);
264
+ }
265
+ if (isString && input.trim() === "") {
266
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is an empty string`);
267
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must not be an empty string.`);
268
+ }
269
+ });
270
+ }
271
+ function validateURL(url, functionName) {
272
+ try {
273
+ new URL(url);
274
+ } catch (e) {
275
+ logger3.info(`URL validation failed for ${url} in ${functionName}: ${e.message}`);
276
+ throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e);
277
+ }
278
+ }
279
+ function validateSignature(providerId, signature, applicationId, timestamp) {
280
+ try {
281
+ logger3.info(`Starting signature validation for providerId: ${providerId}, applicationId: ${applicationId}, timestamp: ${timestamp}`);
282
+ const message = (0, import_canonicalize.default)({ providerId, timestamp });
283
+ if (!message) {
284
+ logger3.info("Failed to canonicalize message for signature validation");
285
+ throw new Error("Failed to canonicalize message");
286
+ }
287
+ const messageHash = import_ethers2.ethers.keccak256(new TextEncoder().encode(message));
288
+ let appId = import_ethers2.ethers.verifyMessage(
289
+ import_ethers2.ethers.getBytes(messageHash),
290
+ import_ethers2.ethers.hexlify(signature)
291
+ ).toLowerCase();
292
+ if (import_ethers2.ethers.getAddress(appId) !== import_ethers2.ethers.getAddress(applicationId)) {
293
+ logger3.info(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`);
294
+ throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`);
295
+ }
296
+ logger3.info(`Signature validated successfully for applicationId: ${applicationId}`);
297
+ } catch (err) {
298
+ logger3.info(`Signature validation failed: ${err.message}`);
299
+ if (err instanceof InvalidSignatureError) {
300
+ throw err;
301
+ }
302
+ throw new InvalidSignatureError(`Failed to validate signature: ${err.message}`);
303
+ }
304
+ }
305
+ function validateRequestedProof(requestedProof) {
306
+ if (!requestedProof.url) {
307
+ logger3.info(`Requested proof validation failed: Provided url in requested proof is not valid`);
308
+ throw new InvalidParamError(`The provided url in requested proof is not valid`);
309
+ }
310
+ if (requestedProof.parameters && typeof requestedProof.parameters !== "object") {
311
+ logger3.info(`Requested proof validation failed: Provided parameters in requested proof is not valid`);
312
+ throw new InvalidParamError(`The provided parameters in requested proof is not valid`);
313
+ }
314
+ }
315
+ function validateContext(context) {
316
+ if (!context.contextAddress) {
317
+ logger3.info(`Context validation failed: Provided context address in context is not valid`);
318
+ throw new InvalidParamError(`The provided context address in context is not valid`);
319
+ }
320
+ if (!context.contextMessage) {
321
+ logger3.info(`Context validation failed: Provided context message in context is not valid`);
322
+ throw new InvalidParamError(`The provided context message in context is not valid`);
323
+ }
324
+ validateFunctionParams([
325
+ { input: context.contextAddress, paramName: "contextAddress", isString: true },
326
+ { input: context.contextMessage, paramName: "contextMessage", isString: true }
327
+ ], "validateContext");
328
+ }
329
+
330
+ // src/utils/sessionUtils.ts
331
+ var logger4 = logger_default.logger;
332
+ function initSession(providerId, appId, timestamp, signature) {
333
+ return __async(this, null, function* () {
334
+ logger4.info(`Initializing session for providerId: ${providerId}, appId: ${appId}`);
335
+ try {
336
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/init-session/`, {
337
+ method: "POST",
338
+ headers: { "Content-Type": "application/json" },
339
+ body: JSON.stringify({ providerId, appId, timestamp, signature })
340
+ });
341
+ const res = yield response.json();
342
+ if (!response.ok) {
343
+ logger4.info(`Session initialization failed: ${res.message || "Unknown error"}`);
344
+ throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`);
345
+ }
346
+ return res;
347
+ } catch (err) {
348
+ logger4.info(`Failed to initialize session for providerId: ${providerId}, appId: ${appId}`, err);
349
+ throw err;
350
+ }
351
+ });
352
+ }
353
+ function updateSession(sessionId, status) {
354
+ return __async(this, null, function* () {
355
+ logger4.info(`Updating session status for sessionId: ${sessionId}, new status: ${status}`);
356
+ validateFunctionParams(
357
+ [{ input: sessionId, paramName: "sessionId", isString: true }],
358
+ "updateSession"
359
+ );
360
+ try {
361
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/update/session/`, {
362
+ method: "POST",
363
+ headers: { "Content-Type": "application/json" },
364
+ body: JSON.stringify({ sessionId, status })
365
+ });
366
+ const res = yield response.json();
367
+ if (!response.ok) {
368
+ const errorMessage = `Error updating session with sessionId: ${sessionId}. Status Code: ${response.status}`;
369
+ logger4.info(errorMessage, res);
370
+ throw new UpdateSessionError(errorMessage);
371
+ }
372
+ logger4.info(`Session status updated successfully for sessionId: ${sessionId}`);
373
+ return res;
374
+ } catch (err) {
375
+ const errorMessage = `Failed to update session with sessionId: ${sessionId}`;
376
+ logger4.info(errorMessage, err);
377
+ throw new UpdateSessionError(`Error updating session with sessionId: ${sessionId}`);
378
+ }
379
+ });
380
+ }
381
+
382
+ // src/utils/proofUtils.ts
383
+ var import_ethers5 = require("ethers");
384
+
385
+ // src/contract-types/contracts/factories/Reclaim__factory.ts
386
+ var import_ethers3 = require("ethers");
135
387
  var _abi = [
136
388
  {
137
389
  anonymous: false,
@@ -668,7 +920,7 @@ var _abi = [
668
920
  ];
669
921
  var Reclaim__factory = class {
670
922
  static connect(address, signerOrProvider) {
671
- return new import_ethers2.Contract(address, _abi, signerOrProvider);
923
+ return new import_ethers3.Contract(address, _abi, signerOrProvider);
672
924
  }
673
925
  };
674
926
  Reclaim__factory.abi = _abi;
@@ -688,7 +940,7 @@ var config_default = {
688
940
  };
689
941
 
690
942
  // src/smart-contract.ts
691
- var import_ethers3 = require("ethers");
943
+ var import_ethers4 = require("ethers");
692
944
  var DEFAULT_CHAIN_ID = 11155420;
693
945
  function makeBeacon(chainId) {
694
946
  chainId = chainId || DEFAULT_CHAIN_ID;
@@ -744,7 +996,7 @@ function getContract(chainId) {
744
996
  if (!contractData) {
745
997
  throw new Error(`Unsupported chain: "${chainKey}"`);
746
998
  }
747
- const rpcProvider = new import_ethers3.ethers.JsonRpcProvider(contractData.rpcUrl);
999
+ const rpcProvider = new import_ethers4.ethers.JsonRpcProvider(contractData.rpcUrl);
748
1000
  existingContractsMap[chainKey] = Reclaim__factory.connect(
749
1001
  contractData.address,
750
1002
  rpcProvider
@@ -753,372 +1005,114 @@ function getContract(chainId) {
753
1005
  return existingContractsMap[chainKey];
754
1006
  }
755
1007
 
756
- // src/utils.ts
757
- var import_canonicalize = __toESM(require("canonicalize"));
758
-
759
- // src/constants.ts
760
- var BACKEND_BASE_URL = "https://api.reclaimprotocol.org";
761
- var constants = {
762
- GET_PROVIDERS_BY_ID_API: BACKEND_BASE_URL + "/api/applications",
763
- DEFAULT_RECLAIM_CALLBACK_URL: BACKEND_BASE_URL + "/api/sdk/callback?callbackId=",
764
- DEFAULT_RECLAIM_STATUS_URL: BACKEND_BASE_URL + "/api/sdk/session/",
765
- RECLAIM_SHARE_URL: "https://share.reclaimprotocol.org/instant/?template=",
766
- RECLAIM_GET_BRANCH_URL: BACKEND_BASE_URL + "/api/sdk/get-branch-url"
767
- };
768
-
769
- // src/errors.ts
770
- var TimeoutError = class extends Error {
771
- constructor(message) {
772
- super(message);
773
- this.name = "TimeoutError";
774
- }
775
- };
776
- var ProofNotVerifiedError = class extends Error {
777
- constructor(message) {
778
- super(message);
779
- this.name = "ProofNotVerifiedError";
780
- }
781
- };
782
- var SessionNotStartedError = class extends Error {
783
- constructor(message) {
784
- super(message);
785
- this.name = "SessionNotStartedError";
786
- }
787
- };
788
- var ProviderAPIError = class extends Error {
789
- constructor(message) {
790
- super(message);
791
- this.name = "ProviderAPIError";
792
- }
793
- };
794
- var BuildProofRequestError = class extends Error {
795
- constructor(message) {
796
- super(message);
797
- this.name = "BuildProofRequest";
798
- }
799
- };
800
- var SignatureNotFoundError = class extends Error {
801
- constructor(message) {
802
- super(message);
803
- this.name = "SignatureNotFound";
804
- }
805
- };
806
- var InvalidSignatureError = class extends Error {
807
- constructor(message) {
808
- super(message);
809
- this.name = "InvalidSignatureError";
810
- }
811
- };
812
- var UpdateSessionError = class extends Error {
813
- constructor(message) {
814
- super(message);
815
- this.name = "UpdateSessionError";
816
- }
817
- };
818
- var CreateSessionError = class extends Error {
819
- constructor(message) {
820
- super(message);
821
- this.name = "CreateSessionError";
822
- }
823
- };
824
- var ProviderFailedError = class extends Error {
825
- constructor(message) {
826
- super(message);
827
- this.name = "ProviderFailedError";
828
- }
829
- };
830
- var InvalidParamError = class extends Error {
831
- constructor(message) {
832
- super(message);
833
- this.name = "InvalidParamError";
834
- }
835
- };
836
- var ApplicationError = class extends Error {
837
- constructor(message) {
838
- super(message);
839
- this.name = "ApplicationError";
840
- }
841
- };
842
-
843
- // src/utils.ts
844
- function validateNotNullOrUndefined(input, paramName, functionName) {
845
- if (input == null) {
846
- throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`);
847
- }
848
- }
849
- function validateNonEmptyString(input, paramName, functionName) {
850
- if (typeof input !== "string") {
851
- throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`);
852
- }
853
- if (input.trim() === "") {
854
- throw new InvalidParamError(`${paramName} passed to ${functionName} must be a non-empty string.`);
855
- }
856
- }
857
- function validateURL(url, functionName) {
858
- validateNotNullOrUndefined(url, "url", functionName);
859
- validateNonEmptyString(url, "url", functionName);
860
- try {
861
- new import_url_parse.default(url);
862
- } catch (e) {
863
- throw new InvalidParamError(`Invalid URL format passed to ${functionName}.`);
864
- }
865
- }
866
- function getWitnessesForClaim(epoch, identifier, timestampS) {
867
- return __async(this, null, function* () {
868
- const beacon = makeBeacon();
869
- if (!beacon)
870
- throw new Error("No beacon");
871
- const state = yield beacon.getState(epoch);
872
- const witnessList = fetchWitnessListForClaim(state, identifier, timestampS);
873
- return witnessList.map((w) => w.id.toLowerCase());
874
- });
875
- }
876
- function recoverSignersOfSignedClaim({
877
- claim,
878
- signatures
879
- }) {
880
- const dataStr = createSignDataForClaim(__spreadValues({}, claim));
881
- return signatures.map(
882
- (signature) => import_ethers4.ethers.verifyMessage(dataStr, import_ethers4.ethers.hexlify(signature)).toLowerCase()
1008
+ // src/utils/proofUtils.ts
1009
+ var logger5 = logger_default.logger;
1010
+ function generateRequestedProof(provider) {
1011
+ const providerParams = {};
1012
+ provider.responseSelections.forEach(
1013
+ (rs) => rs.responseMatch.split(/{{(.*?)}}/).filter((_, i) => i % 2).forEach((param) => providerParams[param] = "")
883
1014
  );
1015
+ const proof = {
1016
+ url: provider.url,
1017
+ parameters: providerParams
1018
+ };
1019
+ return proof;
884
1020
  }
885
- function assertValidSignedClaim(claim, expectedWitnessAddresses) {
886
- const witnessAddresses = recoverSignersOfSignedClaim(claim);
887
- const witnessesNotSeen = new Set(expectedWitnessAddresses);
888
- for (const witness of witnessAddresses) {
889
- if (witnessesNotSeen.has(witness)) {
890
- witnessesNotSeen.delete(witness);
1021
+ function getFilledParameters(requestedProof) {
1022
+ return Object.keys(requestedProof.parameters).reduce((acc, param) => {
1023
+ if (requestedProof.parameters[param]) {
1024
+ acc[param] = requestedProof.parameters[param];
891
1025
  }
892
- }
893
- if (witnessesNotSeen.size > 0) {
894
- throw new ProofNotVerifiedError(
895
- `Missing signatures from ${expectedWitnessAddresses.join(", ")}`
896
- );
897
- }
1026
+ return acc;
1027
+ }, {});
898
1028
  }
899
1029
  function getShortenedUrl(url) {
900
1030
  return __async(this, null, function* () {
1031
+ logger5.info(`Attempting to shorten URL: ${url}`);
901
1032
  try {
902
1033
  validateURL(url, "getShortenedUrl");
903
- const response = yield fetch(BACKEND_BASE_URL + "/api/sdk/shortener", {
1034
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/shortener`, {
904
1035
  method: "POST",
905
- headers: {
906
- "Content-Type": "application/json"
907
- },
908
- body: JSON.stringify({
909
- fullUrl: url
910
- })
1036
+ headers: { "Content-Type": "application/json" },
1037
+ body: JSON.stringify({ fullUrl: url })
911
1038
  });
912
1039
  const res = yield response.json();
1040
+ if (!response.ok) {
1041
+ logger5.info(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);
1042
+ return url;
1043
+ }
913
1044
  const shortenedVerificationUrl = res.result.shortUrl;
914
1045
  return shortenedVerificationUrl;
915
1046
  } catch (err) {
1047
+ logger5.info(`Error shortening URL: ${url}, Error: ${err}`);
916
1048
  return url;
917
1049
  }
918
1050
  });
919
1051
  }
920
- function createSession(sessionId, appId, providerId) {
1052
+ function createLinkWithTemplateData(templateData) {
921
1053
  return __async(this, null, function* () {
922
- validateNotNullOrUndefined(sessionId, "sessionId", "createSession");
923
- validateNotNullOrUndefined(appId, "appId", "createSession");
924
- validateNotNullOrUndefined(providerId, "providerId", "createSession");
925
- validateNonEmptyString(sessionId, "sessionId", "createSession");
926
- validateNonEmptyString(appId, "appId", "createSession");
927
- validateNonEmptyString(providerId, "providerId", "createSession");
1054
+ let template = encodeURIComponent(JSON.stringify(templateData));
1055
+ template = replaceAll(template, "(", "%28");
1056
+ template = replaceAll(template, ")", "%29");
1057
+ const fullLink = `${constants.RECLAIM_SHARE_URL}${template}`;
928
1058
  try {
929
- const response = yield fetch(BACKEND_BASE_URL + "/api/sdk/create-session/", {
930
- method: "POST",
931
- headers: {
932
- "Content-Type": "application/json"
933
- },
934
- body: JSON.stringify({
935
- sessionId,
936
- appId,
937
- providerId
938
- })
939
- });
940
- if (!response.ok) {
941
- throw new CreateSessionError("Error creating session with sessionId: " + sessionId);
942
- }
943
- const res = yield response.json();
944
- return res;
1059
+ const shortenedLink = yield getShortenedUrl(fullLink);
1060
+ return shortenedLink;
945
1061
  } catch (err) {
946
- throw new CreateSessionError("Error creating session with sessionId: " + sessionId);
1062
+ logger5.info(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);
1063
+ return fullLink;
947
1064
  }
948
1065
  });
949
1066
  }
950
- function updateSession(sessionId, status) {
951
- return __async(this, null, function* () {
952
- validateNotNullOrUndefined(sessionId, "sessionId", "updateSession");
953
- validateNonEmptyString(sessionId, "sessionId", "updateSession");
954
- try {
955
- const response = yield fetch(BACKEND_BASE_URL + "/api/sdk/update/session/", {
956
- method: "POST",
957
- headers: {
958
- "Content-Type": "application/json"
959
- },
960
- body: JSON.stringify({
961
- sessionId,
962
- status
963
- })
964
- });
965
- if (!response.ok) {
966
- throw new UpdateSessionError("Error updating session with sessionId: " + sessionId);
967
- }
968
- const res = yield response.json();
969
- return res;
970
- } catch (err) {
971
- throw new UpdateSessionError("Error updating session with sessionId: " + sessionId);
972
- }
973
- });
974
- }
975
- function fetchProvidersByAppId(appId, providerId) {
1067
+ function getWitnessesForClaim(epoch, identifier, timestampS) {
976
1068
  return __async(this, null, function* () {
977
- try {
978
- const response = yield fetch(`${constants.GET_PROVIDERS_BY_ID_API}/${appId}/provider/${providerId}`);
979
- if (response.status === 404) {
980
- throw new ApplicationError("Application not found with AppId: " + appId);
981
- }
982
- if (response.status !== 200) {
983
- throw new Error();
984
- }
985
- const res = yield response.json();
986
- return res.providers.httpProvider;
987
- } catch (err) {
988
- if (err instanceof ApplicationError) {
989
- throw err;
990
- }
991
- throw new ProviderAPIError("Error fetching provider with AppId: " + appId);
1069
+ const beacon = makeBeacon();
1070
+ if (!beacon) {
1071
+ logger5.info("No beacon available for getting witnesses");
1072
+ throw new Error("No beacon available");
992
1073
  }
1074
+ const state = yield beacon.getState(epoch);
1075
+ const witnessList = fetchWitnessListForClaim(state, identifier, timestampS);
1076
+ const witnesses = witnessList.map((w) => w.id.toLowerCase());
1077
+ return witnesses;
993
1078
  });
994
1079
  }
995
- function validateProviderIdsAndReturnProviders(providerId, providers) {
996
- let providerExists = providers.some((provider) => providerId == provider.httpProviderId);
997
- if (!providerExists) {
998
- throw new ProviderAPIError(`The following provider Id is not included in your application => ${providerId}`);
999
- }
1000
- return providers.find((provider) => providerId == provider.httpProviderId);
1001
- }
1002
- function generateRequestedProofs(provider, context, callbackUrl, statusUrl, sessionId, redirectUser) {
1003
- const providerParams = {};
1004
- provider.responseSelections.forEach((rs) => rs.responseMatch.split(/{{(.*?)}}/).filter((e, i) => i % 2).forEach((param) => providerParams[param] = void 0));
1005
- const claims = [{
1006
- provider: encodeURIComponent(provider.name),
1007
- context: JSON.stringify(context),
1008
- httpProviderId: provider.httpProviderId,
1009
- payload: {
1010
- metadata: {
1011
- name: encodeURIComponent(provider.name),
1012
- logoUrl: provider.logoUrl,
1013
- proofCardText: provider.proofCardText,
1014
- proofCardTitle: provider.proofCardTitle
1015
- },
1016
- url: provider.url,
1017
- urlType: provider.urlType,
1018
- method: provider.method,
1019
- login: {
1020
- url: provider.loginUrl
1021
- },
1022
- responseSelections: provider.responseSelections,
1023
- customInjection: provider.customInjection,
1024
- bodySniff: provider.bodySniff,
1025
- userAgent: provider.userAgent,
1026
- geoLocation: provider.geoLocation,
1027
- matchType: provider.matchType,
1028
- injectionType: provider.injectionType,
1029
- disableRequestReplay: provider.disableRequestReplay,
1030
- verificationType: provider.verificationType,
1031
- parameters: providerParams
1032
- }
1033
- }];
1034
- return {
1035
- id: sessionId,
1036
- sessionId,
1037
- name: redirectUser ? "web-r-SDK" : "web-SDK",
1038
- callbackUrl,
1039
- statusUrl,
1040
- claims
1041
- };
1080
+ function recoverSignersOfSignedClaim({
1081
+ claim,
1082
+ signatures
1083
+ }) {
1084
+ const dataStr = createSignDataForClaim(__spreadValues({}, claim));
1085
+ const signers = signatures.map(
1086
+ (signature) => import_ethers5.ethers.verifyMessage(dataStr, import_ethers5.ethers.hexlify(signature)).toLowerCase()
1087
+ );
1088
+ return signers;
1042
1089
  }
1043
- function validateSignature(requestedProofs, signature, applicationId, linkingVersion, timeStamp) {
1044
- var _a, _b;
1045
- try {
1046
- let appId = "";
1047
- if (requestedProofs.claims.length && (linkingVersion === "V2Linking" || ((_b = (_a = requestedProofs.claims[0]) == null ? void 0 : _a.payload) == null ? void 0 : _b.verificationType) === "MANUAL")) {
1048
- appId = import_ethers4.ethers.verifyMessage(
1049
- import_ethers4.ethers.getBytes(
1050
- import_ethers4.ethers.keccak256(
1051
- new TextEncoder().encode((0, import_canonicalize.default)({
1052
- providerId: requestedProofs.claims[0].httpProviderId,
1053
- timestamp: timeStamp
1054
- }))
1055
- )
1056
- ),
1057
- import_ethers4.ethers.hexlify(signature)
1058
- ).toLowerCase();
1059
- } else {
1060
- appId = import_ethers4.ethers.verifyMessage(
1061
- import_ethers4.ethers.getBytes(
1062
- import_ethers4.ethers.keccak256(
1063
- new TextEncoder().encode((0, import_canonicalize.default)(requestedProofs))
1064
- )
1065
- ),
1066
- import_ethers4.ethers.hexlify(signature)
1067
- ).toLowerCase();
1068
- }
1069
- if (import_ethers4.ethers.getAddress(appId) !== import_ethers4.ethers.getAddress(applicationId)) {
1070
- throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`);
1090
+ function assertValidSignedClaim(claim, expectedWitnessAddresses) {
1091
+ const witnessAddresses = recoverSignersOfSignedClaim(claim);
1092
+ const witnessesNotSeen = new Set(expectedWitnessAddresses);
1093
+ for (const witness of witnessAddresses) {
1094
+ if (witnessesNotSeen.has(witness)) {
1095
+ witnessesNotSeen.delete(witness);
1071
1096
  }
1072
- } catch (err) {
1073
- throw err;
1074
1097
  }
1075
- }
1076
- function escapeRegExp(string) {
1077
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1078
- }
1079
- function replaceAll(str, find, replace) {
1080
- return str.replace(new RegExp(escapeRegExp(find), "g"), replace);
1081
- }
1082
- function getBranchLink(template) {
1083
- return __async(this, null, function* () {
1084
- try {
1085
- const options = {
1086
- method: "POST",
1087
- headers: { accept: "application/json", "content-type": "application/json" },
1088
- body: JSON.stringify({
1089
- template
1090
- })
1091
- };
1092
- const response = yield fetch(constants.RECLAIM_GET_BRANCH_URL, options);
1093
- if (response.status !== 200) {
1094
- throw new Error(
1095
- "Error creating verification request - Branch Link not created"
1096
- );
1097
- }
1098
- const data = yield response.json();
1099
- const link = data == null ? void 0 : data.branchUrl;
1100
- if (!link) {
1101
- throw new Error(
1102
- "Error creating verification request - Branch Link not created"
1103
- );
1104
- }
1105
- return link;
1106
- } catch (err) {
1107
- throw err;
1108
- }
1109
- });
1098
+ if (witnessesNotSeen.size > 0) {
1099
+ const missingWitnesses = Array.from(witnessesNotSeen).join(", ");
1100
+ logger5.info(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);
1101
+ throw new ProofNotVerifiedError(
1102
+ `Missing signatures from ${missingWitnesses}`
1103
+ );
1104
+ }
1110
1105
  }
1111
1106
 
1112
1107
  // src/Reclaim.ts
1113
- var import_pino = __toESM(require("pino"));
1114
- var logger = (0, import_pino.default)();
1115
- var _Reclaim = class _Reclaim {
1116
- static verifySignedProof(proof) {
1117
- return __async(this, null, function* () {
1118
- var _a;
1119
- if (!proof.signatures.length) {
1120
- throw new Error("No signatures");
1121
- }
1108
+ var logger6 = logger_default.logger;
1109
+ function verifyProof(proof) {
1110
+ return __async(this, null, function* () {
1111
+ var _a;
1112
+ if (!proof.signatures.length) {
1113
+ throw new SignatureNotFoundError("No signatures");
1114
+ }
1115
+ try {
1122
1116
  let witnesses = [];
1123
1117
  if (proof.witnesses.length && ((_a = proof.witnesses[0]) == null ? void 0 : _a.url) === "manual-verify") {
1124
1118
  witnesses.push(proof.witnesses[0].id);
@@ -1129,358 +1123,362 @@ var _Reclaim = class _Reclaim {
1129
1123
  proof.claimData.timestampS
1130
1124
  );
1131
1125
  }
1132
- try {
1133
- const calculatedIdentifier = getIdentifierFromClaimInfo({
1134
- parameters: JSON.parse(
1135
- (0, import_canonicalize2.default)(proof.claimData.parameters)
1136
- ),
1137
- provider: proof.claimData.provider,
1138
- context: proof.claimData.context
1139
- });
1140
- proof.identifier = replaceAll(proof.identifier, '"', "");
1141
- if (calculatedIdentifier !== proof.identifier) {
1142
- throw new ProofNotVerifiedError("Identifier Mismatch");
1143
- }
1144
- const signedClaim = {
1145
- claim: __spreadValues({}, proof.claimData),
1146
- signatures: proof.signatures.map((signature) => {
1147
- return import_ethers5.ethers.getBytes(signature);
1148
- })
1149
- };
1150
- assertValidSignedClaim(signedClaim, witnesses);
1151
- } catch (e) {
1152
- logger.error(e);
1153
- return false;
1154
- }
1155
- return true;
1156
- });
1157
- }
1158
- static transformForOnchain(proof) {
1159
- const claimInfoBuilder = /* @__PURE__ */ new Map([
1160
- ["context", proof.claimData.context],
1161
- ["parameters", proof.claimData.parameters],
1162
- ["provider", proof.claimData.provider]
1163
- ]);
1164
- const claimInfo = Object.fromEntries(claimInfoBuilder);
1165
- const claimBuilder = /* @__PURE__ */ new Map([
1166
- ["epoch", proof.claimData.epoch],
1167
- ["identifier", proof.claimData.identifier],
1168
- ["owner", proof.claimData.owner],
1169
- ["timestampS", proof.claimData.timestampS]
1170
- ]);
1171
- const signedClaim = {
1172
- claim: Object.fromEntries(claimBuilder),
1173
- signatures: proof.signatures
1174
- };
1175
- return { claimInfo, signedClaim };
1176
- }
1177
- static verifyProvider(proof, providerHash) {
1178
- try {
1179
- validateNotNullOrUndefined(providerHash, "applicationId", "verifyProvider function");
1180
- validateNotNullOrUndefined(proof, "proof", "verifyProvider function");
1181
- validateNonEmptyString(providerHash, "applicationId", "verifyProvider function");
1182
- validateNonEmptyString(proof.claimData.context, "context", "verifyProvider function");
1183
- const jsonContext = JSON.parse(proof.claimData.context);
1184
- if (!jsonContext.providerHash) {
1185
- logger.info(`ProviderHash is not included in proof's context`);
1186
- return false;
1187
- }
1188
- if (providerHash !== jsonContext.providerHash) {
1189
- logger.info(`ProviderHash in context: ${jsonContext.providerHash} does not match the stored providerHash: ${providerHash}`);
1190
- return false;
1126
+ const calculatedIdentifier = getIdentifierFromClaimInfo({
1127
+ parameters: JSON.parse(
1128
+ (0, import_canonicalize2.default)(proof.claimData.parameters)
1129
+ ),
1130
+ provider: proof.claimData.provider,
1131
+ context: proof.claimData.context
1132
+ });
1133
+ proof.identifier = replaceAll(proof.identifier, '"', "");
1134
+ if (calculatedIdentifier !== proof.identifier) {
1135
+ throw new ProofNotVerifiedError("Identifier Mismatch");
1191
1136
  }
1192
- return true;
1137
+ const signedClaim = {
1138
+ claim: __spreadValues({}, proof.claimData),
1139
+ signatures: proof.signatures.map((signature) => {
1140
+ return import_ethers6.ethers.getBytes(signature);
1141
+ })
1142
+ };
1143
+ assertValidSignedClaim(signedClaim, witnesses);
1193
1144
  } catch (e) {
1194
- logger.error(e);
1145
+ logger6.info(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`);
1195
1146
  return false;
1196
1147
  }
1197
- }
1198
- };
1199
- _Reclaim.ProofRequest = class {
1200
- constructor(applicationId, options) {
1148
+ return true;
1149
+ });
1150
+ }
1151
+ function transformForOnchain(proof) {
1152
+ const claimInfoBuilder = /* @__PURE__ */ new Map([
1153
+ ["context", proof.claimData.context],
1154
+ ["parameters", proof.claimData.parameters],
1155
+ ["provider", proof.claimData.provider]
1156
+ ]);
1157
+ const claimInfo = Object.fromEntries(claimInfoBuilder);
1158
+ const claimBuilder = /* @__PURE__ */ new Map([
1159
+ ["epoch", proof.claimData.epoch],
1160
+ ["identifier", proof.claimData.identifier],
1161
+ ["owner", proof.claimData.owner],
1162
+ ["timestampS", proof.claimData.timestampS]
1163
+ ]);
1164
+ const signedClaim = {
1165
+ claim: Object.fromEntries(claimBuilder),
1166
+ signatures: proof.signatures
1167
+ };
1168
+ return { claimInfo, signedClaim };
1169
+ }
1170
+ var ReclaimProofRequest = class _ReclaimProofRequest {
1171
+ // Private constructor
1172
+ constructor(applicationId, providerId, options) {
1201
1173
  this.context = { contextAddress: "0x0", contextMessage: "" };
1202
1174
  this.intervals = /* @__PURE__ */ new Map();
1203
- validateNotNullOrUndefined(applicationId, "applicationId", "the constructor");
1204
- validateNonEmptyString(applicationId, "applicationId", "the constructor");
1205
- if (options == null ? void 0 : options.sessionId) {
1206
- validateNonEmptyString(options == null ? void 0 : options.sessionId, "sessionId", "the constructor");
1207
- }
1208
- this.linkingVersion = "V1";
1209
- this.applicationId = applicationId;
1210
- this.sessionId = (options == null ? void 0 : options.sessionId) || (0, import_uuid.v4)().toString();
1211
- logger.level = (options == null ? void 0 : options.log) ? "info" : "silent";
1212
- logger.info(
1213
- `Initializing client with applicationId: ${this.applicationId} and sessionId: ${this.sessionId}`
1214
- );
1175
+ this.providerId = providerId;
1215
1176
  this.timeStamp = Date.now().toString();
1177
+ this.applicationId = applicationId;
1178
+ this.sessionId = "";
1179
+ if (options == null ? void 0 : options.log) {
1180
+ logger_default.setLogLevel("info");
1181
+ } else {
1182
+ logger_default.setLogLevel("silent");
1183
+ }
1184
+ this.options = options;
1185
+ logger6.info(`Initializing client with applicationId: ${this.applicationId}`);
1216
1186
  }
1217
- addContext(address, message) {
1218
- validateNotNullOrUndefined(address, "address", "addContext");
1219
- validateNotNullOrUndefined(message, "message", "addContext");
1220
- this.context = { contextAddress: address, contextMessage: message };
1187
+ // Static initialization methods
1188
+ static init(applicationId, appSecret, providerId, options) {
1189
+ return __async(this, null, function* () {
1190
+ try {
1191
+ validateFunctionParams([
1192
+ { paramName: "applicationId", input: applicationId, isString: true },
1193
+ { paramName: "providerId", input: providerId, isString: true },
1194
+ { paramName: "appSecret", input: appSecret, isString: true }
1195
+ ], "the constructor");
1196
+ if (options) {
1197
+ if (options.acceptAiProviders) {
1198
+ validateFunctionParams([
1199
+ { paramName: "acceptAiProviders", input: options.acceptAiProviders }
1200
+ ], "the constructor");
1201
+ }
1202
+ if (options.log) {
1203
+ validateFunctionParams([
1204
+ { paramName: "log", input: options.log }
1205
+ ], "the constructor");
1206
+ }
1207
+ }
1208
+ const proofRequestInstance = new _ReclaimProofRequest(applicationId, providerId, options);
1209
+ const signature = yield proofRequestInstance.generateSignature(appSecret);
1210
+ proofRequestInstance.setSignature(signature);
1211
+ const data = yield initSession(providerId, applicationId, proofRequestInstance.timeStamp, signature);
1212
+ proofRequestInstance.sessionId = data.sessionId;
1213
+ yield proofRequestInstance.buildProofRequest(data.provider);
1214
+ return proofRequestInstance;
1215
+ } catch (error) {
1216
+ logger6.info("Failed to initialize ReclaimProofRequest", error);
1217
+ throw new InitError("Failed to initialize ReclaimProofRequest", error);
1218
+ }
1219
+ });
1220
+ }
1221
+ static fromJsonString(jsonString) {
1222
+ return __async(this, null, function* () {
1223
+ try {
1224
+ const {
1225
+ applicationId,
1226
+ providerId,
1227
+ sessionId,
1228
+ context,
1229
+ requestedProof,
1230
+ signature,
1231
+ redirectUrl,
1232
+ timeStamp,
1233
+ appCallbackUrl,
1234
+ options
1235
+ } = JSON.parse(jsonString);
1236
+ validateFunctionParams([
1237
+ { input: applicationId, paramName: "applicationId", isString: true },
1238
+ { input: providerId, paramName: "providerId", isString: true },
1239
+ { input: signature, paramName: "signature", isString: true },
1240
+ { input: sessionId, paramName: "sessionId", isString: true },
1241
+ { input: timeStamp, paramName: "timeStamp", isString: true }
1242
+ ], "fromJsonString");
1243
+ validateRequestedProof(requestedProof);
1244
+ if (redirectUrl) {
1245
+ validateURL(redirectUrl, "fromJsonString");
1246
+ }
1247
+ if (appCallbackUrl) {
1248
+ validateURL(appCallbackUrl, "fromJsonString");
1249
+ }
1250
+ if (context) {
1251
+ validateContext(context);
1252
+ }
1253
+ const proofRequestInstance = new _ReclaimProofRequest(applicationId, providerId, options);
1254
+ proofRequestInstance.sessionId = sessionId;
1255
+ proofRequestInstance.context = context;
1256
+ proofRequestInstance.requestedProof = requestedProof;
1257
+ proofRequestInstance.appCallbackUrl = appCallbackUrl;
1258
+ proofRequestInstance.redirectUrl = redirectUrl;
1259
+ proofRequestInstance.timeStamp = timeStamp;
1260
+ proofRequestInstance.signature = signature;
1261
+ return proofRequestInstance;
1262
+ } catch (error) {
1263
+ logger6.info("Failed to parse JSON string in fromJsonString:", error);
1264
+ throw new InvalidParamError("Invalid JSON string provided to fromJsonString");
1265
+ }
1266
+ });
1221
1267
  }
1268
+ // Setter methods
1222
1269
  setAppCallbackUrl(url) {
1223
1270
  validateURL(url, "setAppCallbackUrl");
1224
- const urlObj = new URL(url);
1225
- urlObj.searchParams.append("callbackId", this.sessionId);
1226
- this.appCallbackUrl = urlObj.toString();
1271
+ this.appCallbackUrl = url;
1227
1272
  }
1228
1273
  setRedirectUrl(url) {
1229
1274
  validateURL(url, "setRedirectUrl");
1230
- const urlObj = new URL(url);
1231
- this.redirectUrl = urlObj.toString();
1275
+ this.redirectUrl = url;
1232
1276
  }
1233
- setStatusUrl(url) {
1234
- validateURL(url, "setStatusUrl");
1235
- this.statusUrl = url;
1277
+ addContext(address, message) {
1278
+ try {
1279
+ validateFunctionParams([
1280
+ { input: address, paramName: "address", isString: true },
1281
+ { input: message, paramName: "message", isString: true }
1282
+ ], "addContext");
1283
+ this.context = { contextAddress: address, contextMessage: message };
1284
+ } catch (error) {
1285
+ logger6.info("Error adding context", error);
1286
+ throw new AddContextError("Error adding context", error);
1287
+ }
1236
1288
  }
1237
- setSignature(signature) {
1238
- validateNotNullOrUndefined(signature, "signature", "setSignature");
1239
- validateNonEmptyString(signature, "signature", "setSignature");
1240
- this.signature = signature;
1289
+ setParams(params) {
1290
+ try {
1291
+ const requestedProof = this.getRequestedProof();
1292
+ if (!requestedProof || !this.requestedProof) {
1293
+ throw new BuildProofRequestError("Requested proof is not present.");
1294
+ }
1295
+ const currentParams = this.availableParams();
1296
+ if (!currentParams) {
1297
+ throw new NoProviderParamsError("No params present in the provider config.");
1298
+ }
1299
+ const paramsToSet = Object.keys(params);
1300
+ for (const param of paramsToSet) {
1301
+ if (!currentParams.includes(param)) {
1302
+ throw new InvalidParamError(
1303
+ `Cannot set parameter ${param} for provider ${this.providerId}. Available parameters: ${currentParams}`
1304
+ );
1305
+ }
1306
+ }
1307
+ this.requestedProof.parameters = __spreadValues(__spreadValues({}, requestedProof.parameters), params);
1308
+ } catch (error) {
1309
+ logger6.info("Error Setting Params:", error);
1310
+ throw new SetParamsError("Error setting params", error);
1311
+ }
1241
1312
  }
1313
+ // Getter methods
1242
1314
  getAppCallbackUrl() {
1243
- return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;
1315
+ try {
1316
+ validateFunctionParams([{ input: this.sessionId, paramName: "sessionId", isString: true }], "getAppCallbackUrl");
1317
+ return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;
1318
+ } catch (error) {
1319
+ logger6.info("Error getting app callback url", error);
1320
+ throw new GetAppCallbackUrlError("Error getting app callback url", error);
1321
+ }
1244
1322
  }
1245
1323
  getStatusUrl() {
1246
- return this.statusUrl || `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`;
1324
+ try {
1325
+ validateFunctionParams([{ input: this.sessionId, paramName: "sessionId", isString: true }], "getStatusUrl");
1326
+ return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`;
1327
+ } catch (error) {
1328
+ logger6.info("Error fetching Status Url", error);
1329
+ throw new GetStatusUrlError("Error fetching status url", error);
1330
+ }
1247
1331
  }
1248
- getRequestedProofs() {
1332
+ // Private helper methods
1333
+ setSignature(signature) {
1249
1334
  try {
1250
- if (!this.requestedProofs) {
1251
- throw new BuildProofRequestError(
1252
- "Call buildProofRequest(providerId: string) first!"
1253
- );
1254
- }
1255
- return this.requestedProofs;
1256
- } catch (err) {
1257
- throw err;
1335
+ validateFunctionParams([{ input: signature, paramName: "signature", isString: true }], "setSignature");
1336
+ this.signature = signature;
1337
+ logger6.info(`Signature set successfully for applicationId: ${this.applicationId}`);
1338
+ } catch (error) {
1339
+ logger6.info("Error setting signature", error);
1340
+ throw new SetSignatureError("Error setting signature", error);
1258
1341
  }
1259
1342
  }
1260
1343
  generateSignature(applicationSecret) {
1261
1344
  return __async(this, null, function* () {
1262
- var _a, _b;
1263
1345
  try {
1264
- const wallet = new import_ethers5.ethers.Wallet(applicationSecret);
1265
- const requestedProofs = this.getRequestedProofs();
1266
- if (requestedProofs.claims.length && (this.linkingVersion === "V2Linking" || ((_b = (_a = requestedProofs.claims[0]) == null ? void 0 : _a.payload) == null ? void 0 : _b.verificationType) === "MANUAL")) {
1267
- const signature2 = yield wallet.signMessage(
1268
- import_ethers5.ethers.getBytes(
1269
- import_ethers5.ethers.keccak256(
1270
- new TextEncoder().encode(
1271
- (0, import_canonicalize2.default)({
1272
- providerId: requestedProofs.claims[0].httpProviderId,
1273
- timestamp: this.timeStamp
1274
- })
1275
- )
1276
- )
1277
- )
1278
- );
1279
- return signature2;
1346
+ const wallet = new import_ethers6.ethers.Wallet(applicationSecret);
1347
+ const canonicalData = (0, import_canonicalize2.default)({ providerId: this.providerId, timestamp: this.timeStamp });
1348
+ if (!canonicalData) {
1349
+ throw new SignatureGeneratingError("Failed to canonicalize data for signing.");
1280
1350
  }
1281
- const signature = yield wallet.signMessage(
1282
- import_ethers5.ethers.getBytes(
1283
- import_ethers5.ethers.keccak256(
1284
- new TextEncoder().encode(
1285
- (0, import_canonicalize2.default)(requestedProofs)
1286
- )
1287
- )
1288
- )
1289
- );
1290
- return signature;
1351
+ const messageHash = import_ethers6.ethers.keccak256(new TextEncoder().encode(canonicalData));
1352
+ return yield wallet.signMessage(import_ethers6.ethers.getBytes(messageHash));
1291
1353
  } catch (err) {
1292
- logger.error(err);
1293
- throw new BuildProofRequestError(
1294
- "Error generating signature for applicationSecret: " + applicationSecret
1295
- );
1354
+ logger6.info(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);
1355
+ throw new SignatureGeneratingError(`Error generating signature for applicationSecret: ${applicationSecret}`);
1296
1356
  }
1297
1357
  });
1298
1358
  }
1299
- buildProofRequest(providerId, redirectUser = false, linkingVersion) {
1359
+ buildProofRequest(provider) {
1300
1360
  return __async(this, null, function* () {
1301
- let providers = yield fetchProvidersByAppId(this.applicationId, providerId);
1302
- const provider = validateProviderIdsAndReturnProviders(
1303
- providerId,
1304
- providers
1305
- );
1306
1361
  try {
1307
- this.providerId = providerId;
1308
- this.requestedProofs = generateRequestedProofs(
1309
- provider,
1310
- this.context,
1311
- this.getAppCallbackUrl(),
1312
- this.getStatusUrl(),
1313
- this.sessionId,
1314
- redirectUser
1315
- );
1316
- if (linkingVersion) {
1317
- if (linkingVersion === "V2Linking") {
1318
- this.linkingVersion = linkingVersion;
1319
- } else {
1320
- throw new BuildProofRequestError(
1321
- "Invalid linking version. Supported linking versions are V2Linking"
1322
- );
1323
- }
1324
- }
1325
- yield createSession(this.sessionId, this.applicationId, providerId);
1326
- return this.requestedProofs;
1362
+ this.requestedProof = generateRequestedProof(provider);
1363
+ return this.requestedProof;
1327
1364
  } catch (err) {
1328
- logger.error(err);
1329
- throw new BuildProofRequestError(
1330
- "Something went wrong while generating proof request"
1331
- );
1365
+ logger6.info(err instanceof Error ? err.message : String(err));
1366
+ throw new BuildProofRequestError("Something went wrong while generating proof request", err);
1332
1367
  }
1333
1368
  });
1334
1369
  }
1335
- createVerificationRequest() {
1370
+ getRequestedProof() {
1371
+ if (!this.requestedProof) {
1372
+ throw new BuildProofRequestError("RequestedProof is not present in the instance.");
1373
+ }
1374
+ return this.requestedProof;
1375
+ }
1376
+ availableParams() {
1377
+ try {
1378
+ const requestedProofs = this.getRequestedProof();
1379
+ let availableParamsStore = Object.keys(requestedProofs.parameters);
1380
+ availableParamsStore = availableParamsStore.concat(requestedProofs.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1381
+ return [...new Set(availableParamsStore)];
1382
+ } catch (error) {
1383
+ logger6.info("Error fetching available params", error);
1384
+ throw new AvailableParamsError("Error fetching available params", error);
1385
+ }
1386
+ }
1387
+ clearInterval() {
1388
+ if (this.sessionId && this.intervals.has(this.sessionId)) {
1389
+ clearInterval(this.intervals.get(this.sessionId));
1390
+ this.intervals.delete(this.sessionId);
1391
+ }
1392
+ }
1393
+ // Public methods
1394
+ toJsonString(options) {
1395
+ return JSON.stringify({
1396
+ applicationId: this.applicationId,
1397
+ providerId: this.providerId,
1398
+ sessionId: this.sessionId,
1399
+ context: this.context,
1400
+ requestedProof: this.requestedProof,
1401
+ appCallbackUrl: this.appCallbackUrl,
1402
+ signature: this.signature,
1403
+ redirectUrl: this.redirectUrl,
1404
+ timeStamp: this.timeStamp,
1405
+ options: this.options
1406
+ });
1407
+ }
1408
+ getRequestUrl() {
1336
1409
  return __async(this, null, function* () {
1337
- var _a, _b, _c, _d, _e;
1410
+ var _a, _b, _c;
1411
+ logger6.info("Creating Request Url");
1412
+ if (!this.signature) {
1413
+ throw new SignatureNotFoundError("Signature is not set.");
1414
+ }
1338
1415
  try {
1339
- const requestedProofs = yield this.getRequestedProofs();
1340
- if (!requestedProofs) {
1341
- throw new BuildProofRequestError(
1342
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1343
- );
1344
- }
1345
- if (!this.signature) {
1346
- throw new SignatureNotFoundError(
1347
- "Signature is not set. Use reclaim.setSignature(signature) to set the signature"
1348
- );
1349
- }
1350
- validateSignature(requestedProofs, this.signature, this.applicationId, this.linkingVersion, this.timeStamp);
1351
- let templateData = {};
1352
- if (requestedProofs.claims.length && (this.linkingVersion === "V2Linking" || ((_b = (_a = requestedProofs.claims[0]) == null ? void 0 : _a.payload) == null ? void 0 : _b.verificationType) === "MANUAL")) {
1353
- templateData = {
1354
- sessionId: this.sessionId,
1355
- providerId: this.providerId,
1356
- applicationId: this.applicationId,
1357
- signature: this.signature,
1358
- timestamp: this.timeStamp,
1359
- callbackUrl: this.getAppCallbackUrl(),
1360
- context: JSON.stringify(this.context),
1361
- verificationType: requestedProofs.claims[0].payload.verificationType,
1362
- parameters: requestedProofs.claims[0].payload.parameters,
1363
- redirectUrl: (_c = this.redirectUrl) != null ? _c : ""
1364
- };
1365
- } else {
1366
- templateData = __spreadProps(__spreadValues({}, requestedProofs), {
1367
- signature: this.signature
1368
- });
1369
- }
1370
- let template = encodeURIComponent(
1371
- JSON.stringify(templateData)
1372
- );
1373
- template = replaceAll(template, "(", "%28");
1374
- template = replaceAll(template, ")", "%29");
1375
- let link = "";
1376
- if (requestedProofs.claims.length && (this.linkingVersion === "V2Linking" || ((_e = (_d = requestedProofs.claims[0]) == null ? void 0 : _d.payload) == null ? void 0 : _e.verificationType) === "MANUAL")) {
1377
- link = `https://share.reclaimprotocol.org/verifier?template=` + template;
1378
- link = yield getShortenedUrl(link);
1379
- } else {
1380
- link = yield getBranchLink(template);
1381
- }
1416
+ const requestedProof = this.getRequestedProof();
1417
+ validateSignature(this.providerId, this.signature, this.applicationId, this.timeStamp);
1418
+ const templateData = {
1419
+ sessionId: this.sessionId,
1420
+ providerId: this.providerId,
1421
+ applicationId: this.applicationId,
1422
+ signature: this.signature,
1423
+ timestamp: this.timeStamp,
1424
+ callbackUrl: this.getAppCallbackUrl(),
1425
+ context: JSON.stringify(this.context),
1426
+ parameters: getFilledParameters(requestedProof),
1427
+ redirectUrl: (_a = this.redirectUrl) != null ? _a : "",
1428
+ acceptAiProviders: (_c = (_b = this.options) == null ? void 0 : _b.acceptAiProviders) != null ? _c : false
1429
+ };
1430
+ const link = yield createLinkWithTemplateData(templateData);
1431
+ logger6.info("Request Url created successfully: " + link);
1382
1432
  yield updateSession(this.sessionId, "SESSION_STARTED" /* SESSION_STARTED */);
1383
- return { requestUrl: link, statusUrl: this.getStatusUrl() };
1433
+ return link;
1384
1434
  } catch (error) {
1385
- logger.error("Error creating verification request:", error);
1435
+ logger6.info("Error creating Request Url:", error);
1386
1436
  throw error;
1387
1437
  }
1388
1438
  });
1389
1439
  }
1390
1440
  startSession(_0) {
1391
- return __async(this, arguments, function* ({
1392
- onSuccessCallback,
1393
- onFailureCallback
1394
- }) {
1441
+ return __async(this, arguments, function* ({ onSuccess, onError }) {
1395
1442
  const statusUrl = this.getStatusUrl();
1396
- if (statusUrl && this.sessionId) {
1397
- logger.info("Starting session");
1398
- const interval = setInterval(() => __async(this, null, function* () {
1399
- try {
1400
- const res = yield fetch(statusUrl);
1401
- const data = yield res.json();
1402
- if (!data.session)
1403
- return;
1404
- if (data.session.status === "PROOF_GENERATION_FAILED" /* PROOF_GENERATION_FAILED */)
1405
- throw new ProviderFailedError();
1406
- if (data.session.proofs.length === 0)
1407
- return;
1408
- const proof = data.session.proofs[0];
1409
- const verified = yield _Reclaim.verifySignedProof(proof);
1410
- if (!verified) {
1411
- throw new ProofNotVerifiedError();
1412
- }
1413
- if (onSuccessCallback) {
1414
- onSuccessCallback(data.session.proofs);
1415
- }
1416
- clearInterval(this.intervals.get(this.sessionId));
1417
- this.intervals.delete(this.sessionId);
1418
- } catch (e) {
1419
- if (onFailureCallback) {
1420
- onFailureCallback(e);
1421
- }
1422
- clearInterval(this.intervals.get(this.sessionId));
1423
- this.intervals.delete(this.sessionId);
1424
- }
1425
- }), 3e3);
1426
- this.intervals.set(this.sessionId, interval);
1427
- this.scheduleIntervalEndingTask(onFailureCallback);
1428
- } else {
1443
+ if (!statusUrl || !this.sessionId) {
1429
1444
  const message = "Session can't be started due to undefined value of statusUrl and sessionId";
1430
- logger.error(message);
1445
+ logger6.info(message);
1431
1446
  throw new SessionNotStartedError(message);
1432
1447
  }
1433
- });
1434
- }
1435
- scheduleIntervalEndingTask(onFailureCallback) {
1436
- setTimeout(() => __async(this, null, function* () {
1437
- if (this.intervals.has(this.sessionId)) {
1438
- const message = "Interval ended without receiveing proofs";
1439
- onFailureCallback(new TimeoutError(message));
1440
- logger.warn(message);
1441
- clearInterval(this.intervals.get(this.sessionId));
1442
- }
1443
- }), 1e3 * 60 * 10);
1444
- }
1445
- availableParams() {
1446
- const requestedProofs = this.getRequestedProofs();
1447
- if (!requestedProofs || !this.requestedProofs) {
1448
- throw new BuildProofRequestError(
1449
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1450
- );
1451
- }
1452
- let availableParamsStore = Object.keys(requestedProofs.claims[0].payload.parameters);
1453
- availableParamsStore = availableParamsStore.concat(requestedProofs.claims[0].payload.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1454
- availableParamsStore = availableParamsStore.concat(requestedProofs.claims[0].payload.login.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1455
- return [...new Set(availableParamsStore)];
1456
- }
1457
- setParams(params) {
1458
- try {
1459
- const requestedProofs = this.getRequestedProofs();
1460
- if (!requestedProofs || !this.requestedProofs) {
1461
- throw new BuildProofRequestError(
1462
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1463
- );
1464
- }
1465
- const availableParams = this.availableParams();
1466
- const paramsToSet = Object.keys(params);
1467
- for (let i = 0; i < paramsToSet.length; i++) {
1468
- if (requestedProofs.claims[0].payload.verificationType === "WITNESS" && !availableParams.includes(paramsToSet[i])) {
1469
- throw new InvalidParamError(
1470
- `Cannot Set parameter ${paramsToSet[i]} for provider ${this.providerId} available Prameters inculde : ${availableParams}`
1471
- );
1448
+ logger6.info("Starting session");
1449
+ const interval = setInterval(() => __async(this, null, function* () {
1450
+ try {
1451
+ const res = yield fetch(statusUrl);
1452
+ const data = yield res.json();
1453
+ if (!data.session) return;
1454
+ if (data.session.status === "PROOF_GENERATION_FAILED" /* PROOF_GENERATION_FAILED */) throw new ProviderFailedError();
1455
+ if (data.session.proofs.length === 0) return;
1456
+ const proof = data.session.proofs[0];
1457
+ const verified = yield verifyProof(proof);
1458
+ if (!verified) {
1459
+ logger6.info(`Proof not verified: ${proof}`);
1460
+ throw new ProofNotVerifiedError();
1461
+ }
1462
+ if (onSuccess) {
1463
+ onSuccess(proof);
1464
+ }
1465
+ this.clearInterval();
1466
+ } catch (e) {
1467
+ if (onError) {
1468
+ onError(e);
1469
+ }
1470
+ this.clearInterval();
1472
1471
  }
1473
- }
1474
- this.requestedProofs.claims[0].payload.parameters = __spreadValues(__spreadValues({}, requestedProofs.claims[0].payload.parameters), params);
1475
- } catch (error) {
1476
- logger.error("Error Setting Params:", error);
1477
- throw error;
1478
- }
1472
+ }), 3e3);
1473
+ this.intervals.set(this.sessionId, interval);
1474
+ scheduleIntervalEndingTask(this.sessionId, this.intervals, onError);
1475
+ });
1479
1476
  }
1480
1477
  };
1481
- var Reclaim = _Reclaim;
1482
1478
  // Annotate the CommonJS export names for ESM import in node:
1483
1479
  0 && (module.exports = {
1484
- Reclaim
1480
+ ReclaimProofRequest,
1481
+ transformForOnchain,
1482
+ verifyProof
1485
1483
  });
1486
1484
  //# sourceMappingURL=index.js.map