@reclaimprotocol/js-sdk 1.3.10 → 2.0.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/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,241 @@ 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 import_pino = __toESM(require("pino"));
170
+ var logger = (0, import_pino.default)({
171
+ level: "info",
172
+ transport: {
173
+ target: "pino-pretty",
174
+ options: {
175
+ colorize: true
176
+ }
177
+ }
178
+ });
179
+ function setLogLevel(level) {
180
+ logger.level = level;
181
+ }
182
+ var logger_default = {
183
+ logger,
184
+ setLogLevel
185
+ };
186
+
187
+ // src/utils/helper.ts
188
+ var logger2 = logger_default.logger;
189
+ function escapeRegExp(string) {
190
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
191
+ }
192
+ function replaceAll(str, find, replace) {
193
+ if (find === "")
194
+ return str;
195
+ return str.replace(new RegExp(escapeRegExp(find), "g"), replace);
196
+ }
197
+ function scheduleIntervalEndingTask(sessionId, intervals, onFailureCallback, timeout = 1e3 * 60 * 10) {
198
+ setTimeout(() => {
199
+ if (intervals.has(sessionId)) {
200
+ const message = "Interval ended without receiving proofs";
201
+ onFailureCallback(new TimeoutError(message));
202
+ logger2.info(message);
203
+ clearInterval(intervals.get(sessionId));
204
+ intervals.delete(sessionId);
205
+ }
206
+ }, timeout);
207
+ }
208
+
209
+ // src/utils/constants.ts
210
+ var BACKEND_BASE_URL = "https://api.reclaimprotocol.org";
211
+ var constants = {
212
+ // Default callback URL for Reclaim protocol
213
+ DEFAULT_RECLAIM_CALLBACK_URL: `${BACKEND_BASE_URL}/api/sdk/callback?callbackId=`,
214
+ // Default status URL for Reclaim sessions
215
+ DEFAULT_RECLAIM_STATUS_URL: `${BACKEND_BASE_URL}/api/sdk/session/`,
216
+ // URL for sharing Reclaim templates
217
+ RECLAIM_SHARE_URL: "https://share.reclaimprotocol.org/verifier/?template="
218
+ };
219
+
220
+ // src/utils/validationUtils.ts
134
221
  var import_ethers2 = require("ethers");
