@renown/sdk 6.2.2-dev.6 → 6.2.2-dev.60

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.
Files changed (75) hide show
  1. package/README.md +162 -1
  2. package/dist/{browser-key-storage-v4O-fjz0.js → browser-key-storage-e3RQsnLS.js} +1 -1
  3. package/dist/{browser-key-storage-v4O-fjz0.js.map → browser-key-storage-e3RQsnLS.js.map} +1 -1
  4. package/dist/constants-BexAR53F.js +82 -0
  5. package/dist/constants-BexAR53F.js.map +1 -0
  6. package/dist/crypto.d.ts +2 -2
  7. package/dist/crypto.js +2 -2
  8. package/dist/index-COkz6hfp.d.ts +131 -0
  9. package/dist/index-COkz6hfp.d.ts.map +1 -0
  10. package/dist/index.d.ts +11 -8
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +21 -9
  13. package/dist/index.js.map +1 -1
  14. package/dist/local-credential-verifier-BcCzjvmd.js +846 -0
  15. package/dist/local-credential-verifier-BcCzjvmd.js.map +1 -0
  16. package/dist/meta-C5aQjD4L.d.ts +19 -0
  17. package/dist/meta-C5aQjD4L.d.ts.map +1 -0
  18. package/dist/meta-CHgd9Qd0.js +31 -0
  19. package/dist/meta-CHgd9Qd0.js.map +1 -0
  20. package/dist/meta-D-5kvwx8.js +27 -0
  21. package/dist/meta-D-5kvwx8.js.map +1 -0
  22. package/dist/meta-DufkALio.d.ts +16 -0
  23. package/dist/meta-DufkALio.d.ts.map +1 -0
  24. package/dist/meta-tst3zTfz.d.ts +19 -0
  25. package/dist/meta-tst3zTfz.d.ts.map +1 -0
  26. package/dist/node.d.ts +11 -11
  27. package/dist/node.d.ts.map +1 -1
  28. package/dist/node.js +104 -12
  29. package/dist/node.js.map +1 -1
  30. package/dist/{signer-CgYhXTV7.js → signer-DrjINLqt.js} +13 -6
  31. package/dist/signer-DrjINLqt.js.map +1 -0
  32. package/dist/{signer-DYKGoYHB.d.ts → types-BlhSzU4B.d.ts} +163 -118
  33. package/dist/types-BlhSzU4B.d.ts.map +1 -0
  34. package/dist/types-BqXZ_2bH.d.ts +59 -0
  35. package/dist/types-BqXZ_2bH.d.ts.map +1 -0
  36. package/dist/types-C_qc_62W.js +20 -0
  37. package/dist/types-C_qc_62W.js.map +1 -0
  38. package/dist/{utils-C9ZgMs_C.d.ts → utils-C8MlqUUa.d.ts} +81 -94
  39. package/dist/utils-C8MlqUUa.d.ts.map +1 -0
  40. package/dist/wallet/index.d.ts +8 -0
  41. package/dist/wallet/index.d.ts.map +1 -0
  42. package/dist/wallet/index.js +30 -0
  43. package/dist/wallet/index.js.map +1 -0
  44. package/dist/wallet/mock/factory.d.ts +9 -0
  45. package/dist/wallet/mock/factory.d.ts.map +1 -0
  46. package/dist/wallet/mock/factory.js +35 -0
  47. package/dist/wallet/mock/factory.js.map +1 -0
  48. package/dist/wallet/mock/index.d.ts +9 -0
  49. package/dist/wallet/mock/index.d.ts.map +1 -0
  50. package/dist/wallet/mock/index.js +16 -0
  51. package/dist/wallet/mock/index.js.map +1 -0
  52. package/dist/wallet/privy/factory.d.ts +58 -0
  53. package/dist/wallet/privy/factory.d.ts.map +1 -0
  54. package/dist/wallet/privy/factory.js +258 -0
  55. package/dist/wallet/privy/factory.js.map +1 -0
  56. package/dist/wallet/privy/index.d.ts +9 -0
  57. package/dist/wallet/privy/index.d.ts.map +1 -0
  58. package/dist/wallet/privy/index.js +16 -0
  59. package/dist/wallet/privy/index.js.map +1 -0
  60. package/dist/wallet/rainbow/factory.d.ts +7 -0
  61. package/dist/wallet/rainbow/factory.d.ts.map +1 -0
  62. package/dist/wallet/rainbow/factory.js +219 -0
  63. package/dist/wallet/rainbow/factory.js.map +1 -0
  64. package/dist/wallet/rainbow/index.d.ts +9 -0
  65. package/dist/wallet/rainbow/index.d.ts.map +1 -0
  66. package/dist/wallet/rainbow/index.js +21 -0
  67. package/dist/wallet/rainbow/index.js.map +1 -0
  68. package/package.json +77 -4
  69. package/dist/browser-key-storage-DSkDBAhU.d.ts +0 -14
  70. package/dist/browser-key-storage-DSkDBAhU.d.ts.map +0 -1
  71. package/dist/renown-builder-Sn_Y2Cb2.js +0 -496
  72. package/dist/renown-builder-Sn_Y2Cb2.js.map +0 -1
  73. package/dist/signer-CgYhXTV7.js.map +0 -1
  74. package/dist/signer-DYKGoYHB.d.ts.map +0 -1
  75. package/dist/utils-C9ZgMs_C.d.ts.map +0 -1
