@renown/sdk 6.2.2-dev.5 → 6.2.2-dev.51

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