222
+ var import_canonicalize = __toESM(require("canonicalize"));
223
+ var logger3 = logger_default.logger;
224
+ function validateFunctionParams(params, functionName) {
225
+ params.forEach(({ input, paramName, isString }) => {
226
+ if (input == null) {
227
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is null or undefined`);
228
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must not be null or undefined.`);
229
+ }
230
+ if (isString && typeof input !== "string") {
231
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is not a string`);
232
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must be a string.`);
233
+ }
234
+ if (isString && input.trim() === "") {
235
+ logger3.info(`Validation failed: ${paramName} in ${functionName} is an empty string`);
236
+ throw new InvalidParamError(`${paramName} passed to ${functionName} must not be an empty string.`);
237
+ }
238
+ });
239
+ }
240
+ function validateURL(url, functionName) {
241
+ try {
242
+ new URL(url);
243
+ } catch (e) {
244
+ logger3.info(`URL validation failed for ${url} in ${functionName}: ${e.message}`);
245
+ throw new InvalidParamError(`Invalid URL format ${url} passed to ${functionName}.`, e);
246
+ }
247
+ }
248
+ function validateSignature(providerId, signature, applicationId, timestamp) {
249
+ try {
250
+ logger3.info(`Starting signature validation for providerId: ${providerId}, applicationId: ${applicationId}, timestamp: ${timestamp}`);
251
+ const message = (0, import_canonicalize.default)({ providerId, timestamp });
252
+ if (!message) {
253
+ logger3.info("Failed to canonicalize message for signature validation");
254
+ throw new Error("Failed to canonicalize message");
255
+ }
256
+ const messageHash = import_ethers2.ethers.keccak256(new TextEncoder().encode(message));
257
+ let appId = import_ethers2.ethers.verifyMessage(
258
+ import_ethers2.ethers.getBytes(messageHash),
259
+ import_ethers2.ethers.hexlify(signature)
260
+ ).toLowerCase();
261
+ if (import_ethers2.ethers.getAddress(appId) !== import_ethers2.ethers.getAddress(applicationId)) {
262
+ logger3.info(`Signature validation failed: Mismatch between derived appId (${appId}) and provided applicationId (${applicationId})`);
263
+ throw new InvalidSignatureError(`Signature does not match the application id: ${appId}`);
264
+ }
265
+ logger3.info(`Signature validated successfully for applicationId: ${applicationId}`);
266
+ } catch (err) {
267
+ logger3.info(`Signature validation failed: ${err.message}`);
268
+ if (err instanceof InvalidSignatureError) {
269
+ throw err;
270
+ }
271
+ throw new InvalidSignatureError(`Failed to validate signature: ${err.message}`);
272
+ }
273
+ }
274
+ function validateRequestedProof(requestedProof) {
275
+ if (!requestedProof.url) {
276
+ logger3.info(`Requested proof validation failed: Provided url in requested proof is not valid`);
277
+ throw new InvalidParamError(`The provided url in requested proof is not valid`);
278
+ }
279
+ if (requestedProof.parameters && typeof requestedProof.parameters !== "object") {
280
+ logger3.info(`Requested proof validation failed: Provided parameters in requested proof is not valid`);
281
+ throw new InvalidParamError(`The provided parameters in requested proof is not valid`);
282
+ }
283
+ }
284
+ function validateContext(context) {
285
+ if (!context.contextAddress) {
286
+ logger3.info(`Context validation failed: Provided context address in context is not valid`);
287
+ throw new InvalidParamError(`The provided context address in context is not valid`);
288
+ }
289
+ if (!context.contextMessage) {
290
+ logger3.info(`Context validation failed: Provided context message in context is not valid`);
291
+ throw new InvalidParamError(`The provided context message in context is not valid`);
292
+ }
293
+ validateFunctionParams([
294
+ { input: context.contextAddress, paramName: "contextAddress", isString: true },
295
+ { input: context.contextMessage, paramName: "contextMessage", isString: true }
296
+ ], "validateContext");
297
+ }
298
+
299
+ // src/utils/sessionUtils.ts
300
+ var logger4 = logger_default.logger;
301
+ function initSession(providerId, appId, timestamp, signature) {
302
+ return __async(this, null, function* () {
303
+ logger4.info(`Initializing session for providerId: ${providerId}, appId: ${appId}`);
304
+ try {
305
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/init-session/`, {
306
+ method: "POST",
307
+ headers: { "Content-Type": "application/json" },
308
+ body: JSON.stringify({ providerId, appId, timestamp, signature })
309
+ });
310
+ const res = yield response.json();
311
+ if (!response.ok) {
312
+ logger4.info(`Session initialization failed: ${res.message || "Unknown error"}`);
313
+ throw new InitSessionError(res.message || `Error initializing session with providerId: ${providerId}`);
314
+ }
315
+ return res;
316
+ } catch (err) {
317
+ logger4.info({
318
+ message: "Failed to initialize session",
319
+ providerId,
320
+ appId,
321
+ timestamp,
322
+ error: err
323
+ });
324
+ throw err;
325
+ }
326
+ });
327
+ }
328
+ function updateSession(sessionId, status) {
329
+ return __async(this, null, function* () {
330
+ logger4.info(`Updating session status for sessionId: ${sessionId}, new status: ${status}`);
331
+ validateFunctionParams(
332
+ [{ input: sessionId, paramName: "sessionId", isString: true }],
333
+ "updateSession"
334
+ );
335
+ try {
336
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/update/session/`, {
337
+ method: "POST",
338
+ headers: { "Content-Type": "application/json" },
339
+ body: JSON.stringify({ sessionId, status })
340
+ });
341
+ const res = yield response.json();
342
+ if (!response.ok) {
343
+ const errorMessage = `Error updating session with sessionId: ${sessionId}. Status Code: ${response.status}`;
344
+ logger4.info(errorMessage, res);
345
+ throw new UpdateSessionError(errorMessage);
346
+ }
347
+ logger4.info(`Session status updated successfully for sessionId: ${sessionId}`);
348
+ return res;
349
+ } catch (err) {
350
+ const errorMessage = `Failed to update session with sessionId: ${sessionId}`;
351
+ logger4.info(errorMessage, err);
352
+ throw new UpdateSessionError(`Error updating session with sessionId: ${sessionId}`);
353
+ }
354
+ });
355
+ }
356
+
357
+ // src/utils/proofUtils.ts
358
+ var import_ethers5 = require("ethers");
359
+
360
+ // src/contract-types/contracts/factories/Reclaim__factory.ts
361
+ var import_ethers3 = require("ethers");
135
362
  var _abi = [
136
363
  {
137
364
  anonymous: false,
@@ -668,7 +895,7 @@ var _abi = [
668
895
  ];
669
896
  var Reclaim__factory = class {
670
897
  static connect(address, signerOrProvider) {
671
- return new import_ethers2.Contract(address, _abi, signerOrProvider);
898
+ return new import_ethers3.Contract(address, _abi, signerOrProvider);
672
899
  }
673
900
  };
674
901
  Reclaim__factory.abi = _abi;
@@ -688,7 +915,7 @@ var config_default = {
688
915
  };
689
916
 
690
917
  // src/smart-contract.ts
691
- var import_ethers3 = require("ethers");
918
+ var import_ethers4 = require("ethers");
692
919
  var DEFAULT_CHAIN_ID = 11155420;
693
920
  function makeBeacon(chainId) {
694
921
  chainId = chainId || DEFAULT_CHAIN_ID;
@@ -744,7 +971,7 @@ function getContract(chainId) {
744
971
  if (!contractData) {
745
972
  throw new Error(`Unsupported chain: "${chainKey}"`);
746
973
  }
747
- const rpcProvider = new import_ethers3.ethers.JsonRpcProvider(contractData.rpcUrl);
974
+ const rpcProvider = new import_ethers4.ethers.JsonRpcProvider(contractData.rpcUrl);
748
975
  existingContractsMap[chainKey] = Reclaim__factory.connect(
749
976
  contractData.address,
750
977
  rpcProvider
@@ -753,372 +980,114 @@ function getContract(chainId) {
753
980
  return existingContractsMap[chainKey];
754
981
  }
755
982
 
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()
983
+ // src/utils/proofUtils.ts
984
+ var logger5 = logger_default.logger;
985
+ function generateRequestedProof(provider) {
986
+ const providerParams = {};
987
+ provider.responseSelections.forEach(
988
+ (rs) => rs.responseMatch.split(/{{(.*?)}}/).filter((_, i) => i % 2).forEach((param) => providerParams[param] = "")
883
989
  );
990
+ const proof = {
991
+ url: provider.url,
992
+ parameters: providerParams
993
+ };
994
+ return proof;
884
995
  }
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);
996
+ function getFilledParameters(requestedProof) {
997
+ return Object.keys(requestedProof.parameters).reduce((acc, param) => {
998
+ if (requestedProof.parameters[param]) {
999
+ acc[param] = requestedProof.parameters[param];
891
1000
  }
892
- }
893
- if (witnessesNotSeen.size > 0) {
894
- throw new ProofNotVerifiedError(
895
- `Missing signatures from ${expectedWitnessAddresses.join(", ")}`
896
- );
897
- }
1001
+ return acc;
1002
+ }, {});
898
1003
  }
899
1004
  function getShortenedUrl(url) {
900
1005
  return __async(this, null, function* () {
1006
+ logger5.info(`Attempting to shorten URL: ${url}`);
901
1007
  try {
902
1008
  validateURL(url, "getShortenedUrl");
903
- const response = yield fetch(BACKEND_BASE_URL + "/api/sdk/shortener", {
1009
+ const response = yield fetch(`${BACKEND_BASE_URL}/api/sdk/shortener`, {
904
1010
  method: "POST",
905
- headers: {
906
- "Content-Type": "application/json"
907
- },
908
- body: JSON.stringify({
909
- fullUrl: url
910
- })
1011
+ headers: { "Content-Type": "application/json" },
1012
+ body: JSON.stringify({ fullUrl: url })
911
1013
  });
912
1014
  const res = yield response.json();
1015
+ if (!response.ok) {
1016
+ logger5.info(`Failed to shorten URL: ${url}, Response: ${JSON.stringify(res)}`);
1017
+ return url;
1018
+ }
913
1019
  const shortenedVerificationUrl = res.result.shortUrl;
914
1020
  return shortenedVerificationUrl;
915
1021
  } catch (err) {
1022
+ logger5.info(`Error shortening URL: ${url}, Error: ${err}`);
916
1023
  return url;
917
1024
  }
918
1025
  });
919
1026
  }
920
- function createSession(sessionId, appId, providerId) {
1027
+ function createLinkWithTemplateData(templateData) {
921
1028
  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");
1029
+ let template = encodeURIComponent(JSON.stringify(templateData));
1030
+ template = replaceAll(template, "(", "%28");
1031
+ template = replaceAll(template, ")", "%29");
1032
+ const fullLink = `${constants.RECLAIM_SHARE_URL}${template}`;
928
1033
  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;
1034
+ const shortenedLink = yield getShortenedUrl(fullLink);
1035
+ return shortenedLink;
945
1036
  } catch (err) {
946
- throw new CreateSessionError("Error creating session with sessionId: " + sessionId);
1037
+ logger5.info(`Error creating link for sessionId: ${templateData.sessionId}, Error: ${err}`);
1038
+ return fullLink;
947
1039
  }
948
1040
  });
949
1041
  }
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) {
1042
+ function getWitnessesForClaim(epoch, identifier, timestampS) {
976
1043
  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);
1044
+ const beacon = makeBeacon();
1045
+ if (!beacon) {
1046
+ logger5.info("No beacon available for getting witnesses");
1047
+ throw new Error("No beacon available");
992
1048
  }
1049
+ const state = yield beacon.getState(epoch);
1050
+ const witnessList = fetchWitnessListForClaim(state, identifier, timestampS);
1051
+ const witnesses = witnessList.map((w) => w.id.toLowerCase());
1052
+ return witnesses;
993
1053
  });
994
1054
  }
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
- };
1055
+ function recoverSignersOfSignedClaim({
1056
+ claim,
1057
+ signatures
1058
+ }) {
1059
+ const dataStr = createSignDataForClaim(__spreadValues({}, claim));
1060
+ const signers = signatures.map(
1061
+ (signature) => import_ethers5.ethers.verifyMessage(dataStr, import_ethers5.ethers.hexlify(signature)).toLowerCase()
1062
+ );
1063
+ return signers;
1042
1064
  }
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}`);
1065
+ function assertValidSignedClaim(claim, expectedWitnessAddresses) {
1066
+ const witnessAddresses = recoverSignersOfSignedClaim(claim);
1067
+ const witnessesNotSeen = new Set(expectedWitnessAddresses);
1068
+ for (const witness of witnessAddresses) {
1069
+ if (witnessesNotSeen.has(witness)) {
1070
+ witnessesNotSeen.delete(witness);
1071
1071
  }
1072
- } catch (err) {
1073
- throw err;
1074
1072
  }
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
- });
1073
+ if (witnessesNotSeen.size > 0) {
1074
+ const missingWitnesses = Array.from(witnessesNotSeen).join(", ");
1075
+ logger5.info(`Claim validation failed. Missing signatures from: ${missingWitnesses}`);
1076
+ throw new ProofNotVerifiedError(
1077
+ `Missing signatures from ${missingWitnesses}`
1078
+ );
1079
+ }
1110
1080
  }
1111
1081
 
1112
1082
  // 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
- }
1083
+ var logger6 = logger_default.logger;
1084
+ function verifyProof(proof) {
1085
+ return __async(this, null, function* () {
1086
+ var _a;
1087
+ if (!proof.signatures.length) {
1088
+ throw new SignatureNotFoundError("No signatures");
1089
+ }
1090
+ try {
1122
1091
  let witnesses = [];
1123
1092
  if (proof.witnesses.length && ((_a = proof.witnesses[0]) == null ? void 0 : _a.url) === "manual-verify") {
1124
1093
  witnesses.push(proof.witnesses[0].id);
@@ -1129,375 +1098,365 @@ var _Reclaim = class _Reclaim {
1129
1098
  proof.claimData.timestampS
1130
1099
  );
1131
1100
  }
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;
1101
+ const calculatedIdentifier = getIdentifierFromClaimInfo({
1102
+ parameters: JSON.parse(
1103
+ (0, import_canonicalize2.default)(proof.claimData.parameters)
1104
+ ),
1105
+ provider: proof.claimData.provider,
1106
+ context: proof.claimData.context
1107
+ });
1108
+ proof.identifier = replaceAll(proof.identifier, '"', "");
1109
+ if (calculatedIdentifier !== proof.identifier) {
1110
+ throw new ProofNotVerifiedError("Identifier Mismatch");
1191
1111
  }
1192
- return true;
1112
+ const signedClaim = {
1113
+ claim: __spreadValues({}, proof.claimData),
1114
+ signatures: proof.signatures.map((signature) => {
1115
+ return import_ethers6.ethers.getBytes(signature);
1116
+ })
1117
+ };
1118
+ assertValidSignedClaim(signedClaim, witnesses);
1193
1119
  } catch (e) {
1194
- logger.error(e);
1120
+ logger6.info(`Error verifying proof: ${e instanceof Error ? e.message : String(e)}`);
1195
1121
  return false;
1196
1122
  }
1197
- }
1198
- };
1199
- _Reclaim.ProofRequest = class {
1200
- constructor(applicationId, options) {
1123
+ return true;
1124
+ });
1125
+ }
1126
+ function transformForOnchain(proof) {
1127
+ const claimInfoBuilder = /* @__PURE__ */ new Map([
1128
+ ["context", proof.claimData.context],
1129
+ ["parameters", proof.claimData.parameters],
1130
+ ["provider", proof.claimData.provider]
1131
+ ]);
1132
+ const claimInfo = Object.fromEntries(claimInfoBuilder);
1133
+ const claimBuilder = /* @__PURE__ */ new Map([
1134
+ ["epoch", proof.claimData.epoch],
1135
+ ["identifier", proof.claimData.identifier],
1136
+ ["owner", proof.claimData.owner],
1137
+ ["timestampS", proof.claimData.timestampS]
1138
+ ]);
1139
+ const signedClaim = {
1140
+ claim: Object.fromEntries(claimBuilder),
1141
+ signatures: proof.signatures
1142
+ };
1143
+ return { claimInfo, signedClaim };
1144
+ }
1145
+ var ReclaimProofRequest = class _ReclaimProofRequest {
1146
+ // Private constructor
1147
+ constructor(applicationId, providerId, options) {
1201
1148
  this.context = { contextAddress: "0x0", contextMessage: "" };
1202
1149
  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
- );
1150
+ this.providerId = providerId;
1215
1151
  this.timeStamp = Date.now().toString();
1152
+ this.applicationId = applicationId;
1153
+ this.sessionId = "";
1154
+ if (options == null ? void 0 : options.log) {
1155
+ logger_default.setLogLevel("info");
1156
+ } else {
1157
+ logger_default.setLogLevel("silent");
1158
+ }
1159
+ this.options = options;
1160
+ logger6.info(`Initializing client with applicationId: ${this.applicationId}`);
1216
1161
  }
1217
- addContext(address, message) {
1218
- validateNotNullOrUndefined(address, "address", "addContext");
1219
- validateNotNullOrUndefined(message, "message", "addContext");
1220
- this.context = { contextAddress: address, contextMessage: message };
1162
+ // Static initialization methods
1163
+ static init(applicationId, appSecret, providerId, options) {
1164
+ return __async(this, null, function* () {
1165
+ try {
1166
+ validateFunctionParams([
1167
+ { paramName: "applicationId", input: applicationId, isString: true },
1168
+ { paramName: "providerId", input: providerId, isString: true },
1169
+ { paramName: "appSecret", input: appSecret, isString: true }
1170
+ ], "the constructor");
1171
+ if (options) {
1172
+ if (options.acceptAiProviders) {
1173
+ validateFunctionParams([
1174
+ { paramName: "acceptAiProviders", input: options.acceptAiProviders }
1175
+ ], "the constructor");
1176
+ }
1177
+ if (options.log) {
1178
+ validateFunctionParams([
1179
+ { paramName: "log", input: options.log }
1180
+ ], "the constructor");
1181
+ }
1182
+ }
1183
+ const proofRequestInstance = new _ReclaimProofRequest(applicationId, providerId, options);
1184
+ const signature = yield proofRequestInstance.generateSignature(appSecret);
1185
+ proofRequestInstance.setSignature(signature);
1186
+ const data = yield initSession(providerId, applicationId, proofRequestInstance.timeStamp, signature);
1187
+ proofRequestInstance.sessionId = data.sessionId;
1188
+ yield proofRequestInstance.buildProofRequest(data.provider);
1189
+ return proofRequestInstance;
1190
+ } catch (error) {
1191
+ logger6.info(error);
1192
+ throw new InitError("Failed to initialize ReclaimProofRequest", error);
1193
+ }
1194
+ });
1221
1195
  }
1196
+ static fromJsonString(jsonString) {
1197
+ return __async(this, null, function* () {
1198
+ try {
1199
+ const {
1200
+ applicationId,
1201
+ providerId,
1202
+ sessionId,
1203
+ context,
1204
+ requestedProof,
1205
+ signature,
1206
+ redirectUrl,
1207
+ timeStamp,
1208
+ appCallbackUrl,
1209
+ options
1210
+ } = JSON.parse(jsonString);
1211
+ validateFunctionParams([
1212
+ { input: applicationId, paramName: "applicationId", isString: true },
1213
+ { input: providerId, paramName: "providerId", isString: true },
1214
+ { input: signature, paramName: "signature", isString: true },
1215
+ { input: sessionId, paramName: "sessionId", isString: true },
1216
+ { input: timeStamp, paramName: "timeStamp", isString: true }
1217
+ ], "fromJsonString");
1218
+ validateRequestedProof(requestedProof);
1219
+ if (redirectUrl) {
1220
+ validateURL(redirectUrl, "fromJsonString");
1221
+ }
1222
+ if (appCallbackUrl) {
1223
+ validateURL(appCallbackUrl, "fromJsonString");
1224
+ }
1225
+ if (context) {
1226
+ validateContext(context);
1227
+ }
1228
+ const proofRequestInstance = new _ReclaimProofRequest(applicationId, providerId, options);
1229
+ proofRequestInstance.sessionId = sessionId;
1230
+ proofRequestInstance.context = context;
1231
+ proofRequestInstance.requestedProof = requestedProof;
1232
+ proofRequestInstance.appCallbackUrl = appCallbackUrl;
1233
+ proofRequestInstance.redirectUrl = redirectUrl;
1234
+ proofRequestInstance.timeStamp = timeStamp;
1235
+ proofRequestInstance.signature = signature;
1236
+ return proofRequestInstance;
1237
+ } catch (error) {
1238
+ logger6.info("Failed to parse JSON string in fromJsonString:", error);
1239
+ throw new InvalidParamError("Invalid JSON string provided to fromJsonString");
1240
+ }
1241
+ });
1242
+ }
1243
+ // Setter methods
1222
1244
  setAppCallbackUrl(url) {
1223
1245
  validateURL(url, "setAppCallbackUrl");
1224
- const urlObj = new URL(url);
1225
- urlObj.searchParams.append("callbackId", this.sessionId);
1226
- this.appCallbackUrl = urlObj.toString();
1246
+ this.appCallbackUrl = url;
1227
1247
  }
1228
1248
  setRedirectUrl(url) {
1229
1249
  validateURL(url, "setRedirectUrl");
1230
- const urlObj = new URL(url);
1231
- this.redirectUrl = urlObj.toString();
1250
+ this.redirectUrl = url;
1232
1251
  }
1233
- setStatusUrl(url) {
1234
- validateURL(url, "setStatusUrl");
1235
- this.statusUrl = url;
1252
+ addContext(address, message) {
1253
+ try {
1254
+ validateFunctionParams([
1255
+ { input: address, paramName: "address", isString: true },
1256
+ { input: message, paramName: "message", isString: true }
1257
+ ], "addContext");
1258
+ this.context = { contextAddress: address, contextMessage: message };
1259
+ } catch (error) {
1260
+ logger6.info("Error adding context", error);
1261
+ throw new AddContextError("Error adding context", error);
1262
+ }
1236
1263
  }
1237
- setSignature(signature) {
1238
- validateNotNullOrUndefined(signature, "signature", "setSignature");
1239
- validateNonEmptyString(signature, "signature", "setSignature");
1240
- this.signature = signature;
1264
+ setParams(params) {
1265
+ try {
1266
+ const requestedProof = this.getRequestedProof();
1267
+ if (!requestedProof || !this.requestedProof) {
1268
+ throw new BuildProofRequestError("Requested proof is not present.");
1269
+ }
1270
+ const currentParams = this.availableParams();
1271
+ if (!currentParams) {
1272
+ throw new NoProviderParamsError("No params present in the provider config.");
1273
+ }
1274
+ const paramsToSet = Object.keys(params);
1275
+ for (const param of paramsToSet) {
1276
+ if (!currentParams.includes(param)) {
1277
+ throw new InvalidParamError(
1278
+ `Cannot set parameter ${param} for provider ${this.providerId}. Available parameters: ${currentParams}`
1279
+ );
1280
+ }
1281
+ }
1282
+ this.requestedProof.parameters = __spreadValues(__spreadValues({}, requestedProof.parameters), params);
1283
+ } catch (error) {
1284
+ logger6.info("Error Setting Params:", error);
1285
+ throw new SetParamsError("Error setting params", error);
1286
+ }
1241
1287
  }
1288
+ // Getter methods
1242
1289
  getAppCallbackUrl() {
1243
- return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;
1290
+ try {
1291
+ validateFunctionParams([{ input: this.sessionId, paramName: "sessionId", isString: true }], "getAppCallbackUrl");
1292
+ return this.appCallbackUrl || `${constants.DEFAULT_RECLAIM_CALLBACK_URL}${this.sessionId}`;
1293
+ } catch (error) {
1294
+ logger6.info("Error getting app callback url", error);
1295
+ throw new GetAppCallbackUrlError("Error getting app callback url", error);
1296
+ }
1244
1297
  }
1245
1298
  getStatusUrl() {
1246
- return this.statusUrl || `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`;
1299
+ try {
1300
+ validateFunctionParams([{ input: this.sessionId, paramName: "sessionId", isString: true }], "getStatusUrl");
1301
+ return `${constants.DEFAULT_RECLAIM_STATUS_URL}${this.sessionId}`;
1302
+ } catch (error) {
1303
+ logger6.info("Error fetching Status Url", error);
1304
+ throw new GetStatusUrlError("Error fetching status url", error);
1305
+ }
1247
1306
  }
1248
- getRequestedProofs() {
1307
+ // Private helper methods
1308
+ setSignature(signature) {
1249
1309
  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;
1310
+ validateFunctionParams([{ input: signature, paramName: "signature", isString: true }], "setSignature");
1311
+ this.signature = signature;
1312
+ logger6.info(`Signature set successfully for session ID: ${this.sessionId}`);
1313
+ } catch (error) {
1314
+ logger6.info("Error setting signature", error);
1315
+ throw new SetSignatureError("Error setting signature", error);
1258
1316
  }
1259
1317
  }
1260
1318
  generateSignature(applicationSecret) {
1261
1319
  return __async(this, null, function* () {
1262
- var _a, _b;
1263
1320
  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;
1321
+ const wallet = new import_ethers6.ethers.Wallet(applicationSecret);
1322
+ const canonicalData = (0, import_canonicalize2.default)({ providerId: this.providerId, timestamp: this.timeStamp });
1323
+ if (!canonicalData) {
1324
+ throw new SignatureGeneratingError("Failed to canonicalize data for signing.");
1280
1325
  }
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;
1326
+ const messageHash = import_ethers6.ethers.keccak256(new TextEncoder().encode(canonicalData));
1327
+ return yield wallet.signMessage(import_ethers6.ethers.getBytes(messageHash));
1291
1328
  } catch (err) {
1292
- logger.error(err);
1293
- throw new BuildProofRequestError(
1294
- "Error generating signature for applicationSecret: " + applicationSecret
1295
- );
1329
+ logger6.info(`Error generating proof request for applicationId: ${this.applicationId}, providerId: ${this.providerId}, signature: ${this.signature}, timeStamp: ${this.timeStamp}`, err);
1330
+ throw new SignatureGeneratingError(`Error generating signature for applicationSecret: ${applicationSecret}`);
1296
1331
  }
1297
1332
  });
1298
1333
  }
1299
- buildProofRequest(providerId, redirectUser = false, linkingVersion) {
1334
+ buildProofRequest(provider) {
1300
1335
  return __async(this, null, function* () {
1301
- let providers = yield fetchProvidersByAppId(this.applicationId, providerId);
1302
- const provider = validateProviderIdsAndReturnProviders(
1303
- providerId,
1304
- providers
1305
- );
1306
1336
  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
- return this.requestedProofs;
1337
+ this.requestedProof = generateRequestedProof(provider);
1338
+ return this.requestedProof;
1326
1339
  } catch (err) {
1327
- logger.error(err);
1328
- throw new BuildProofRequestError(
1329
- "Something went wrong while generating proof request"
1330
- );
1340
+ logger6.info(err instanceof Error ? err.message : String(err));
1341
+ throw new BuildProofRequestError("Something went wrong while generating proof request", err);
1331
1342
  }
1332
1343
  });
1333
1344
  }
1334
- createVerificationRequest() {
1345
+ getRequestedProof() {
1346
+ if (!this.requestedProof) {
1347
+ throw new BuildProofRequestError("RequestedProof is not present in the instance.");
1348
+ }
1349
+ return this.requestedProof;
1350
+ }
1351
+ availableParams() {
1352
+ try {
1353
+ const requestedProofs = this.getRequestedProof();
1354
+ let availableParamsStore = Object.keys(requestedProofs.parameters);
1355
+ availableParamsStore = availableParamsStore.concat(requestedProofs.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1356
+ return [...new Set(availableParamsStore)];
1357
+ } catch (error) {
1358
+ logger6.info("Error fetching available params", error);
1359
+ throw new AvailableParamsError("Error fetching available params", error);
1360
+ }
1361
+ }
1362
+ clearInterval() {
1363
+ if (this.sessionId && this.intervals.has(this.sessionId)) {
1364
+ clearInterval(this.intervals.get(this.sessionId));
1365
+ this.intervals.delete(this.sessionId);
1366
+ }
1367
+ }
1368
+ // Public methods
1369
+ toJsonString(options) {
1370
+ return JSON.stringify({
1371
+ applicationId: this.applicationId,
1372
+ providerId: this.providerId,
1373
+ sessionId: this.sessionId,
1374
+ context: this.context,
1375
+ requestedProof: this.requestedProof,
1376
+ appCallbackUrl: this.appCallbackUrl,
1377
+ signature: this.signature,
1378
+ redirectUrl: this.redirectUrl,
1379
+ timeStamp: this.timeStamp,
1380
+ options: this.options
1381
+ });
1382
+ }
1383
+ getRequestUrl() {
1335
1384
  return __async(this, null, function* () {
1336
- var _a, _b, _c, _d, _e;
1385
+ var _a, _b, _c;
1386
+ logger6.info("Creating Request Url");
1387
+ if (!this.signature) {
1388
+ throw new SignatureNotFoundError("Signature is not set.");
1389
+ }
1337
1390
  try {
1338
- const requestedProofs = yield this.getRequestedProofs();
1339
- if (!requestedProofs) {
1340
- throw new BuildProofRequestError(
1341
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1342
- );
1343
- }
1344
- if (!this.signature) {
1345
- throw new SignatureNotFoundError(
1346
- "Signature is not set. Use reclaim.setSignature(signature) to set the signature"
1347
- );
1348
- }
1349
- validateSignature(requestedProofs, this.signature, this.applicationId, this.linkingVersion, this.timeStamp);
1350
- let templateData = {};
1351
- if (requestedProofs.claims.length && (this.linkingVersion === "V2Linking" || ((_b = (_a = requestedProofs.claims[0]) == null ? void 0 : _a.payload) == null ? void 0 : _b.verificationType) === "MANUAL")) {
1352
- templateData = {
1353
- sessionId: this.sessionId,
1354
- providerId: this.providerId,
1355
- applicationId: this.applicationId,
1356
- signature: this.signature,
1357
- timestamp: this.timeStamp,
1358
- callbackUrl: this.getAppCallbackUrl(),
1359
- context: JSON.stringify(this.context),
1360
- verificationType: requestedProofs.claims[0].payload.verificationType,
1361
- parameters: requestedProofs.claims[0].payload.parameters,
1362
- redirectUrl: (_c = this.redirectUrl) != null ? _c : ""
1363
- };
1364
- } else {
1365
- templateData = __spreadProps(__spreadValues({}, requestedProofs), {
1366
- signature: this.signature
1367
- });
1368
- }
1369
- let template = encodeURIComponent(
1370
- JSON.stringify(templateData)
1371
- );
1372
- template = replaceAll(template, "(", "%28");
1373
- template = replaceAll(template, ")", "%29");
1374
- let link = "";
1375
- if (requestedProofs.claims.length && (this.linkingVersion === "V2Linking" || ((_e = (_d = requestedProofs.claims[0]) == null ? void 0 : _d.payload) == null ? void 0 : _e.verificationType) === "MANUAL")) {
1376
- link = `https://share.reclaimprotocol.org/verifier?template=` + template;
1377
- link = yield getShortenedUrl(link);
1378
- } else {
1379
- link = yield getBranchLink(template);
1380
- }
1381
- yield createSession(this.sessionId, this.applicationId, this.providerId);
1382
- return { requestUrl: link, statusUrl: this.getStatusUrl() };
1391
+ const requestedProof = this.getRequestedProof();
1392
+ validateSignature(this.providerId, this.signature, this.applicationId, this.timeStamp);
1393
+ const templateData = {
1394
+ sessionId: this.sessionId,
1395
+ providerId: this.providerId,
1396
+ applicationId: this.applicationId,
1397
+ signature: this.signature,
1398
+ timestamp: this.timeStamp,
1399
+ callbackUrl: this.getAppCallbackUrl(),
1400
+ context: JSON.stringify(this.context),
1401
+ parameters: getFilledParameters(requestedProof),
1402
+ redirectUrl: (_a = this.redirectUrl) != null ? _a : "",
1403
+ acceptAiProviders: (_c = (_b = this.options) == null ? void 0 : _b.acceptAiProviders) != null ? _c : false
1404
+ };
1405
+ const link = yield createLinkWithTemplateData(templateData);
1406
+ logger6.info("Request Url created successfully: " + link);
1407
+ yield updateSession(this.sessionId, "SESSION_STARTED" /* SESSION_STARTED */);
1408
+ return link;
1383
1409
  } catch (error) {
1384
- logger.error("Error creating verification request:", error);
1410
+ logger6.info("Error creating Request Url:", error);
1385
1411
  throw error;
1386
1412
  }