@@ -0,0 +1,846 @@
1
+ import { a as DEFAULT_RENOWN_NETWORK_ID, o as DEFAULT_RENOWN_URL, r as CREDENTIAL_TYPES } from "./constants-BexAR53F.js";
2
+ import { m as verifyAuthBearerToken, p as parsePkhDid, s as RenownCryptoBuilder, t as RenownCryptoSigner } from "./signer-DrjINLqt.js";
3
+ import { recoverTypedDataAddress } from "viem";
4
+ import { createAction } from "@powerhousedao/shared/document-model";
5
+ //#region src/discovery.ts
6
+ const DEFAULT_DISCOVERY_TIMEOUT_MS = 3e3;
7
+ async function resolveSwitchboardEndpoint(options) {
8
+ const { switchboardUrl, baseUrl, timeoutMs } = options;
9
+ if (switchboardUrl) return switchboardUrl;
10
+ if (!baseUrl) return;
11
+ const controller = new AbortController();
12
+ const timeout = setTimeout(() => controller.abort(), timeoutMs ?? DEFAULT_DISCOVERY_TIMEOUT_MS);
13
+ try {
14
+ const url = new URL("/api/switchboard", baseUrl);
15
+ const response = await fetch(url, {
16
+ method: "GET",
17
+ signal: controller.signal
18
+ });
19
+ if (!response.ok) return;
20
+ return (await response.json()).endpoint || void 0;
21
+ } catch {
22
+ return;
23
+ } finally {
24
+ clearTimeout(timeout);
25
+ }
26
+ }
27
+ //#endregion
28
+ //#region src/switchboard.ts
29
+ function userDriveId(address) {
30
+ return `renown-${address.toLowerCase()}`;
31
+ }
32
+ const CREDENTIALS_QUERY = `
33
+ query RenownCredentials($input: RenownCredentialsInput!) {
34
+ renownCredentials(input: $input) {
35
+ documentId
36
+ credentialId
37
+ context
38
+ type
39
+ issuerId
40
+ issuerEthereumAddress
41
+ issuanceDate
42
+ expirationDate
43
+ credentialSubjectId
44
+ credentialSubjectApp
45
+ credentialStatusId
46
+ credentialStatusType
47
+ credentialSchemaId
48
+ credentialSchemaType
49
+ proofVerificationMethod
50
+ proofEthereumAddress
51
+ proofCreated
52
+ proofPurpose
53
+ proofType
54
+ proofValue
55
+ proofEip712Domain
56
+ proofEip712PrimaryType
57
+ revoked
58
+ }
59
+ }
60
+ `;
61
+ const USERS_QUERY = `
62
+ query RenownUsers($input: RenownUsersInput!) {
63
+ renownUsers(input: $input) {
64
+ documentId
65
+ username
66
+ ethAddress
67
+ userImage
68
+ createdAt
69
+ updatedAt
70
+ }
71
+ }
72
+ `;
73
+ const CREATE_EMPTY_DOCUMENT_MUTATION = `
74
+ mutation CreateEmptyDocument(
75
+ $documentType: String!
76
+ $parentIdentifier: String
77
+ ) {
78
+ createEmptyDocument(
79
+ documentType: $documentType
80
+ parentIdentifier: $parentIdentifier
81
+ ) {
82
+ id
83
+ }
84
+ }
85
+ `;
86
+ const MUTATE_DOCUMENT_MUTATION = `
87
+ mutation MutateDocument(
88
+ $documentIdentifier: String!
89
+ $actions: [ActionInput!]!
90
+ ) {
91
+ mutateDocument: execute(
92
+ documentIdentifier: $documentIdentifier
93
+ actions: $actions
94
+ ) {
95
+ id
96
+ }
97
+ }
98
+ `;
99
+ const RENOWN_CREDENTIAL_DOC_TYPE = "powerhouse/renown-credential";
100
+ const RENOWN_USER_DOC_TYPE = "powerhouse/renown-user";
101
+ function reshapeCredential(row) {
102
+ const domain = JSON.parse(row.proofEip712Domain);
103
+ return {
104
+ "@context": row.context,
105
+ type: row.type,
106
+ id: row.credentialId,
107
+ issuer: {
108
+ id: row.issuerId,
109
+ ethereumAddress: row.issuerEthereumAddress
110
+ },
111
+ credentialSubject: {
112
+ id: row.credentialSubjectId ?? "",
113
+ app: row.credentialSubjectApp
114
+ },
115
+ credentialSchema: {
116
+ id: row.credentialSchemaId,
117
+ type: row.credentialSchemaType
118
+ },
119
+ ...row.credentialStatusId ? { credentialStatus: {
120
+ id: row.credentialStatusId,
121
+ type: row.credentialStatusType ?? ""
122
+ } } : {},
123
+ issuanceDate: row.issuanceDate,
124
+ expirationDate: row.expirationDate ?? "",
125
+ proof: {
126
+ type: row.proofType,
127
+ created: row.proofCreated,
128
+ verificationMethod: row.proofVerificationMethod,
129
+ proofPurpose: row.proofPurpose,
130
+ proofValue: row.proofValue,
131
+ ethereumAddress: row.proofEthereumAddress,
132
+ eip712: {
133
+ domain,
134
+ types: CREDENTIAL_TYPES,
135
+ primaryType: "VerifiableCredential"
136
+ }
137
+ }
138
+ };
139
+ }
140
+ function issuerChainId(issuerId) {
141
+ return issuerId.split(":")[3];
142
+ }
143
+ function issuerDidAddress(issuerId) {
144
+ return issuerId.split(":")[4];
145
+ }
146
+ function bindsTo(row, address, chainId, appDid) {
147
+ const expected = address.toLowerCase();
148
+ return !row.revoked && row.credentialSubjectId === appDid && issuerChainId(row.issuerId) === String(chainId) && issuerDidAddress(row.issuerId)?.toLowerCase() === expected && row.issuerEthereumAddress.toLowerCase() === expected;
149
+ }
150
+ var SwitchboardClient = class {
151
+ #endpoint;
152
+ #transport;
153
+ constructor(source) {
154
+ if (typeof source === "string") {
155
+ this.#endpoint = source;
156
+ this.#transport = (query, variables) => this.#post(source, query, variables);
157
+ } else this.#transport = source;
158
+ }
159
+ /** The HTTP endpoint, or undefined when reading through a local executor. */
160
+ get endpoint() {
161
+ return this.#endpoint;
162
+ }
163
+ async #post(endpoint, query, variables) {
164
+ const response = await fetch(endpoint, {
165
+ method: "POST",
166
+ headers: { "Content-Type": "application/json" },
167
+ body: JSON.stringify({
168
+ query,
169
+ variables
170
+ })
171
+ });
172
+ if (!response.ok) throw new Error(`Switchboard request failed: ${response.status}`);
173
+ const body = await response.json();
174
+ if (body.errors?.length) throw new Error(body.errors.map((e) => e.message).join("; "));
175
+ return body.data;
176
+ }
177
+ async #request(query, variables) {
178
+ const data = await this.#transport(query, variables);
179
+ if (!data) throw new Error("Switchboard returned no data");
180
+ return data;
181
+ }
182
+ async getCredential(params) {
183
+ const { address, chainId, appDid } = params;
184
+ const { renownCredentials } = await this.#request(CREDENTIALS_QUERY, { input: {
185
+ driveId: userDriveId(address),
186
+ ethAddress: address.toLowerCase(),
187
+ did: appDid,
188
+ includeRevoked: false
189
+ } });
190
+ const now = Date.now();
191
+ const mostRecent = renownCredentials.filter((row) => bindsTo(row, address, chainId, appDid)).filter((row) => {
192
+ if (!row.expirationDate) return true;
193
+ const expiresAt = Date.parse(row.expirationDate);
194
+ return !Number.isNaN(expiresAt) && expiresAt > now;
195
+ }).sort((a, b) => Date.parse(b.issuanceDate) - Date.parse(a.issuanceDate)).at(0);
196
+ return mostRecent ? reshapeCredential(mostRecent) : void 0;
197
+ }
198
+ async getProfileByAddress(address) {
199
+ const { renownUsers } = await this.#request(USERS_QUERY, { input: {
200
+ driveId: userDriveId(address),
201
+ ethAddresses: [address.toLowerCase()]
202
+ } });
203
+ const user = renownUsers.at(0);
204
+ if (!user) return void 0;
205
+ return {
206
+ documentId: user.documentId,
207
+ username: user.username,
208
+ ethAddress: user.ethAddress,
209
+ userImage: user.userImage,
210
+ createdAt: user.createdAt,
211
+ updatedAt: user.updatedAt
212
+ };
213
+ }
214
+ async createEmptyDocument(documentType, parentIdentifier) {
215
+ const { createEmptyDocument } = await this.#request(CREATE_EMPTY_DOCUMENT_MUTATION, {
216
+ documentType,
217
+ parentIdentifier
218
+ });
219
+ return createEmptyDocument.id;
220
+ }
221
+ async mutateDocument(documentIdentifier, actions) {
222
+ const { mutateDocument } = await this.#request(MUTATE_DOCUMENT_MUTATION, {
223
+ documentIdentifier,
224
+ actions
225
+ });
226
+ return mutateDocument.id;
227
+ }
228
+ async issueCredential(credential, parentIdentifier) {
229
+ const documentId = await this.createEmptyDocument(RENOWN_CREDENTIAL_DOC_TYPE, parentIdentifier);
230
+ const input = {
231
+ id: credential.id,
232
+ context: credential["@context"],
233
+ type: credential.type,
234
+ issuer: {
235
+ id: credential.issuer.id,
236
+ ethereumAddress: credential.issuer.ethereumAddress
237
+ },
238
+ credentialSubject: {
239
+ id: credential.credentialSubject.id,
240
+ app: credential.credentialSubject.app
241
+ },
242
+ credentialSchema: {
243
+ id: credential.credentialSchema.id,
244
+ type: credential.credentialSchema.type
245
+ },
246
+ issuanceDate: credential.issuanceDate,
247
+ expirationDate: credential.expirationDate || void 0,
248
+ proof: {
249
+ type: credential.proof.type,
250
+ created: credential.proof.created,
251
+ verificationMethod: credential.proof.verificationMethod,
252
+ proofPurpose: credential.proof.proofPurpose,
253
+ proofValue: credential.proof.proofValue,
254
+ ethereumAddress: credential.proof.ethereumAddress,
255
+ eip712: {
256
+ domain: {
257
+ version: credential.proof.eip712.domain.version,
258
+ chainId: credential.proof.eip712.domain.chainId
259
+ },
260
+ primaryType: credential.proof.eip712.primaryType
261
+ }
262
+ }
263
+ };
264
+ await this.mutateDocument(documentId, [createAction("INIT", input)]);
265
+ return documentId;
266
+ }
267
+ async findOrCreateUser(address, profile = {}) {
268
+ const updates = [];
269
+ if (profile.username !== void 0) updates.push(createAction("SET_USERNAME", { username: profile.username }));
270
+ if (profile.userImage !== void 0) updates.push(createAction("SET_USER_IMAGE", { userImage: profile.userImage }));
271
+ const existing = await this.getProfileByAddress(address);
272
+ if (existing) {
273
+ if (updates.length) await this.mutateDocument(existing.documentId, updates);
274
+ return existing.documentId;
275
+ }
276
+ const documentId = await this.createEmptyDocument(RENOWN_USER_DOC_TYPE);
277
+ await this.mutateDocument(documentId, [createAction("SET_ETH_ADDRESS", { ethAddress: address }), ...updates]);
278
+ return documentId;
279
+ }
280
+ async revokeCredential(documentId, reason) {
281
+ await this.mutateDocument(documentId, [createAction("REVOKE", {
282
+ revokedAt: (/* @__PURE__ */ new Date()).toISOString(),
283
+ reason: reason ?? null
284
+ })]);
285
+ }
286
+ profileFetcher = (user) => this.getProfileByAddress(user.address).catch(() => void 0);
287
+ };
288
+ //#endregion
289
+ //#region src/credential.ts
290
+ /** Assemble a Renown delegation VC and sign it with the provided signer. */
291
+ async function buildAndSignCredential(params) {
292
+ const { signTypedData, address, chainId, app, appId, expiresInDays = 7 } = params;
293
+ const issuerId = `did:pkh:${DEFAULT_RENOWN_NETWORK_ID}:${chainId}:${address.toLowerCase()}`;
294
+ const credentialId = `urn:uuid:${globalThis.crypto.randomUUID()}`;
295
+ const now = /* @__PURE__ */ new Date();
296
+ const expirationDate = new Date(now.getTime() + expiresInDays * 24 * 60 * 60 * 1e3);
297
+ const message = {
298
+ "@context": ["https://www.w3.org/2018/credentials/v1"],
299
+ type: ["VerifiableCredential", "RenownCredential"],
300
+ id: credentialId,
301
+ issuer: {
302
+ id: issuerId,
303
+ ethereumAddress: address
304
+ },
305
+ credentialSubject: {
306
+ id: appId,
307
+ app
308
+ },
309
+ credentialSchema: {
310
+ id: "https://renown.id/schemas/renown-credential/v1",
311
+ type: "JsonSchemaValidator2018"
312
+ },
313
+ issuanceDate: now.toISOString(),
314
+ expirationDate: expirationDate.toISOString()
315
+ };
316
+ const domain = {
317
+ version: "1",
318
+ chainId
319
+ };
320
+ const { EIP712Domain, ...signTypes } = CREDENTIAL_TYPES;
321
+ const signature = await signTypedData({
322
+ domain,
323
+ types: signTypes,
324
+ primaryType: "VerifiableCredential",
325
+ message
326
+ });
327
+ return {
328
+ ...message,
329
+ proof: {
330
+ type: "EthereumEip712Signature2021",
331
+ created: message.issuanceDate,
332
+ verificationMethod: issuerId,
333
+ proofPurpose: "assertionMethod",
334
+ proofValue: signature,
335
+ ethereumAddress: address,
336
+ eip712: {
337
+ domain,
338
+ types: CREDENTIAL_TYPES,
339
+ primaryType: "VerifiableCredential"
340
+ }
341
+ }
342
+ };
343
+ }
344
+ /** Recover the address that signed a credential's EIP-712 proof. */
345
+ async function recoverCredentialSigner(credential) {
346
+ const { proof, ...message } = credential;
347
+ const { EIP712Domain, ...types } = CREDENTIAL_TYPES;
348
+ return recoverTypedDataAddress({
349
+ domain: proof.eip712.domain,
350
+ types,
351
+ primaryType: "VerifiableCredential",
352
+ message,
353
+ signature: proof.proofValue
354
+ });
355
+ }
356
+ /** True when the proof was signed by the credential's declared issuer address. */
357
+ async function verifyCredentialSignature(credential) {
358
+ try {
359
+ return (await recoverCredentialSigner(credential)).toLowerCase() === credential.issuer.ethereumAddress.toLowerCase();
360
+ } catch {
361
+ return false;
362
+ }
363
+ }
364
+ function withEip712Domain(credential, chainId) {
365
+ if (credential.proof.eip712?.domain) return credential;
366
+ return {
367
+ ...credential,
368
+ proof: {
369
+ ...credential.proof,
370
+ eip712: {
371
+ domain: {
372
+ version: "1",
373
+ chainId
374
+ },
375
+ types: CREDENTIAL_TYPES,
376
+ primaryType: "VerifiableCredential"
377
+ }
378
+ }
379
+ };
380
+ }
381
+ async function fetchDelegationCredentialRest(params) {
382
+ const { address, chainId, appDid, baseUrl } = params;
383
+ const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, baseUrl);
384
+ const response = await fetch(url, { method: "GET" });
385
+ if (!response.ok) return void 0;
386
+ const { credential } = await response.json();
387
+ if (!credential) return void 0;
388
+ const [, , , issuerChainId, issuerAddress] = credential.issuer.id.split(":");
389
+ if (credential.credentialSubject.id !== appDid || issuerChainId !== String(chainId) || issuerAddress.toLowerCase() !== address.toLowerCase() || credential.issuer.ethereumAddress.toLowerCase() !== address.toLowerCase()) return;
390
+ if (credential.expirationDate) {
391
+ const expiresAt = Date.parse(credential.expirationDate);
392
+ if (Number.isNaN(expiresAt) || expiresAt <= Date.now()) return;
393
+ }
394
+ return credential;
395
+ }
396
+ async function finalizeCredential(credential, chainId, verifySignature) {
397
+ if (!verifySignature) return credential;
398
+ const withDomain = withEip712Domain(credential, chainId);
399
+ if (withDomain.proof.eip712.domain.chainId !== chainId || !await verifyCredentialSignature(withDomain)) return;
400
+ return withDomain;
401
+ }
402
+ async function fetchDelegationCredential(options) {
403
+ const { address, chainId, appDid, switchboardUrl, switchboardRequest, discover = true, verifySignature = true } = options;
404
+ const explicitBaseUrl = options.baseUrl;
405
+ const baseUrl = explicitBaseUrl ?? "https://www.renown.id";
406
+ try {
407
+ const source = switchboardRequest ?? (switchboardUrl ? switchboardUrl : discover && explicitBaseUrl ? await resolveSwitchboardEndpoint({ baseUrl }) : void 0);
408
+ const credential = source ? await new SwitchboardClient(source).getCredential({
409
+ address,
410
+ chainId,
411
+ appDid
412
+ }) : await fetchDelegationCredentialRest({
413
+ address,
414
+ chainId,
415
+ appDid,
416
+ baseUrl
417
+ });
418
+ if (!credential) return void 0;
419
+ return await finalizeCredential(credential, chainId, verifySignature);
420
+ } catch {
421
+ return;
422
+ }
423
+ }
424
+ async function verifyAuthCredential(jwt, options = {}) {
425
+ const verified = await verifyAuthBearerToken(jwt, { audience: options.audience });
426
+ if (!verified) return void 0;
427
+ const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
428
+ const appDid = verified.issuer;
429
+ const credential = await fetchDelegationCredential({
430
+ address,
431
+ chainId,
432
+ appDid,
433
+ baseUrl: options.renownUrl,
434
+ switchboardUrl: options.switchboardUrl,
435
+ switchboardRequest: options.switchboardRequest,
436
+ verifySignature: options.verifySignature
437
+ });
438
+ if (!credential) return void 0;
439
+ return {
440
+ address,
441
+ chainId,
442
+ networkId,
443
+ did: credential.issuer.id,
444
+ appDid,
445
+ credential
446
+ };
447
+ }
448
+ //#endregion
449
+ //#region src/storage/common.ts
450
+ var BaseStorage = class {};
451
+ var MemoryStorage = class extends BaseStorage {
452
+ data = /* @__PURE__ */ new Map();
453
+ get(key) {
454
+ return this.data.get(key);
455
+ }
456
+ set(key, value) {
457
+ if (value === void 0) this.data.delete(key);
458
+ else this.data.set(key, value);
459
+ }
460
+ delete(key) {
461
+ this.data.delete(key);
462
+ }
463
+ };
464
+ //#endregion
465
+ //#region src/common.ts
466
+ var RenownMemoryStorage = class extends MemoryStorage {};
467
+ var Renown = class {
468
+ #baseUrl;
469
+ #store;
470
+ #eventEmitter;
471
+ #appName;
472
+ #crypto;
473
+ #signer;
474
+ #profileFetcher;
475
+ #switchboard;
476
+ #chainId;
477
+ #status = "initial";
478
+ constructor(store, eventEmitter, crypto, appName, baseUrl = DEFAULT_RENOWN_URL, profileFetcher, switchboard, chainId = 1) {
479
+ this.#store = store;
480
+ this.#eventEmitter = eventEmitter;
481
+ this.#baseUrl = baseUrl;
482
+ this.#crypto = crypto;
483
+ this.#appName = appName;
484
+ this.#profileFetcher = profileFetcher;
485
+ this.#switchboard = switchboard;
486
+ this.#chainId = chainId;
487
+ const restoredUser = this.user;
488
+ this.#signer = new RenownCryptoSigner(crypto, this.#appName, restoredUser);
489
+ if (restoredUser) this.#status = "authorized";
490
+ this.on("user", (user) => {
491
+ this.#signer.user = user;
492
+ });
493
+ }
494
+ get baseUrl() {
495
+ return this.#baseUrl;
496
+ }
497
+ /** Chain id this app issues credentials on; a session from another chain is rejected by {@link signIn}. */
498
+ get chainId() {
499
+ return this.#chainId;
500
+ }
501
+ get user() {
502
+ return this.#store.get("user");
503
+ }
504
+ get status() {
505
+ return this.#status;
506
+ }
507
+ get signer() {
508
+ return this.#signer;
509
+ }
510
+ get crypto() {
511
+ return this.#crypto;
512
+ }
513
+ get did() {
514
+ return this.#crypto.did;
515
+ }
516
+ get profileFetcher() {
517
+ return this.#profileFetcher;
518
+ }
519
+ #updateStatus(status) {
520
+ this.#status = status;
521
+ this.#eventEmitter.emit("status", status);
522
+ }
523
+ #updateUser(user) {
524
+ if (user) this.#store.set("user", user);
525
+ else this.#store.delete("user");
526
+ this.#eventEmitter.emit("user", user);
527
+ }
528
+ async login(userDid) {
529
+ this.#updateStatus("checking");
530
+ try {
531
+ const result = parsePkhDid(userDid);
532
+ const credential = await this.#getCredential(result.address, result.chainId, this.#crypto.did);
533
+ if (!credential) {
534
+ this.#updateUser(void 0);
535
+ throw new Error("Credential not found");
536
+ }
537
+ return await this.#completeLogin(userDid, result, credential);
538
+ } catch (error) {
539
+ this.#updateUser(void 0);
540
+ this.#updateStatus("not-authorized");
541
+ throw error;
542
+ }
543
+ }
544
+ async signIn(params) {
545
+ if (!this.#switchboard) throw new Error("signIn requires a switchboard endpoint. Set switchboardUrl or a discoverable baseUrl.");
546
+ const { address, chainId, signTypedData, username, userImage, expiresInDays } = params;
547
+ if (chainId !== this.#chainId) throw new Error(`Renown signIn: wallet is on chain ${chainId}, but this app issues credentials on chain ${this.#chainId}. Switch networks and retry — signing here would create a separate identity for the same address.`);
548
+ this.#updateStatus("checking");
549
+ try {
550
+ const credential = await buildAndSignCredential({
551
+ signTypedData,
552
+ address,
553
+ chainId,
554
+ app: this.#appName,
555
+ appId: this.did,
556
+ expiresInDays
557
+ });
558
+ await this.#switchboard.issueCredential(credential);
559
+ await this.#switchboard.findOrCreateUser(address, {
560
+ username,
561
+ userImage
562
+ });
563
+ const userDid = `did:pkh:${DEFAULT_RENOWN_NETWORK_ID}:${chainId}:${address.toLowerCase()}`;
564
+ return await this.#completeLogin(userDid, parsePkhDid(userDid), credential);
565
+ } catch (error) {
566
+ this.#updateUser(void 0);
567
+ this.#updateStatus("not-authorized");
568
+ throw error;
569
+ }
570
+ }
571
+ async #completeLogin(userDid, result, credential) {
572
+ if (!(credential.issuer.id === userDid && credential.credentialSubject.id === this.did)) throw new Error("Invalid credential");
573
+ const verifiableCredential = credential.proof.eip712?.domain ? credential : {
574
+ ...credential,
575
+ proof: {
576
+ ...credential.proof,
577
+ eip712: {
578
+ domain: {
579
+ version: "1",
580
+ chainId: result.chainId
581
+ },
582
+ types: CREDENTIAL_TYPES,
583
+ primaryType: "VerifiableCredential"
584
+ }
585
+ }
586
+ };
587
+ if (credential.issuer.ethereumAddress.toLowerCase() !== result.address.toLowerCase() || verifiableCredential.proof.eip712.domain.chainId !== result.chainId || !await verifyCredentialSignature(verifiableCredential)) throw new Error("Invalid credential signature");
588
+ const user = {
589
+ ...result,
590
+ address: credential.issuer.ethereumAddress,
591
+ did: userDid,
592
+ credential: verifiableCredential
593
+ };
594
+ this.#updateUser(user);
595
+ this.#updateStatus("authorized");
596
+ if (this.#profileFetcher) this.#profileFetcher(user, this.#baseUrl).then((profile) => {
597
+ if (profile && this.user?.address === user.address && this.user.chainId === user.chainId) this.#updateUser({
598
+ ...this.user,
599
+ profile,
600
+ ens: {
601
+ name: profile.username ?? void 0,
602
+ avatarUrl: profile.userImage ?? void 0
603
+ }
604
+ });
605
+ }).catch(console.error);
606
+ return user;
607
+ }
608
+ logout() {
609
+ this.#updateUser(void 0);
610
+ this.#updateStatus("initial");
611
+ return Promise.resolve();
612
+ }
613
+ async revalidate() {
614
+ const user = this.user;
615
+ if (!user) return false;
616
+ try {
617
+ if (!await this.#getCredential(user.address, user.chainId, this.#crypto.did)) {
618
+ await this.logout();
619
+ return false;
620
+ }
621
+ await this.refreshProfile();
622
+ return true;
623
+ } catch {
624
+ return true;
625
+ }
626
+ }
627
+ async refreshProfile() {
628
+ const user = this.user;
629
+ if (!user || !this.#profileFetcher) return false;
630
+ try {
631
+ const profile = await this.#profileFetcher(user, this.#baseUrl);
632
+ if (!profile) return false;
633
+ const current = this.user;
634
+ if (!current || current.address !== user.address || current.chainId !== user.chainId) return false;
635
+ if (current.profile !== void 0 && current.profile.documentId === profile.documentId && current.profile.username === profile.username && current.profile.userImage === profile.userImage) return false;
636
+ this.#updateUser({
637
+ ...current,
638
+ profile,
639
+ ens: {
640
+ name: profile.username ?? void 0,
641
+ avatarUrl: profile.userImage ?? void 0
642
+ }
643
+ });
644
+ return true;
645
+ } catch {
646
+ return false;
647
+ }
648
+ }
649
+ on(event, listener) {
650
+ return this.#eventEmitter.on(event, listener);
651
+ }
652
+ async #getCredential(address, chainId, appDid) {
653
+ if (this.#switchboard) return this.#switchboard.getCredential({
654
+ address,
655
+ chainId,
656
+ appDid
657
+ });
658
+ if (!this.#baseUrl) throw new Error("RENOWN_URL is not set");
659
+ const url = new URL(`/api/auth/credential?address=${encodeURIComponent(address)}&chainId=${encodeURIComponent(chainId)}&connectId=${encodeURIComponent(appDid)}&appId=${encodeURIComponent(appDid)}`, this.#baseUrl);
660
+ const response = await fetch(url, { method: "GET" });
661
+ if (response.ok) return (await response.json()).credential;
662
+ else throw new Error(`Failed to get credential: ${response.status}`);
663
+ }
664
+ async verifyBearerToken(token) {
665
+ return verifyAuthBearerToken(token);
666
+ }
667
+ async getBearerToken(options) {
668
+ if (!this.user) throw new Error("User not found");
669
+ return this.#crypto.getBearerToken(this.user.address, options);
670
+ }
671
+ };
672
+ //#endregion
673
+ //#region src/event/memory.ts
674
+ var MemoryEventEmitter = class {
675
+ #listeners = /* @__PURE__ */ new Map();
676
+ on(event, listener) {
677
+ if (!this.#listeners.has(event)) this.#listeners.set(event, /* @__PURE__ */ new Set());
678
+ this.#listeners.get(event).add(listener);
679
+ return () => {
680
+ this.#listeners.get(event)?.delete(listener);
681
+ };
682
+ }
683
+ emit(event, data) {
684
+ this.#listeners.get(event)?.forEach((listener) => listener(data));
685
+ }
686
+ };
687
+ //#endregion
688
+ //#region src/profile.ts
689
+ const fetchRenownProfile = async (user, baseUrl) => {
690
+ try {
691
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/profile`, {
692
+ method: "POST",
693
+ headers: { "Content-Type": "application/json" },
694
+ body: JSON.stringify({ ethAddress: user.address })
695
+ });
696
+ if (!response.ok) return;
697
+ return (await response.json()).profile ?? void 0;
698
+ } catch {
699
+ return;
700
+ }
701
+ };
702
+ //#endregion
703
+ //#region src/renown-builder.ts
704
+ /**
705
+ * Base builder for creating Renown instances.
706
+ * Use platform-specific builders (RenownBuilder from init.browser.js or init.node.js)
707
+ * for pre-configured defaults.
708
+ */
709
+ var BaseRenownBuilder = class BaseRenownBuilder {
710
+ #appName;
711
+ #storage;
712
+ #eventEmitter;
713
+ #crypto;
714
+ #keyPairStorage;
715
+ #baseUrl;
716
+ #switchboardUrl;
717
+ #profileFetcher;
718
+ #chainId;
719
+ /**
720
+ * @param appName - Application name used for signing context
721
+ */
722
+ constructor(appName) {
723
+ this.#appName = appName;
724
+ }
725
+ /**
726
+ * Set custom storage for user data persistence.
727
+ * Defaults to in-memory storage if not set.
728
+ */
729
+ withStorage(storage) {
730
+ this.#storage = storage;
731
+ return this;
732
+ }
733
+ /**
734
+ * Set custom event emitter for user state changes.
735
+ * Defaults to in-memory event emitter if not set.
736
+ */
737
+ withEventEmitter(eventEmitter) {
738
+ this.#eventEmitter = eventEmitter;
739
+ return this;
740
+ }
741
+ /**
742
+ * Set a pre-built crypto instance.
743
+ * Either crypto or keyPairStorage must be provided.
744
+ */
745
+ withCrypto(crypto) {
746
+ this.#crypto = crypto;
747
+ return this;
748
+ }
749
+ /**
750
+ * Set key pair storage for cryptographic keys.
751
+ * A crypto instance will be built from this storage.
752
+ * Either crypto or keyPairStorage must be provided.
753
+ */
754
+ withKeyPairStorage(keyPairStorage) {
755
+ this.#keyPairStorage = keyPairStorage;
756
+ return this;
757
+ }
758
+ /**
759
+ * Set the Renown server URL for credential verification.
760
+ * Defaults to https://www.renown.id
761
+ */
762
+ withBaseUrl(baseUrl) {
763
+ this.#baseUrl = baseUrl;
764
+ return this;
765
+ }
766
+ withSwitchboardUrl(switchboardUrl) {
767
+ this.#switchboardUrl = switchboardUrl;
768
+ return this;
769
+ }
770
+ withChainId(chainId) {
771
+ this.#chainId = chainId;
772
+ return this;
773
+ }
774
+ /**
775
+ * Set a profile fetcher strategy for enriching user data after login.
776
+ * The fetcher receives the authenticated user and the base URL,
777
+ * and returns a RenownProfile. Called in the background after each login.
778
+ * Defaults to fetchRenownProfile which calls the Renown API.
779
+ */
780
+ withProfileFetcher(profileFetcher) {
781
+ this.#profileFetcher = profileFetcher;
782
+ return this;
783
+ }
784
+ /**
785
+ * Build and initialize the Renown instance.
786
+ * If a user is stored, attempts to re-authenticate them.
787
+ * @throws Error if neither crypto nor keyPairStorage is provided
788
+ */
789
+ async build() {
790
+ if (!this.#crypto && !this.#keyPairStorage) throw new Error("Either crypto or keyPairStorage is required. Use withCrypto() or withKeyPairStorage() to set one.");
791
+ const chainId = this.#chainId ?? 1;
792
+ const crypto = this.#crypto ?? await new RenownCryptoBuilder().withKeyPairStorage(this.#keyPairStorage).withChainId(chainId).build();
793
+ if (crypto.chainId !== void 0 && crypto.chainId !== chainId) console.warn(`Renown: the supplied crypto signs bearer tokens for chain ${crypto.chainId}, but credentials are issued on chain ${chainId}.`);
794
+ const storage = this.#storage ?? new RenownMemoryStorage();
795
+ const eventEmitter = this.#eventEmitter ?? new MemoryEventEmitter();
796
+ const baseUrl = this.#baseUrl ?? "https://www.renown.id";
797
+ const switchboardEndpoint = await resolveSwitchboardEndpoint({
798
+ switchboardUrl: this.#switchboardUrl,
799
+ baseUrl
800
+ });
801
+ const switchboard = switchboardEndpoint ? new SwitchboardClient(switchboardEndpoint) : void 0;
802
+ const profileFetcher = this.#profileFetcher ?? (switchboard ? switchboard.profileFetcher : fetchRenownProfile);
803
+ return new Renown(storage, eventEmitter, crypto, this.#appName, baseUrl, profileFetcher, switchboard, chainId);
804
+ }
805
+ /**
806
+ * Create a BaseRenownBuilder from options object for a more concise API
807
+ */
808
+ static from(options) {
809
+ const builder = new BaseRenownBuilder(options.appName);
810
+ if (options.storage) builder.withStorage(options.storage);
811
+ if (options.eventEmitter) builder.withEventEmitter(options.eventEmitter);
812
+ if (options.crypto) builder.withCrypto(options.crypto);
813
+ if (options.keyPairStorage) builder.withKeyPairStorage(options.keyPairStorage);
814
+ if (options.baseUrl) builder.withBaseUrl(options.baseUrl);
815
+ if (options.switchboardUrl) builder.withSwitchboardUrl(options.switchboardUrl);
816
+ if (options.profileFetcher) builder.withProfileFetcher(options.profileFetcher);
817
+ if (options.chainId !== void 0) builder.withChainId(options.chainId);
818
+ return builder;
819
+ }
820
+ };
821
+ //#endregion
822
+ //#region src/local-credential-verifier.ts
823
+ /** A credential check that reads a Switchboard's own renown read model through
824
+ * `execute`, rather than any Renown or Switchboard over HTTP. */
825
+ function createLocalCredentialVerifier(execute, options = {}) {
826
+ const request = async (query, variables) => {
827
+ try {
828
+ return await execute(query, variables);
829
+ } catch (error) {
830
+ options.onError?.(error);
831
+ throw error;
832
+ }
833
+ };
834
+ return async ({ address, chainId, appId }) => {
835
+ return await fetchDelegationCredential({
836
+ address,
837
+ chainId,
838
+ appDid: appId,
839
+ switchboardRequest: request
840
+ }) !== void 0;
841
+ };
842
+ }
843
+ //#endregion
844
+ export { RenownMemoryStorage as a, fetchDelegationCredential as c, verifyCredentialSignature as d, SwitchboardClient as f, Renown as i, recoverCredentialSigner as l, BaseRenownBuilder as n, BaseStorage as o, resolveSwitchboardEndpoint as p, fetchRenownProfile as r, buildAndSignCredential as s, createLocalCredentialVerifier as t, verifyAuthCredential as u };
845
+
846
+ //# sourceMappingURL=local-credential-verifier-BcCzjvmd.js.map