1387
1413
  });
1388
1414
  }
1389
1415
  startSession(_0) {
1390
- return __async(this, arguments, function* ({
1391
- onSuccessCallback,
1392
- onFailureCallback
1393
- }) {
1416
+ return __async(this, arguments, function* ({ onSuccess, onError }) {
1394
1417
  const statusUrl = this.getStatusUrl();
1395
- if (statusUrl && this.sessionId) {
1396
- logger.info("Starting session");
1397
- try {
1398
- yield updateSession(this.sessionId, "SDK_STARTED" /* SDK_STARTED */);
1399
- } catch (e) {
1400
- logger.error(e);
1401
- }
1402
- const interval = setInterval(() => __async(this, null, function* () {
1403
- try {
1404
- const res = yield fetch(statusUrl);
1405
- const data = yield res.json();
1406
- if (!data.session)
1407
- return;
1408
- if (data.session.status === "FAILED" /* FAILED */)
1409
- throw new ProviderFailedError();
1410
- if (data.session.proofs.length === 0)
1411
- return;
1412
- const proof = data.session.proofs[0];
1413
- const verified = yield _Reclaim.verifySignedProof(proof);
1414
- if (!verified) {
1415
- throw new ProofNotVerifiedError();
1416
- }
1417
- if (onSuccessCallback) {
1418
- try {
1419
- yield updateSession(this.sessionId, "SDK_RECEIVED" /* SDK_RECEIVED */);
1420
- } catch (e) {
1421
- logger.error(e);
1422
- }
1423
- onSuccessCallback(data.session.proofs);
1424
- }
1425
- clearInterval(this.intervals.get(this.sessionId));
1426
- this.intervals.delete(this.sessionId);
1427
- } catch (e) {
1428
- if (!(e instanceof ProviderFailedError)) {
1429
- try {
1430
- yield updateSession(this.sessionId, "FAILED" /* FAILED */);
1431
- } catch (e2) {
1432
- logger.error(e2);
1433
- }
1434
- }
1435
- if (onFailureCallback) {
1436
- onFailureCallback(e);
1437
- }
1438
- clearInterval(this.intervals.get(this.sessionId));
1439
- this.intervals.delete(this.sessionId);
1440
- }
1441
- }), 3e3);
1442
- this.intervals.set(this.sessionId, interval);
1443
- this.scheduleIntervalEndingTask(onFailureCallback);
1444
- } else {
1418
+ if (!statusUrl || !this.sessionId) {
1445
1419
  const message = "Session can't be started due to undefined value of statusUrl and sessionId";
1446
- logger.error(message);
1420
+ logger6.info(message);
1447
1421
  throw new SessionNotStartedError(message);
1448
1422
  }
1449
- });
1450
- }
1451
- scheduleIntervalEndingTask(onFailureCallback) {
1452
- setTimeout(() => __async(this, null, function* () {
1453
- if (this.intervals.has(this.sessionId)) {
1454
- const message = "Interval ended without receiveing proofs";
1455
- yield updateSession(this.sessionId, "FAILED" /* FAILED */);
1456
- onFailureCallback(new TimeoutError(message));
1457
- logger.warn(message);
1458
- clearInterval(this.intervals.get(this.sessionId));
1459
- }
1460
- }), 1e3 * 60 * 10);
1461
- }
1462
- availableParams() {
1463
- const requestedProofs = this.getRequestedProofs();
1464
- if (!requestedProofs || !this.requestedProofs) {
1465
- throw new BuildProofRequestError(
1466
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1467
- );
1468
- }
1469
- let availableParamsStore = Object.keys(requestedProofs.claims[0].payload.parameters);
1470
- availableParamsStore = availableParamsStore.concat(requestedProofs.claims[0].payload.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1471
- availableParamsStore = availableParamsStore.concat(requestedProofs.claims[0].payload.login.url.split(/{{(.*?)}}/).filter((_, i) => i % 2));
1472
- return [...new Set(availableParamsStore)];
1473
- }
1474
- setParams(params) {
1475
- try {
1476
- const requestedProofs = this.getRequestedProofs();
1477
- if (!requestedProofs || !this.requestedProofs) {
1478
- throw new BuildProofRequestError(
1479
- "Requested proofs are not built yet. Call buildProofRequest(providerId: string) first!"
1480
- );
1481
- }
1482
- const availableParams = this.availableParams();
1483
- const paramsToSet = Object.keys(params);
1484
- for (let i = 0; i < paramsToSet.length; i++) {
1485
- if (requestedProofs.claims[0].payload.verificationType === "WITNESS" && !availableParams.includes(paramsToSet[i])) {
1486
- throw new InvalidParamError(
1487
- `Cannot Set parameter ${paramsToSet[i]} for provider ${this.providerId} available Prameters inculde : ${availableParams}`
1488
- );
1423
+ logger6.info("Starting session");
1424
+ const interval = setInterval(() => __async(this, null, function* () {
1425
+ try {
1426
+ const res = yield fetch(statusUrl);
1427
+ const data = yield res.json();
1428
+ if (!data.session)
1429
+ return;
1430
+ if (data.session.status === "PROOF_GENERATION_FAILED" /* PROOF_GENERATION_FAILED */)
1431
+ throw new ProviderFailedError();
1432
+ if (data.session.proofs.length === 0)
1433
+ return;
1434
+ const proof = data.session.proofs[0];
1435
+ const verified = yield verifyProof(proof);
1436
+ if (!verified) {
1437
+ logger6.info(`Proof not verified: ${proof}`);
1438
+ throw new ProofNotVerifiedError();
1439
+ }
1440
+ if (onSuccess) {
1441
+ onSuccess(proof);
1442
+ }
1443
+ this.clearInterval();
1444
+ } catch (e) {
1445
+ if (onError) {
1446
+ onError(e);
1447
+ }
1448
+ this.clearInterval();
1489
1449
  }
1490
- }
1491
- this.requestedProofs.claims[0].payload.parameters = __spreadValues(__spreadValues({}, requestedProofs.claims[0].payload.parameters), params);
1492
- } catch (error) {
1493
- logger.error("Error Setting Params:", error);
1494
- throw error;
1495
- }
1450
+ }), 3e3);
1451
+ this.intervals.set(this.sessionId, interval);
1452
+ scheduleIntervalEndingTask(this.sessionId, this.intervals, onError);
1453
+ });
1496
1454
  }
1497
1455
  };
1498
- var Reclaim = _Reclaim;
1499
1456
  // Annotate the CommonJS export names for ESM import in node:
1500
1457
  0 && (module.exports = {
1501
- Reclaim
1458
+ ReclaimProofRequest,
1459
+ transformForOnchain,
1460
+ verifyProof
1502
1461
  });
1503
1462
  //# sourceMappingURL=index.js.map