ns-auth-sdk 1.2.6 → 1.3.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.mjs CHANGED
@@ -1,1223 +1,1359 @@
1
- import { NosskeyManager } from 'nosskey-sdk';
2
- import { useState, useEffect } from 'react';
3
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
- import { useZxing } from 'react-zxing';
5
- import { create } from 'zustand';
1
+ import { t as NosskeyManager } from "./utils-CV_lg5Ir.mjs";
2
+ import { useEffect, useState } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ import DOMPurify from "isomorphic-dompurify";
5
+ import { useZxing } from "react-zxing";
6
+ import { create } from "zustand";
6
7
 
7
- // src/services/auth.service.ts
8
+ //#region src/services/auth.service.ts
9
+ /**
10
+ * Service wrapper around NosskeyManager
11
+ * Handles WebAuthn/Passkey integration with Nostr
12
+ */
8
13
  var AuthService = class {
9
- constructor(config = {}) {
10
- this.manager = null;
11
- this.config = {
12
- rpId: config.rpId || (typeof window !== "undefined" ? window.location.hostname.replace(/^www\./, "") : "localhost"),
13
- rpName: config.rpName || this.getDefaultRpName(),
14
- storageKey: config.storageKey || "nsauth_keyinfo",
15
- cacheTimeoutMs: config.cacheTimeoutMs || 60 * 1e3
16
- };
17
- }
18
- getDefaultRpName() {
19
- if (typeof window === "undefined") return "localhost";
20
- const hostname = window.location.hostname;
21
- if (hostname.includes("nosskey.app")) return "nosskey.app";
22
- return hostname.replace(/^www\./, "");
23
- }
24
- /**
25
- * Initialize the NosskeyManager instance
26
- */
27
- getManager() {
28
- if (!this.manager) {
29
- this.manager = new NosskeyManager({
30
- cacheOptions: {
31
- enabled: true,
32
- timeoutMs: this.config.cacheTimeoutMs
33
- },
34
- storageOptions: {
35
- enabled: true,
36
- storageKey: this.config.storageKey
37
- }
38
- });
39
- }
40
- return this.manager;
41
- }
42
- /**
43
- * Create a new passkey
44
- * Uses platform authenticator only (Touch ID, Face ID, Windows Hello)
45
- */
46
- async createPasskey(username) {
47
- const manager = this.getManager();
48
- const rpId = this.config.rpId === "localhost" ? "localhost" : this.config.rpId;
49
- const rpName = this.config.rpName;
50
- const trimmedUsername = username?.trim();
51
- const uniqueUsername = trimmedUsername ? trimmedUsername : `user-${Date.now()}@example.com`;
52
- const options = {
53
- rp: {
54
- id: rpId,
55
- name: rpName
56
- },
57
- user: {
58
- name: uniqueUsername,
59
- displayName: trimmedUsername || "User"
60
- },
61
- authenticatorSelection: {
62
- authenticatorAttachment: "platform",
63
- residentKey: "preferred",
64
- userVerification: "preferred"
65
- },
66
- extensions: {
67
- prf: {}
68
- }
69
- };
70
- return await manager.createPasskey(options);
71
- }
72
- /**
73
- * Create a new Nostr key from a credential ID
74
- */
75
- async createNostrKey(credentialId) {
76
- const manager = this.getManager();
77
- return await manager.createNostrKey(credentialId);
78
- }
79
- /**
80
- * Get the current public key
81
- */
82
- async getPublicKey() {
83
- const manager = this.getManager();
84
- return await manager.getPublicKey();
85
- }
86
- /**
87
- * Sign a Nostr event
88
- */
89
- async signEvent(event) {
90
- const manager = this.getManager();
91
- return await manager.signEvent(event);
92
- }
93
- /**
94
- * Get current key info
95
- */
96
- getCurrentKeyInfo() {
97
- const manager = this.getManager();
98
- return manager.getCurrentKeyInfo();
99
- }
100
- /**
101
- * Set current key info
102
- */
103
- setCurrentKeyInfo(keyInfo) {
104
- const manager = this.getManager();
105
- manager.setCurrentKeyInfo(keyInfo);
106
- }
107
- /**
108
- * Check if key info exists
109
- */
110
- hasKeyInfo() {
111
- const manager = this.getManager();
112
- return manager.hasKeyInfo();
113
- }
114
- /**
115
- * Clear stored key info
116
- */
117
- clearStoredKeyInfo() {
118
- const manager = this.getManager();
119
- manager.clearStoredKeyInfo();
120
- }
121
- /**
122
- * Check if PRF is supported
123
- */
124
- async isPrfSupported() {
125
- const { isPrfSupported } = await import('nosskey-sdk');
126
- return await isPrfSupported();
127
- }
14
+ constructor(config = {}) {
15
+ this.manager = null;
16
+ this.config = {
17
+ rpId: config.rpId || (typeof window !== "undefined" ? window.location.hostname.replace(/^www\./, "") : "localhost"),
18
+ rpName: config.rpName || this.getDefaultRpName(),
19
+ storageKey: config.storageKey || "nsauth_keyinfo",
20
+ cacheTimeoutMs: config.cacheTimeoutMs || 1800 * 1e3
21
+ };
22
+ }
23
+ getDefaultRpName() {
24
+ if (typeof window === "undefined") return "localhost";
25
+ const hostname = window.location.hostname;
26
+ if (hostname.includes("nosskey.app")) return "nosskey.app";
27
+ return hostname.replace(/^www\./, "");
28
+ }
29
+ /**
30
+ * Initialize the NosskeyManager instance
31
+ */
32
+ getManager() {
33
+ if (!this.manager) this.manager = new NosskeyManager({
34
+ cacheOptions: {
35
+ enabled: true,
36
+ timeoutMs: this.config.cacheTimeoutMs
37
+ },
38
+ storageOptions: {
39
+ enabled: true,
40
+ storageKey: this.config.storageKey
41
+ }
42
+ });
43
+ return this.manager;
44
+ }
45
+ /**
46
+ * Create a new passkey
47
+ * Uses platform authenticator only (Touch ID, Face ID, Windows Hello)
48
+ */
49
+ async createPasskey(username) {
50
+ const manager = this.getManager();
51
+ const rpId = this.config.rpId === "localhost" ? "localhost" : this.config.rpId;
52
+ const rpName = this.config.rpName;
53
+ const trimmedUsername = username?.trim();
54
+ const uniqueUsername = trimmedUsername ? trimmedUsername : `user-${Date.now()}@example.com`;
55
+ const options = {
56
+ rp: {
57
+ id: rpId,
58
+ name: rpName
59
+ },
60
+ user: {
61
+ name: uniqueUsername,
62
+ displayName: trimmedUsername || "User"
63
+ },
64
+ authenticatorSelection: {
65
+ authenticatorAttachment: "platform",
66
+ residentKey: "preferred",
67
+ userVerification: "preferred"
68
+ },
69
+ extensions: { prf: {} }
70
+ };
71
+ return await manager.createPasskey(options);
72
+ }
73
+ /**
74
+ * Create a new Nostr key from a credential ID
75
+ */
76
+ async createNostrKey(credentialId) {
77
+ return await this.getManager().createNostrKey(credentialId);
78
+ }
79
+ /**
80
+ * Get the current public key
81
+ */
82
+ async getPublicKey() {
83
+ return await this.getManager().getPublicKey();
84
+ }
85
+ /**
86
+ * Sign a Nostr event
87
+ */
88
+ async signEvent(event) {
89
+ return await this.getManager().signEvent(event);
90
+ }
91
+ /**
92
+ * Get current key info
93
+ */
94
+ getCurrentKeyInfo() {
95
+ return this.getManager().getCurrentKeyInfo();
96
+ }
97
+ /**
98
+ * Set current key info
99
+ */
100
+ setCurrentKeyInfo(keyInfo) {
101
+ this.getManager().setCurrentKeyInfo(keyInfo);
102
+ }
103
+ /**
104
+ * Check if key info exists
105
+ */
106
+ hasKeyInfo() {
107
+ return this.getManager().hasKeyInfo();
108
+ }
109
+ /**
110
+ * Clear stored key info
111
+ */
112
+ clearStoredKeyInfo() {
113
+ this.getManager().clearStoredKeyInfo();
114
+ }
115
+ /**
116
+ * Check if PRF is supported
117
+ */
118
+ async isPrfSupported() {
119
+ const { isPrfSupported } = await import("./utils-BVvtCpMQ.mjs");
120
+ return await isPrfSupported();
121
+ }
128
122
  };
129
123
 
130
- // src/services/relay.service.ts
124
+ //#endregion
125
+ //#region src/utils/validation.ts
126
+ const MAX_ROLE_LENGTH = 100;
127
+ const ROLE_PATTERN = /^[a-zA-Z0-9\s\-_]+$/;
128
+ const isValidRoleTag = (role) => {
129
+ const trimmed = role.trim();
130
+ return trimmed.length > 0 && trimmed.length <= MAX_ROLE_LENGTH && ROLE_PATTERN.test(trimmed);
131
+ };
132
+ const isValidPubkey = (pubkey) => pubkey.length === 64 && /^[0-9a-fA-F]+$/.test(pubkey);
133
+ const isValidHttpUrl = (url) => {
134
+ try {
135
+ const parsed = new URL(url);
136
+ return ["http:", "https:"].includes(parsed.protocol);
137
+ } catch {
138
+ return false;
139
+ }
140
+ };
141
+ const isValidRelayUrl = (url) => {
142
+ try {
143
+ const parsed = new URL(url);
144
+ return ["ws:", "wss:"].includes(parsed.protocol) && parsed.hostname.length > 0;
145
+ } catch {
146
+ return false;
147
+ }
148
+ };
149
+
150
+ //#endregion
151
+ //#region src/services/relay.service.ts
152
+ /**
153
+ * Service for communicating with Nostr relays using applesauce-core
154
+ */
131
155
  var RelayService = class {
132
- constructor(config = {}) {
133
- this.eventStore = null;
134
- this.defaultRelays = ["wss://relay.damus.io"];
135
- this.relayUrls = config.relayUrls || this.defaultRelays;
136
- }
137
- /**
138
- * Initialize with applesauce EventStore
139
- */
140
- initialize(eventStore) {
141
- this.eventStore = eventStore;
142
- if (eventStore && "setRelays" in eventStore && typeof eventStore.setRelays === "function") {
143
- eventStore.setRelays(this.relayUrls);
144
- }
145
- }
146
- /**
147
- * Set relay URLs
148
- */
149
- setRelays(urls) {
150
- this.relayUrls = urls;
151
- if (this.eventStore && "setRelays" in this.eventStore && typeof this.eventStore.setRelays === "function") {
152
- this.eventStore.setRelays(urls);
153
- }
154
- }
155
- /**
156
- * Publish an event to relays
157
- */
158
- async publishEvent(event, timeoutMs = 1e3) {
159
- if (!this.eventStore) {
160
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
161
- }
162
- return new Promise((resolve, reject) => {
163
- if (this.relayUrls.length === 0) {
164
- reject(new Error("No relays configured"));
165
- return;
166
- }
167
- const eventStore = this.eventStore;
168
- if (!eventStore || typeof eventStore.publish !== "function") {
169
- reject(new Error("EventStore does not support publish method"));
170
- return;
171
- }
172
- const subscription = eventStore.publish(event).subscribe({
173
- next: (response) => {
174
- if (response?.type === "OK") {
175
- subscription.unsubscribe();
176
- resolve(true);
177
- }
178
- },
179
- error: (error) => {
180
- subscription.unsubscribe();
181
- reject(error);
182
- }
183
- });
184
- setTimeout(() => {
185
- subscription.unsubscribe();
186
- resolve(false);
187
- }, timeoutMs);
188
- });
189
- }
190
- /**
191
- * Fetch a profile (Kind 0 event)
192
- */
193
- async fetchProfile(pubkey) {
194
- if (!this.eventStore) {
195
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
196
- }
197
- return new Promise((resolve) => {
198
- const filter = {
199
- kinds: [0],
200
- authors: [pubkey],
201
- limit: 1
202
- };
203
- const eventStore = this.eventStore;
204
- if (!eventStore || typeof eventStore.query !== "function") {
205
- resolve(null);
206
- return;
207
- }
208
- const subscription = eventStore.query(filter).subscribe({
209
- next: (packet) => {
210
- if (packet?.event && packet.event.kind === 0) {
211
- try {
212
- const metadata = JSON.parse(packet.event.content);
213
- subscription.unsubscribe();
214
- resolve(metadata);
215
- } catch (error) {
216
- console.error("Failed to parse profile metadata:", error);
217
- }
218
- }
219
- },
220
- complete: () => {
221
- subscription.unsubscribe();
222
- resolve(null);
223
- },
224
- error: (error) => {
225
- console.error("Error fetching profile:", error);
226
- subscription.unsubscribe();
227
- resolve(null);
228
- }
229
- });
230
- setTimeout(() => {
231
- subscription.unsubscribe();
232
- resolve(null);
233
- }, 5e3);
234
- });
235
- }
236
- /**
237
- * Fetch role tag from profile event (Kind 0)
238
- */
239
- async fetchProfileRoleTag(pubkey) {
240
- if (!this.eventStore) {
241
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
242
- }
243
- return new Promise((resolve) => {
244
- const filter = {
245
- kinds: [0],
246
- authors: [pubkey],
247
- limit: 1
248
- };
249
- const eventStore = this.eventStore;
250
- if (!eventStore || typeof eventStore.query !== "function") {
251
- resolve(null);
252
- return;
253
- }
254
- const subscription = eventStore.query(filter).subscribe({
255
- next: (packet) => {
256
- if (packet?.event && packet.event.kind === 0) {
257
- const tags = packet.event.tags || [];
258
- for (const tag of tags) {
259
- if (tag[0] === "role" && tag[1]) {
260
- subscription.unsubscribe();
261
- resolve(tag[1]);
262
- return;
263
- }
264
- }
265
- subscription.unsubscribe();
266
- resolve(null);
267
- }
268
- },
269
- complete: () => {
270
- subscription.unsubscribe();
271
- resolve(null);
272
- },
273
- error: (error) => {
274
- console.error("Error fetching profile role tag:", error);
275
- subscription.unsubscribe();
276
- resolve(null);
277
- }
278
- });
279
- setTimeout(() => {
280
- subscription.unsubscribe();
281
- resolve(null);
282
- }, 5e3);
283
- });
284
- }
285
- /**
286
- * Fetch a follow list (Kind 3 event)
287
- */
288
- async fetchFollowList(pubkey) {
289
- if (!this.eventStore) {
290
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
291
- }
292
- return new Promise((resolve) => {
293
- const filter = {
294
- kinds: [3],
295
- authors: [pubkey],
296
- limit: 1
297
- };
298
- const eventStore = this.eventStore;
299
- if (!eventStore || typeof eventStore.query !== "function") {
300
- resolve([]);
301
- return;
302
- }
303
- const subscription = eventStore.query(filter).subscribe({
304
- next: (packet) => {
305
- if (packet?.event && packet.event.kind === 3) {
306
- const followList = [];
307
- const tags = packet.event.tags || [];
308
- for (const tag of tags) {
309
- if (tag[0] === "p" && tag[1]) {
310
- followList.push({
311
- pubkey: tag[1],
312
- relay: tag[2] || void 0,
313
- petname: tag[3] || void 0
314
- });
315
- }
316
- }
317
- subscription.unsubscribe();
318
- resolve(followList);
319
- }
320
- },
321
- complete: () => {
322
- subscription.unsubscribe();
323
- resolve([]);
324
- },
325
- error: (error) => {
326
- console.error("Error fetching follow list:", error);
327
- subscription.unsubscribe();
328
- resolve([]);
329
- }
330
- });
331
- setTimeout(() => {
332
- subscription.unsubscribe();
333
- resolve([]);
334
- }, 1e4);
335
- });
336
- }
337
- /**
338
- * Fetch multiple profiles in batch
339
- */
340
- async fetchMultipleProfiles(pubkeys) {
341
- if (!this.eventStore) {
342
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
343
- }
344
- if (pubkeys.length === 0) {
345
- return /* @__PURE__ */ new Map();
346
- }
347
- return new Promise((resolve) => {
348
- const profiles = /* @__PURE__ */ new Map();
349
- const filter = {
350
- kinds: [0],
351
- authors: pubkeys
352
- };
353
- const eventStore = this.eventStore;
354
- if (!eventStore || typeof eventStore.query !== "function") {
355
- resolve(/* @__PURE__ */ new Map());
356
- return;
357
- }
358
- const subscription = eventStore.query(filter).subscribe({
359
- next: (packet) => {
360
- if (packet?.event && packet.event.kind === 0 && packet.event.pubkey) {
361
- try {
362
- const metadata = JSON.parse(packet.event.content);
363
- profiles.set(packet.event.pubkey, metadata);
364
- } catch (error) {
365
- console.error("Failed to parse profile metadata:", error);
366
- }
367
- }
368
- },
369
- complete: () => {
370
- subscription.unsubscribe();
371
- resolve(profiles);
372
- },
373
- error: (error) => {
374
- console.error("Error fetching profiles:", error);
375
- subscription.unsubscribe();
376
- resolve(profiles);
377
- }
378
- });
379
- setTimeout(() => {
380
- subscription.unsubscribe();
381
- resolve(profiles);
382
- }, 1e3);
383
- });
384
- }
385
- /**
386
- * Query kind 0 events (profiles) by pubkey
387
- * If pubkeys array is empty, fetches recent kind 0 events
388
- */
389
- async queryProfiles(pubkeys = [], limit = 100) {
390
- if (!this.eventStore) {
391
- throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
392
- }
393
- return new Promise((resolve) => {
394
- const profiles = /* @__PURE__ */ new Map();
395
- const filter = {
396
- kinds: [0],
397
- limit
398
- };
399
- if (pubkeys.length > 0) {
400
- filter.authors = pubkeys;
401
- }
402
- const eventStore = this.eventStore;
403
- if (!eventStore || typeof eventStore.query !== "function") {
404
- resolve(/* @__PURE__ */ new Map());
405
- return;
406
- }
407
- const subscription = eventStore.query(filter).subscribe({
408
- next: (packet) => {
409
- if (packet?.event && packet.event.kind === 0 && packet.event.pubkey) {
410
- try {
411
- const metadata = JSON.parse(packet.event.content);
412
- const timestamp = packet.event.created_at || 0;
413
- const existing = profiles.get(packet.event.pubkey);
414
- if (!existing || timestamp > existing.timestamp) {
415
- profiles.set(packet.event.pubkey, { metadata, timestamp });
416
- }
417
- } catch (error) {
418
- console.error("Failed to parse profile metadata:", error);
419
- }
420
- }
421
- },
422
- complete: () => {
423
- subscription.unsubscribe();
424
- const result = /* @__PURE__ */ new Map();
425
- profiles.forEach((value, pubkey) => {
426
- result.set(pubkey, value.metadata);
427
- });
428
- resolve(result);
429
- },
430
- error: (error) => {
431
- console.error("Error querying profiles:", error);
432
- subscription.unsubscribe();
433
- const result = /* @__PURE__ */ new Map();
434
- profiles.forEach((value, pubkey) => {
435
- result.set(pubkey, value.metadata);
436
- });
437
- resolve(result);
438
- }
439
- });
440
- setTimeout(() => {
441
- subscription.unsubscribe();
442
- const result = /* @__PURE__ */ new Map();
443
- profiles.forEach((value, pubkey) => {
444
- result.set(pubkey, value.metadata);
445
- });
446
- resolve(result);
447
- }, 1e4);
448
- });
449
- }
450
- /**
451
- * Publish or update a kind 3 event (follow list/contacts)
452
- */
453
- async publishFollowList(pubkey, followList, signEvent) {
454
- const tags = followList.map((entry) => {
455
- const tag = ["p", entry.pubkey];
456
- if (entry.relay) {
457
- tag.push(entry.relay);
458
- }
459
- if (entry.petname) {
460
- tag.push(entry.petname);
461
- }
462
- return tag;
463
- });
464
- const event = {
465
- kind: 3,
466
- content: "",
467
- created_at: Math.floor(Date.now() / 1e3),
468
- tags
469
- };
470
- const signedEvent = await signEvent(event);
471
- return await this.publishEvent(signedEvent);
472
- }
156
+ constructor(config = {}) {
157
+ this.eventStore = null;
158
+ this.defaultRelays = ["wss://relay.damus.io"];
159
+ this.maxProfileContentSize = 1e4;
160
+ this.minProfileQueryIntervalMs = 300;
161
+ this.minPublishIntervalMs = 750;
162
+ this.lastActionAt = /* @__PURE__ */ new Map();
163
+ this.relayUrls = this.validateRelayUrls(config.relayUrls ?? this.defaultRelays);
164
+ }
165
+ /**
166
+ * Initialize with applesauce EventStore
167
+ */
168
+ initialize(eventStore) {
169
+ this.eventStore = eventStore;
170
+ if (eventStore && "setRelays" in eventStore && typeof eventStore.setRelays === "function") eventStore.setRelays(this.relayUrls);
171
+ }
172
+ /**
173
+ * Set relay URLs
174
+ */
175
+ setRelays(urls) {
176
+ this.relayUrls = this.validateRelayUrls(urls);
177
+ if (this.eventStore && "setRelays" in this.eventStore && typeof this.eventStore.setRelays === "function") this.eventStore.setRelays(this.relayUrls);
178
+ }
179
+ /**
180
+ * Get current relay URLs
181
+ */
182
+ getRelays() {
183
+ return [...this.relayUrls];
184
+ }
185
+ /**
186
+ * Publish an event to relays
187
+ */
188
+ async publishEvent(event, timeoutMs = 1e3) {
189
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
190
+ await this.enforceRateLimit("publish", this.minPublishIntervalMs);
191
+ return new Promise((resolve, reject) => {
192
+ if (this.relayUrls.length === 0) {
193
+ reject(/* @__PURE__ */ new Error("No relays configured"));
194
+ return;
195
+ }
196
+ const eventStore = this.eventStore;
197
+ if (!eventStore || typeof eventStore.publish !== "function") {
198
+ reject(/* @__PURE__ */ new Error("EventStore does not support publish method"));
199
+ return;
200
+ }
201
+ const subscription = eventStore.publish(event).subscribe({
202
+ next: (response) => {
203
+ if (response?.type === "OK") {
204
+ subscription.unsubscribe();
205
+ resolve(true);
206
+ }
207
+ },
208
+ error: (error) => {
209
+ subscription.unsubscribe();
210
+ reject(error);
211
+ }
212
+ });
213
+ setTimeout(() => {
214
+ subscription.unsubscribe();
215
+ resolve(false);
216
+ }, timeoutMs);
217
+ });
218
+ }
219
+ /**
220
+ * Fetch a profile (Kind 0 event)
221
+ */
222
+ async fetchProfile(pubkey) {
223
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
224
+ await this.enforceRateLimit("fetch-profile", this.minProfileQueryIntervalMs);
225
+ return new Promise((resolve) => {
226
+ const filter = {
227
+ kinds: [0],
228
+ authors: [pubkey],
229
+ limit: 1
230
+ };
231
+ const eventStore = this.eventStore;
232
+ if (!eventStore || typeof eventStore.query !== "function") {
233
+ resolve(null);
234
+ return;
235
+ }
236
+ const subscription = eventStore.query(filter).subscribe({
237
+ next: (packet) => {
238
+ if (packet?.event && packet.event.kind === 0) {
239
+ const metadata = this.parseProfileMetadata(packet.event.content);
240
+ if (metadata) {
241
+ subscription.unsubscribe();
242
+ resolve(metadata);
243
+ return;
244
+ }
245
+ console.error("Failed to parse profile metadata");
246
+ }
247
+ },
248
+ complete: () => {
249
+ subscription.unsubscribe();
250
+ resolve(null);
251
+ },
252
+ error: (error) => {
253
+ console.error("Error fetching profile:", error);
254
+ subscription.unsubscribe();
255
+ resolve(null);
256
+ }
257
+ });
258
+ setTimeout(() => {
259
+ subscription.unsubscribe();
260
+ resolve(null);
261
+ }, 5e3);
262
+ });
263
+ }
264
+ /**
265
+ * Fetch role tag from profile event (Kind 0)
266
+ */
267
+ async fetchProfileRoleTag(pubkey) {
268
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
269
+ await this.enforceRateLimit("fetch-role-tag", this.minProfileQueryIntervalMs);
270
+ return new Promise((resolve) => {
271
+ const filter = {
272
+ kinds: [0],
273
+ authors: [pubkey],
274
+ limit: 1
275
+ };
276
+ const eventStore = this.eventStore;
277
+ if (!eventStore || typeof eventStore.query !== "function") {
278
+ resolve(null);
279
+ return;
280
+ }
281
+ const subscription = eventStore.query(filter).subscribe({
282
+ next: (packet) => {
283
+ if (packet?.event && packet.event.kind === 0) {
284
+ const tags = packet.event.tags || [];
285
+ for (const tag of tags) if (tag[0] === "role" && tag[1]) {
286
+ const candidate = tag[1].trim();
287
+ if (isValidRoleTag(candidate)) {
288
+ subscription.unsubscribe();
289
+ resolve(candidate);
290
+ return;
291
+ }
292
+ }
293
+ subscription.unsubscribe();
294
+ resolve(null);
295
+ }
296
+ },
297
+ complete: () => {
298
+ subscription.unsubscribe();
299
+ resolve(null);
300
+ },
301
+ error: (error) => {
302
+ console.error("Error fetching profile role tag:", error);
303
+ subscription.unsubscribe();
304
+ resolve(null);
305
+ }
306
+ });
307
+ setTimeout(() => {
308
+ subscription.unsubscribe();
309
+ resolve(null);
310
+ }, 5e3);
311
+ });
312
+ }
313
+ /**
314
+ * Fetch a follow list (Kind 3 event)
315
+ */
316
+ async fetchFollowList(pubkey) {
317
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
318
+ await this.enforceRateLimit("fetch-follow-list", this.minProfileQueryIntervalMs);
319
+ return new Promise((resolve) => {
320
+ const filter = {
321
+ kinds: [3],
322
+ authors: [pubkey],
323
+ limit: 1
324
+ };
325
+ const eventStore = this.eventStore;
326
+ if (!eventStore || typeof eventStore.query !== "function") {
327
+ resolve([]);
328
+ return;
329
+ }
330
+ const subscription = eventStore.query(filter).subscribe({
331
+ next: (packet) => {
332
+ if (packet?.event && packet.event.kind === 3) {
333
+ const followList = [];
334
+ const tags = packet.event.tags || [];
335
+ for (const tag of tags) if (tag[0] === "p" && tag[1]) followList.push({
336
+ pubkey: tag[1],
337
+ relay: tag[2] || void 0,
338
+ petname: tag[3] || void 0
339
+ });
340
+ subscription.unsubscribe();
341
+ resolve(followList);
342
+ }
343
+ },
344
+ complete: () => {
345
+ subscription.unsubscribe();
346
+ resolve([]);
347
+ },
348
+ error: (error) => {
349
+ console.error("Error fetching follow list:", error);
350
+ subscription.unsubscribe();
351
+ resolve([]);
352
+ }
353
+ });
354
+ setTimeout(() => {
355
+ subscription.unsubscribe();
356
+ resolve([]);
357
+ }, 1e4);
358
+ });
359
+ }
360
+ /**
361
+ * Fetch multiple profiles in batch
362
+ */
363
+ async fetchMultipleProfiles(pubkeys) {
364
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
365
+ if (pubkeys.length === 0) return /* @__PURE__ */ new Map();
366
+ await this.enforceRateLimit("fetch-multiple-profiles", this.minProfileQueryIntervalMs);
367
+ return new Promise((resolve) => {
368
+ const profiles = /* @__PURE__ */ new Map();
369
+ const filter = {
370
+ kinds: [0],
371
+ authors: pubkeys
372
+ };
373
+ const eventStore = this.eventStore;
374
+ if (!eventStore || typeof eventStore.query !== "function") {
375
+ resolve(/* @__PURE__ */ new Map());
376
+ return;
377
+ }
378
+ const subscription = eventStore.query(filter).subscribe({
379
+ next: (packet) => {
380
+ if (packet?.event && packet.event.kind === 0 && packet.event.pubkey) {
381
+ const metadata = this.parseProfileMetadata(packet.event.content);
382
+ if (metadata) profiles.set(packet.event.pubkey, metadata);
383
+ else console.error("Failed to parse profile metadata");
384
+ }
385
+ },
386
+ complete: () => {
387
+ subscription.unsubscribe();
388
+ resolve(profiles);
389
+ },
390
+ error: (error) => {
391
+ console.error("Error fetching profiles:", error);
392
+ subscription.unsubscribe();
393
+ resolve(profiles);
394
+ }
395
+ });
396
+ setTimeout(() => {
397
+ subscription.unsubscribe();
398
+ resolve(profiles);
399
+ }, 1e3);
400
+ });
401
+ }
402
+ /**
403
+ * Query kind 0 events (profiles) by pubkey
404
+ * If pubkeys array is empty, fetches recent kind 0 events
405
+ */
406
+ async queryProfiles(pubkeys = [], limit = 100) {
407
+ if (!this.eventStore) throw new Error("RelayService not initialized. Call initialize() with an EventStore instance.");
408
+ await this.enforceRateLimit("query-profiles", this.minProfileQueryIntervalMs);
409
+ return new Promise((resolve) => {
410
+ const profiles = /* @__PURE__ */ new Map();
411
+ const filter = {
412
+ kinds: [0],
413
+ limit
414
+ };
415
+ if (pubkeys.length > 0) filter.authors = pubkeys;
416
+ const eventStore = this.eventStore;
417
+ if (!eventStore || typeof eventStore.query !== "function") {
418
+ resolve(/* @__PURE__ */ new Map());
419
+ return;
420
+ }
421
+ const subscription = eventStore.query(filter).subscribe({
422
+ next: (packet) => {
423
+ if (packet?.event && packet.event.kind === 0 && packet.event.pubkey) {
424
+ const metadata = this.parseProfileMetadata(packet.event.content);
425
+ if (metadata) {
426
+ const timestamp = packet.event.created_at || 0;
427
+ const existing = profiles.get(packet.event.pubkey);
428
+ if (!existing || timestamp > existing.timestamp) profiles.set(packet.event.pubkey, {
429
+ metadata,
430
+ timestamp
431
+ });
432
+ } else console.error("Failed to parse profile metadata");
433
+ }
434
+ },
435
+ complete: () => {
436
+ subscription.unsubscribe();
437
+ const result = /* @__PURE__ */ new Map();
438
+ profiles.forEach((value, pubkey) => {
439
+ result.set(pubkey, value.metadata);
440
+ });
441
+ resolve(result);
442
+ },
443
+ error: (error) => {
444
+ console.error("Error querying profiles:", error);
445
+ subscription.unsubscribe();
446
+ const result = /* @__PURE__ */ new Map();
447
+ profiles.forEach((value, pubkey) => {
448
+ result.set(pubkey, value.metadata);
449
+ });
450
+ resolve(result);
451
+ }
452
+ });
453
+ setTimeout(() => {
454
+ subscription.unsubscribe();
455
+ const result = /* @__PURE__ */ new Map();
456
+ profiles.forEach((value, pubkey) => {
457
+ result.set(pubkey, value.metadata);
458
+ });
459
+ resolve(result);
460
+ }, 1e4);
461
+ });
462
+ }
463
+ /**
464
+ * Publish or update a kind 3 event (follow list/contacts)
465
+ */
466
+ async publishFollowList(pubkey, followList, signEvent) {
467
+ const tags = followList.map((entry) => {
468
+ if (!isValidPubkey(entry.pubkey)) throw new Error("Invalid pubkey format for follow list entry.");
469
+ if (entry.relay && !isValidRelayUrl(entry.relay)) throw new Error("Invalid relay URL format for follow list entry.");
470
+ const tag = ["p", entry.pubkey];
471
+ if (entry.relay) tag.push(entry.relay);
472
+ if (entry.petname) tag.push(entry.petname);
473
+ return tag;
474
+ });
475
+ const signedEvent = await signEvent({
476
+ kind: 3,
477
+ content: "",
478
+ created_at: Math.floor(Date.now() / 1e3),
479
+ tags
480
+ });
481
+ return await this.publishEvent(signedEvent);
482
+ }
483
+ validateRelayUrls(urls) {
484
+ if (urls.length === 0) return [];
485
+ const validUrls = urls.filter((url) => isValidRelayUrl(url));
486
+ if (validUrls.length !== urls.length) throw new Error("Invalid relay URL format");
487
+ return validUrls;
488
+ }
489
+ parseProfileMetadata(content) {
490
+ if (content.length > this.maxProfileContentSize) return null;
491
+ try {
492
+ const parsed = JSON.parse(content);
493
+ if (!parsed || typeof parsed !== "object") return null;
494
+ const metadata = {};
495
+ if (typeof parsed.name === "string") metadata.name = parsed.name;
496
+ if (typeof parsed.display_name === "string") metadata.display_name = parsed.display_name;
497
+ if (typeof parsed.about === "string") metadata.about = parsed.about;
498
+ if (typeof parsed.picture === "string") metadata.picture = parsed.picture;
499
+ if (typeof parsed.website === "string") metadata.website = parsed.website;
500
+ return metadata;
501
+ } catch (error) {
502
+ console.error("Failed to parse profile metadata:", error);
503
+ return null;
504
+ }
505
+ }
506
+ async enforceRateLimit(action, minIntervalMs) {
507
+ const lastAt = this.lastActionAt.get(action) ?? 0;
508
+ const waitMs = minIntervalMs - (Date.now() - lastAt);
509
+ if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
510
+ this.lastActionAt.set(action, Date.now());
511
+ }
473
512
  };
474
- function LoginButton({
475
- authService,
476
- setAuthenticated,
477
- setLoginError,
478
- onSuccess
479
- }) {
480
- const [isLoading, setIsLoading] = useState(false);
481
- const handleLogin = async () => {
482
- setIsLoading(true);
483
- setLoginError(null);
484
- try {
485
- if (!authService.hasKeyInfo()) {
486
- throw new Error("No account found. Please register first.");
487
- }
488
- const keyInfo = authService.getCurrentKeyInfo();
489
- if (!keyInfo) {
490
- throw new Error("Failed to load account information.");
491
- }
492
- await authService.getPublicKey();
493
- setAuthenticated(keyInfo);
494
- if (onSuccess) {
495
- onSuccess();
496
- }
497
- } catch (err) {
498
- console.error("Login error:", err);
499
- const errorMessage = err instanceof Error ? err.message : "Failed to login";
500
- setLoginError(errorMessage);
501
- setIsLoading(false);
502
- }
503
- };
504
- return /* @__PURE__ */ jsx("div", { className: "login-button-container", children: /* @__PURE__ */ jsx(
505
- "button",
506
- {
507
- className: "auth-button secondary",
508
- onClick: handleLogin,
509
- disabled: isLoading,
510
- children: isLoading ? "Logging in..." : "Login"
511
- }
512
- ) });
513
+
514
+ //#endregion
515
+ //#region src/components/auth/LoginButton.tsx
516
+ function LoginButton({ authService, setAuthenticated, setLoginError, onSuccess }) {
517
+ const [isLoading, setIsLoading] = useState(false);
518
+ const handleLogin = async () => {
519
+ setIsLoading(true);
520
+ setLoginError(null);
521
+ try {
522
+ if (!authService.hasKeyInfo()) throw new Error("No account found. Please register first.");
523
+ const keyInfo = authService.getCurrentKeyInfo();
524
+ if (!keyInfo) throw new Error("Failed to load account information.");
525
+ await authService.getPublicKey();
526
+ setAuthenticated(keyInfo);
527
+ if (onSuccess) onSuccess();
528
+ } catch (err) {
529
+ console.error("Login error:", err);
530
+ setLoginError(err instanceof Error ? err.message : "Failed to login");
531
+ setIsLoading(false);
532
+ }
533
+ };
534
+ return /* @__PURE__ */ jsx("div", {
535
+ className: "login-button-container",
536
+ children: /* @__PURE__ */ jsx("button", {
537
+ className: "auth-button secondary",
538
+ onClick: handleLogin,
539
+ disabled: isLoading,
540
+ children: isLoading ? "Logging in..." : "Login"
541
+ })
542
+ });
513
543
  }
514
- function RegistrationFlow({
515
- authService,
516
- setAuthenticated,
517
- onSuccess
518
- }) {
519
- const [isLoading, setIsLoading] = useState(false);
520
- const [error, setError] = useState(null);
521
- const [step, setStep] = useState("info");
522
- const [username, setUsername] = useState("");
523
- const handleRegister = async () => {
524
- setIsLoading(true);
525
- setError(null);
526
- setStep("creating");
527
- try {
528
- authService.clearStoredKeyInfo();
529
- let credentialId;
530
- const passkeyUsername = username.trim() || void 0;
531
- try {
532
- credentialId = await authService.createPasskey(passkeyUsername);
533
- } catch (passkeyError) {
534
- console.error("[RegistrationFlow] Passkey creation failed:", passkeyError);
535
- const errorMessage = passkeyError instanceof Error ? passkeyError.message : String(passkeyError);
536
- if (errorMessage.includes("NotAllowedError") || errorMessage.includes("user")) {
537
- throw new Error(
538
- "Passkey creation was cancelled or not allowed. Please try again and complete the authentication prompt."
539
- );
540
- } else if (errorMessage.includes("NotSupportedError") || errorMessage.includes("PRF")) {
541
- throw new Error(
542
- "WebAuthn PRF extension is not supported in your browser. Please use Chrome 118+, Safari 17+, or a compatible browser."
543
- );
544
- }
545
- throw new Error(`Failed to create passkey: ${errorMessage}`);
546
- }
547
- let keyInfo;
548
- try {
549
- keyInfo = await authService.createNostrKey(credentialId);
550
- } catch (nostrKeyError) {
551
- console.error("[RegistrationFlow] Failed to create Nostr key from passkey:", nostrKeyError);
552
- const errorMessage = nostrKeyError instanceof Error ? nostrKeyError.message : String(nostrKeyError);
553
- if (errorMessage.includes("PRF secret not available") || errorMessage.includes("PRF")) {
554
- throw new Error(
555
- "PRF extension is required but not available. This may mean:\n1. Your browser doesn't support WebAuthn PRF extension (Chrome 118+, Safari 17+)\n2. The passkey was created without PRF support\nPlease try again or use a compatible browser."
556
- );
557
- }
558
- throw nostrKeyError;
559
- }
560
- authService.setCurrentKeyInfo(keyInfo);
561
- setAuthenticated(keyInfo);
562
- setStep("success");
563
- if (onSuccess) {
564
- setTimeout(() => {
565
- onSuccess();
566
- }, 1500);
567
- }
568
- } catch (err) {
569
- console.error("[RegistrationFlow] Registration error:", err);
570
- setError(err instanceof Error ? err.message : "Failed to create account");
571
- setStep("info");
572
- setIsLoading(false);
573
- }
574
- };
575
- return /* @__PURE__ */ jsx("div", { className: "auth-container", children: /* @__PURE__ */ jsxs("div", { className: "auth-card", children: [
576
- /* @__PURE__ */ jsx("h1", { children: "Create Account" }),
577
- /* @__PURE__ */ jsx("p", { className: "auth-description", children: "Create a new decentralized Identity. Your identity will be securely derived from a passkey." }),
578
- step === "info" && /* @__PURE__ */ jsxs(Fragment, { children: [
579
- /* @__PURE__ */ jsxs("div", { className: "auth-features", children: [
580
- /* @__PURE__ */ jsxs("div", { className: "feature-item", children: [
581
- /* @__PURE__ */ jsx("span", { className: "feature-icon", children: "\u{1F510}" }),
582
- /* @__PURE__ */ jsx("span", { children: "Phishing-resistant authentication" })
583
- ] }),
584
- /* @__PURE__ */ jsxs("div", { className: "feature-item", children: [
585
- /* @__PURE__ */ jsx("span", { className: "feature-icon", children: "\u{1F4F1}" }),
586
- /* @__PURE__ */ jsx("span", { children: "Biometric authentication support" })
587
- ] }),
588
- /* @__PURE__ */ jsxs("div", { className: "feature-item", children: [
589
- /* @__PURE__ */ jsx("span", { className: "feature-icon", children: "\u{1F310}" }),
590
- /* @__PURE__ */ jsx("span", { children: "Cross-device synchronization" })
591
- ] })
592
- ] }),
593
- /* @__PURE__ */ jsxs("div", { className: "username-section", children: [
594
- /* @__PURE__ */ jsx("label", { htmlFor: "username", className: "username-label", children: "Name (Optional)" }),
595
- /* @__PURE__ */ jsx(
596
- "input",
597
- {
598
- id: "username",
599
- type: "text",
600
- className: "username-input",
601
- placeholder: "Enter a name for this passkey",
602
- value: username,
603
- onChange: (e) => setUsername(e.target.value),
604
- disabled: isLoading
605
- }
606
- )
607
- ] }),
608
- error && /* @__PURE__ */ jsx("div", { className: "error-message", children: error }),
609
- /* @__PURE__ */ jsx(
610
- "button",
611
- {
612
- className: "auth-button primary",
613
- onClick: handleRegister,
614
- disabled: isLoading,
615
- children: isLoading ? "Creating..." : "Create Account"
616
- }
617
- )
618
- ] }),
619
- step === "creating" && /* @__PURE__ */ jsxs("div", { className: "loading-state", children: [
620
- /* @__PURE__ */ jsx("div", { className: "spinner" }),
621
- /* @__PURE__ */ jsx("p", { children: "Creating your passkey..." }),
622
- /* @__PURE__ */ jsx("p", { className: "loading-hint", children: "Please follow your browser's authentication prompt" }),
623
- /* @__PURE__ */ jsx("p", { className: "loading-hint-small", children: "\u{1F4A1} Using your system's native passkey manager (Touch ID, Face ID, Windows Hello, etc.)" })
624
- ] }),
625
- step === "success" && /* @__PURE__ */ jsxs("div", { className: "success-state", children: [
626
- /* @__PURE__ */ jsx("div", { className: "success-icon", children: "\u2713" }),
627
- /* @__PURE__ */ jsx("p", { children: "Account created successfully!" }),
628
- /* @__PURE__ */ jsx("p", { className: "success-hint", children: "Redirecting to profile setup..." })
629
- ] })
630
- ] }) });
544
+
545
+ //#endregion
546
+ //#region src/components/auth/RegistrationFlow.tsx
547
+ function RegistrationFlow({ authService, setAuthenticated, onSuccess }) {
548
+ const [isLoading, setIsLoading] = useState(false);
549
+ const [error, setError] = useState(null);
550
+ const [step, setStep] = useState("info");
551
+ const [username, setUsername] = useState("");
552
+ const maxUsernameLength = 100;
553
+ const handleRegister = async () => {
554
+ setIsLoading(true);
555
+ setError(null);
556
+ setStep("creating");
557
+ try {
558
+ authService.clearStoredKeyInfo();
559
+ let credentialId;
560
+ const passkeyUsername = username.trim() || void 0;
561
+ try {
562
+ credentialId = await authService.createPasskey(passkeyUsername);
563
+ } catch (passkeyError) {
564
+ console.error("[RegistrationFlow] Passkey creation failed:", passkeyError);
565
+ throw new Error("Unable to create passkey. Please try again.");
566
+ }
567
+ let keyInfo;
568
+ try {
569
+ keyInfo = await authService.createNostrKey(credentialId);
570
+ } catch (nostrKeyError) {
571
+ console.error("[RegistrationFlow] Failed to create Nostr key from passkey:", nostrKeyError);
572
+ throw new Error("Unable to finalize account. Please try again.");
573
+ }
574
+ authService.setCurrentKeyInfo(keyInfo);
575
+ setAuthenticated(keyInfo);
576
+ setStep("success");
577
+ if (onSuccess) setTimeout(() => {
578
+ onSuccess();
579
+ }, 1500);
580
+ } catch (err) {
581
+ console.error("[RegistrationFlow] Registration error:", err);
582
+ setError("Registration failed. Please try again.");
583
+ setStep("info");
584
+ setIsLoading(false);
585
+ }
586
+ };
587
+ return /* @__PURE__ */ jsx("div", {
588
+ className: "auth-container",
589
+ children: /* @__PURE__ */ jsxs("div", {
590
+ className: "auth-card",
591
+ children: [
592
+ /* @__PURE__ */ jsx("h1", { children: "Create Account" }),
593
+ /* @__PURE__ */ jsx("p", {
594
+ className: "auth-description",
595
+ children: "Create a new decentralized Identity. Your identity will be securely derived from a passkey."
596
+ }),
597
+ step === "info" && /* @__PURE__ */ jsxs(Fragment, { children: [
598
+ /* @__PURE__ */ jsxs("div", {
599
+ className: "auth-features",
600
+ children: [
601
+ /* @__PURE__ */ jsxs("div", {
602
+ className: "feature-item",
603
+ children: [/* @__PURE__ */ jsx("span", {
604
+ className: "feature-icon",
605
+ children: "🔐"
606
+ }), /* @__PURE__ */ jsx("span", { children: "Phishing-resistant authentication" })]
607
+ }),
608
+ /* @__PURE__ */ jsxs("div", {
609
+ className: "feature-item",
610
+ children: [/* @__PURE__ */ jsx("span", {
611
+ className: "feature-icon",
612
+ children: "📱"
613
+ }), /* @__PURE__ */ jsx("span", { children: "Biometric authentication support" })]
614
+ }),
615
+ /* @__PURE__ */ jsxs("div", {
616
+ className: "feature-item",
617
+ children: [/* @__PURE__ */ jsx("span", {
618
+ className: "feature-icon",
619
+ children: "🌐"
620
+ }), /* @__PURE__ */ jsx("span", { children: "Cross-device synchronization" })]
621
+ })
622
+ ]
623
+ }),
624
+ /* @__PURE__ */ jsxs("div", {
625
+ className: "username-section",
626
+ children: [/* @__PURE__ */ jsx("label", {
627
+ htmlFor: "username",
628
+ className: "username-label",
629
+ children: "Name (Optional)"
630
+ }), /* @__PURE__ */ jsx("input", {
631
+ id: "username",
632
+ type: "text",
633
+ className: "username-input",
634
+ placeholder: "Enter a name for this passkey",
635
+ value: username,
636
+ onChange: (e) => setUsername(e.target.value),
637
+ disabled: isLoading,
638
+ maxLength: maxUsernameLength
639
+ })]
640
+ }),
641
+ error && /* @__PURE__ */ jsx("div", {
642
+ className: "error-message",
643
+ children: error
644
+ }),
645
+ /* @__PURE__ */ jsx("button", {
646
+ className: "auth-button primary",
647
+ onClick: handleRegister,
648
+ disabled: isLoading,
649
+ children: isLoading ? "Creating..." : "Create Account"
650
+ })
651
+ ] }),
652
+ step === "creating" && /* @__PURE__ */ jsxs("div", {
653
+ className: "loading-state",
654
+ children: [
655
+ /* @__PURE__ */ jsx("div", { className: "spinner" }),
656
+ /* @__PURE__ */ jsx("p", { children: "Creating your passkey..." }),
657
+ /* @__PURE__ */ jsx("p", {
658
+ className: "loading-hint",
659
+ children: "Please follow your browser's authentication prompt"
660
+ }),
661
+ /* @__PURE__ */ jsx("p", {
662
+ className: "loading-hint-small",
663
+ children: "💡 Using your system's native passkey manager (Touch ID, Face ID, Windows Hello, etc.)"
664
+ })
665
+ ]
666
+ }),
667
+ step === "success" && /* @__PURE__ */ jsxs("div", {
668
+ className: "success-state",
669
+ children: [
670
+ /* @__PURE__ */ jsx("div", {
671
+ className: "success-icon",
672
+ children: "✓"
673
+ }),
674
+ /* @__PURE__ */ jsx("p", { children: "Account created successfully!" }),
675
+ /* @__PURE__ */ jsx("p", {
676
+ className: "success-hint",
677
+ children: "Redirecting to profile setup..."
678
+ })
679
+ ]
680
+ })
681
+ ]
682
+ })
683
+ });
631
684
  }
632
- var BarcodeScanner = ({ onDecode, active = true }) => {
633
- const [error, setError] = useState(null);
634
- const { ref } = useZxing({
635
- onDecodeResult: (result) => {
636
- onDecode(result.getText());
637
- },
638
- onError: (e) => {
639
- const errorMessage = e instanceof Error ? e.message : "Camera error";
640
- setError(errorMessage);
641
- }
642
- });
643
- if (!active) return null;
644
- return /* @__PURE__ */ jsxs("div", { style: { position: "relative", width: "100%", maxWidth: "400px" }, children: [
645
- /* @__PURE__ */ jsx(
646
- "video",
647
- {
648
- ref,
649
- style: { width: "100%", borderRadius: "8px" },
650
- playsInline: true,
651
- muted: true
652
- }
653
- ),
654
- error && /* @__PURE__ */ jsx("p", { style: { color: "red", marginTop: "0.5rem" }, children: error })
655
- ] });
685
+
686
+ //#endregion
687
+ //#region src/utils/sanitize.ts
688
+ const sanitizeOptions = {
689
+ ALLOWED_TAGS: [],
690
+ ALLOWED_ATTR: []
656
691
  };
657
- var TrustInfo = () => /* @__PURE__ */ jsxs("section", { className: "trust-info", children: [
658
- /* @__PURE__ */ jsx("h2", { children: "Building Trust with Verifiable Relationship Credentials" }),
659
- /* @__PURE__ */ jsxs("p", { children: [
660
- "Beyond the Personhood Credential, members can create ",
661
- /* @__PURE__ */ jsx("strong", { children: "Verifiable Relationship Credentials (VRCs)" }),
662
- ". A VRC is issued directly between two members \u2013 for example, by scanning a QR\u2011code at a meetup \u2013 and certifies a first\u2011hand trust link."
663
- ] }),
664
- /* @__PURE__ */ jsxs("p", { children: [
665
- "Each VRC becomes a node in a decentralized trust graph. When you add a member, the system records a ",
666
- /* @__PURE__ */ jsx("strong", { children: "role" }),
667
- " tag that ties the new participant to your existing graph, enabling permissionless access to network\u2011state resources while keeping the underlying data private."
668
- ] }),
669
- /* @__PURE__ */ jsx("p", { children: "The graph grows organically: trusted authorities issue PHCs, and members continuously enrich the network with peer\u2011generated VRCs, creating a resilient, scalable web of verified participants." })
670
- ] });
671
- function MembershipPage({
672
- authService,
673
- relayService,
674
- publicKey,
675
- onUnauthenticated
676
- }) {
677
- const [isLoading, setIsLoading] = useState(false);
678
- const [isSaving, setIsSaving] = useState(false);
679
- const [saveMessage, setSaveMessage] = useState(null);
680
- const [searchQuery, setSearchQuery] = useState("");
681
- const [profiles, setProfiles] = useState([]);
682
- const [members, setMembers] = useState([]);
683
- const [memberProfiles, setMemberProfiles] = useState(/* @__PURE__ */ new Map());
684
- const [showScanner, setShowScanner] = useState(false);
685
- useEffect(() => {
686
- if (!publicKey) {
687
- if (onUnauthenticated) {
688
- onUnauthenticated();
689
- }
690
- return;
691
- }
692
- loadFollowList();
693
- }, [publicKey]);
694
- useEffect(() => {
695
- if (members.length > 0) {
696
- loadMemberProfiles();
697
- }
698
- }, [members]);
699
- const handleDecoded = (decoded) => {
700
- setSearchQuery(decoded);
701
- setShowScanner(false);
702
- handleSearch();
703
- };
704
- const loadFollowList = async () => {
705
- if (!publicKey) return;
706
- setIsLoading(true);
707
- try {
708
- const followList = await relayService.fetchFollowList(publicKey);
709
- setMembers(followList);
710
- } catch (error) {
711
- console.error("Failed to load follow list:", error);
712
- setSaveMessage("Failed to load membership list");
713
- } finally {
714
- setIsLoading(false);
715
- }
716
- };
717
- const loadMemberProfiles = async () => {
718
- if (members.length === 0) return;
719
- try {
720
- const pubkeys = members.map((m) => m.pubkey);
721
- const profilesMap = await relayService.fetchMultipleProfiles(pubkeys);
722
- setMemberProfiles(profilesMap);
723
- } catch (error) {
724
- console.error("Failed to load member profiles:", error);
725
- }
726
- };
727
- const handleSearch = async () => {
728
- if (!searchQuery.trim()) {
729
- setIsLoading(true);
730
- try {
731
- const profilesMap = await relayService.queryProfiles([], 50);
732
- const profilesList = [];
733
- profilesMap.forEach((profile, pubkey) => {
734
- profilesList.push({ ...profile, pubkey });
735
- });
736
- setProfiles(profilesList);
737
- } catch (error) {
738
- console.error("Failed to query profiles:", error);
739
- setSaveMessage("Failed to search profiles");
740
- } finally {
741
- setIsLoading(false);
742
- }
743
- return;
744
- }
745
- const trimmedQuery = searchQuery.trim();
746
- if (trimmedQuery.length !== 64 || !/^[0-9a-fA-F]+$/.test(trimmedQuery)) {
747
- setSaveMessage("Invalid pubkey format. Must be 64 hex characters.");
748
- setTimeout(() => setSaveMessage(null), 3e3);
749
- return;
750
- }
751
- setIsLoading(true);
752
- try {
753
- const profilesMap = await relayService.queryProfiles([trimmedQuery], 1);
754
- const profilesList = [];
755
- profilesMap.forEach((profile, pubkey) => {
756
- profilesList.push({ ...profile, pubkey });
757
- });
758
- setProfiles(profilesList);
759
- if (profilesList.length === 0) {
760
- setSaveMessage("No profile found for this pubkey");
761
- setTimeout(() => setSaveMessage(null), 3e3);
762
- }
763
- } catch (error) {
764
- console.error("Failed to query profile:", error);
765
- setSaveMessage("Failed to search profile");
766
- } finally {
767
- setIsLoading(false);
768
- }
769
- };
770
- const handleAddMember = async (pubkey) => {
771
- if (!publicKey) return;
772
- if (members.some((m) => m.pubkey === pubkey)) {
773
- setSaveMessage("User is already a member");
774
- setTimeout(() => setSaveMessage(null), 3e3);
775
- return;
776
- }
777
- setIsSaving(true);
778
- try {
779
- const newMembers = [
780
- ...members,
781
- {
782
- pubkey
783
- }
784
- ];
785
- await relayService.publishFollowList(
786
- publicKey,
787
- newMembers,
788
- (event) => authService.signEvent(event)
789
- );
790
- setMembers(newMembers);
791
- setSaveMessage("Member added successfully!");
792
- setTimeout(() => setSaveMessage(null), 3e3);
793
- } catch (error) {
794
- console.error("Failed to add member:", error);
795
- setSaveMessage(
796
- error instanceof Error ? `Error: ${error.message}` : "Failed to add member"
797
- );
798
- } finally {
799
- setIsSaving(false);
800
- }
801
- };
802
- const handleRemoveMember = async (pubkey) => {
803
- if (!publicKey) return;
804
- setIsSaving(true);
805
- try {
806
- const newMembers = members.filter((m) => m.pubkey !== pubkey);
807
- await relayService.publishFollowList(
808
- publicKey,
809
- newMembers,
810
- (event) => authService.signEvent(event)
811
- );
812
- setMembers(newMembers);
813
- setSaveMessage("Member removed successfully!");
814
- setTimeout(() => setSaveMessage(null), 3e3);
815
- } catch (error) {
816
- console.error("Failed to remove member:", error);
817
- setSaveMessage(
818
- error instanceof Error ? `Error: ${error.message}` : "Failed to remove member"
819
- );
820
- } finally {
821
- setIsSaving(false);
822
- }
823
- };
824
- const getProfileDisplayName = (profile, pubkey) => {
825
- return profile.display_name || profile.name || pubkey.slice(0, 16) + "...";
826
- };
827
- const formatPubkey = (pubkey) => {
828
- return `${pubkey.slice(0, 8)}...${pubkey.slice(-8)}`;
829
- };
830
- if (isLoading && members.length === 0) {
831
- return /* @__PURE__ */ jsx("div", { className: "membership-container", children: /* @__PURE__ */ jsxs("div", { className: "loading-state", children: [
832
- /* @__PURE__ */ jsx("div", { className: "spinner" }),
833
- /* @__PURE__ */ jsx("p", { children: "Loading membership list..." })
834
- ] }) });
835
- }
836
- return /* @__PURE__ */ jsx("div", { className: "membership-container", children: /* @__PURE__ */ jsxs("div", { className: "membership-card", children: [
837
- /* @__PURE__ */ jsx("h1", { children: "Membership Management" }),
838
- /* @__PURE__ */ jsx(TrustInfo, {}),
839
- /* @__PURE__ */ jsx("p", { className: "membership-description", children: "Query applicants and manage the membership list." }),
840
- saveMessage && /* @__PURE__ */ jsx(
841
- "div",
842
- {
843
- className: `save-message ${saveMessage.includes("Error") || saveMessage.includes("Failed") ? "error" : "success"}`,
844
- children: saveMessage
845
- }
846
- ),
847
- /* @__PURE__ */ jsxs("div", { className: "search-section", children: [
848
- /* @__PURE__ */ jsx("h2", { children: "Add Member" }),
849
- /* @__PURE__ */ jsxs("div", { className: "search-form", children: [
850
- /* @__PURE__ */ jsx(
851
- "input",
852
- {
853
- type: "text",
854
- value: searchQuery,
855
- onChange: (e) => setSearchQuery(e.target.value),
856
- onKeyPress: (e) => e.key === "Enter" && handleSearch(),
857
- placeholder: "Enter pubkey or leave empty for recent profiles",
858
- className: "search-input",
859
- disabled: isLoading
860
- }
861
- ),
862
- /* @__PURE__ */ jsx(
863
- "button",
864
- {
865
- onClick: handleSearch,
866
- className: "search-button",
867
- disabled: isLoading || isSaving,
868
- children: isLoading ? "Searching..." : "Search"
869
- }
870
- ),
871
- /* @__PURE__ */ jsx(
872
- "button",
873
- {
874
- onClick: () => setShowScanner((prev) => !prev),
875
- className: "scanner-toggle",
876
- disabled: isLoading || isSaving,
877
- children: showScanner ? "Close Scanner" : "Scan QR"
878
- }
879
- )
880
- ] }),
881
- showScanner && /* @__PURE__ */ jsxs("div", { style: { marginTop: "1rem" }, children: [
882
- /* @__PURE__ */ jsx(BarcodeScanner, { onDecode: handleDecoded, active: true }),
883
- /* @__PURE__ */ jsx("p", { style: { fontSize: "0.85rem", marginTop: "0.5rem" }, children: "Point at QR\u2011code containing a pubkey" })
884
- ] }),
885
- profiles.length > 0 && /* @__PURE__ */ jsxs("div", { className: "profiles-list", children: [
886
- /* @__PURE__ */ jsx("h3", { children: "Search Results" }),
887
- profiles.map((profile) => {
888
- const isMember = members.some((m) => m.pubkey === profile.pubkey);
889
- return /* @__PURE__ */ jsxs("div", { className: "profile-item", children: [
890
- /* @__PURE__ */ jsxs("div", { className: "profile-info", children: [
891
- profile.picture && /* @__PURE__ */ jsx(
892
- "img",
893
- {
894
- src: profile.picture,
895
- alt: getProfileDisplayName(profile, profile.pubkey),
896
- className: "profile-avatar"
897
- }
898
- ),
899
- /* @__PURE__ */ jsxs("div", { className: "profile-details", children: [
900
- /* @__PURE__ */ jsx("div", { className: "profile-name", children: getProfileDisplayName(profile, profile.pubkey) }),
901
- /* @__PURE__ */ jsx("div", { className: "profile-pubkey", children: formatPubkey(profile.pubkey) }),
902
- profile.about && /* @__PURE__ */ jsx("div", { className: "profile-about", children: profile.about })
903
- ] })
904
- ] }),
905
- /* @__PURE__ */ jsx(
906
- "button",
907
- {
908
- onClick: () => isMember ? handleRemoveMember(profile.pubkey) : handleAddMember(profile.pubkey),
909
- className: `member-button ${isMember ? "remove" : "add"}`,
910
- disabled: isSaving,
911
- children: isMember ? "Remove" : "Add Member"
912
- }
913
- )
914
- ] }, profile.pubkey);
915
- })
916
- ] })
917
- ] }),
918
- /* @__PURE__ */ jsxs("div", { className: "members-section", children: [
919
- /* @__PURE__ */ jsxs("h2", { children: [
920
- "Current Members (",
921
- members.length,
922
- ")"
923
- ] }),
924
- members.length === 0 ? /* @__PURE__ */ jsx("p", { className: "empty-message", children: "No members yet. Add members from search results above." }) : /* @__PURE__ */ jsx("div", { className: "members-list", children: members.map((member) => {
925
- const profile = memberProfiles.get(member.pubkey);
926
- return /* @__PURE__ */ jsxs("div", { className: "member-item", children: [
927
- /* @__PURE__ */ jsxs("div", { className: "profile-info", children: [
928
- profile?.picture && /* @__PURE__ */ jsx(
929
- "img",
930
- {
931
- src: profile.picture,
932
- alt: getProfileDisplayName(profile || {}, member.pubkey),
933
- className: "profile-avatar"
934
- }
935
- ),
936
- /* @__PURE__ */ jsxs("div", { className: "profile-details", children: [
937
- /* @__PURE__ */ jsx("div", { className: "profile-name", children: profile ? getProfileDisplayName(profile, member.pubkey) : formatPubkey(member.pubkey) }),
938
- /* @__PURE__ */ jsx("div", { className: "profile-pubkey", children: formatPubkey(member.pubkey) }),
939
- profile?.about && /* @__PURE__ */ jsx("div", { className: "profile-about", children: profile.about }),
940
- member.petname && /* @__PURE__ */ jsxs("div", { className: "profile-petname", children: [
941
- "Name: ",
942
- member.petname
943
- ] })
944
- ] })
945
- ] }),
946
- /* @__PURE__ */ jsx(
947
- "button",
948
- {
949
- onClick: () => handleRemoveMember(member.pubkey),
950
- className: "member-button remove",
951
- disabled: isSaving,
952
- children: "Remove"
953
- }
954
- )
955
- ] }, member.pubkey);
956
- }) })
957
- ] })
958
- ] }) });
692
+ const sanitizeText = (value) => DOMPurify.sanitize(value, sanitizeOptions);
693
+
694
+ //#endregion
695
+ //#region src/components/membership/BarcodeScanner.tsx
696
+ const BarcodeScanner = ({ onDecode, active = true }) => {
697
+ const [error, setError] = useState(null);
698
+ const { ref } = useZxing({
699
+ onDecodeResult: (result) => {
700
+ onDecode(result.getText());
701
+ },
702
+ onError: (e) => {
703
+ setError(e instanceof Error ? e.message : "Camera error");
704
+ }
705
+ });
706
+ if (!active) return null;
707
+ return /* @__PURE__ */ jsxs("div", {
708
+ style: {
709
+ position: "relative",
710
+ width: "100%",
711
+ maxWidth: "400px"
712
+ },
713
+ children: [/* @__PURE__ */ jsx("video", {
714
+ ref,
715
+ style: {
716
+ width: "100%",
717
+ borderRadius: "8px"
718
+ },
719
+ playsInline: true,
720
+ muted: true
721
+ }), error && /* @__PURE__ */ jsx("p", {
722
+ style: {
723
+ color: "red",
724
+ marginTop: "0.5rem"
725
+ },
726
+ children: error
727
+ })]
728
+ });
729
+ };
730
+
731
+ //#endregion
732
+ //#region src/components/membership/MembershipPage.tsx
733
+ const TrustInfo = () => /* @__PURE__ */ jsxs("section", {
734
+ className: "trust-info",
735
+ children: [
736
+ /* @__PURE__ */ jsx("h2", { children: "Building Trust with Verifiable Relationship Credentials" }),
737
+ /* @__PURE__ */ jsxs("p", { children: [
738
+ "Beyond the Personhood Credential, members can create ",
739
+ /* @__PURE__ */ jsx("strong", { children: "Verifiable Relationship Credentials (VRCs)" }),
740
+ ". A VRC is issued directly between two members – for example, by scanning a QR‑code at a meetup – and certifies a first‑hand trust link."
741
+ ] }),
742
+ /* @__PURE__ */ jsxs("p", { children: [
743
+ "Each VRC becomes a node in a decentralized trust graph. When you add a member, the system records a ",
744
+ /* @__PURE__ */ jsx("strong", { children: "role" }),
745
+ " tag that ties the new participant to your existing graph, enabling permissionless access to network‑state resources while keeping the underlying data private."
746
+ ] }),
747
+ /* @__PURE__ */ jsx("p", { children: "The graph grows organically: trusted authorities issue PHCs, and members continuously enrich the network with peer‑generated VRCs, creating a resilient, scalable web of verified participants." })
748
+ ]
749
+ });
750
+ function MembershipPage({ authService, relayService, publicKey, onUnauthenticated }) {
751
+ const [isLoading, setIsLoading] = useState(false);
752
+ const [isSaving, setIsSaving] = useState(false);
753
+ const [saveMessage, setSaveMessage] = useState(null);
754
+ const [searchQuery, setSearchQuery] = useState("");
755
+ const [profiles, setProfiles] = useState([]);
756
+ const [members, setMembers] = useState([]);
757
+ const [memberProfiles, setMemberProfiles] = useState(/* @__PURE__ */ new Map());
758
+ const [showScanner, setShowScanner] = useState(false);
759
+ useEffect(() => {
760
+ if (!publicKey) {
761
+ if (onUnauthenticated) onUnauthenticated();
762
+ return;
763
+ }
764
+ loadFollowList();
765
+ }, [publicKey]);
766
+ useEffect(() => {
767
+ if (members.length > 0) loadMemberProfiles();
768
+ }, [members]);
769
+ const handleDecoded = (decoded) => {
770
+ setSearchQuery(decoded);
771
+ setShowScanner(false);
772
+ handleSearch();
773
+ };
774
+ const loadFollowList = async () => {
775
+ if (!publicKey) return;
776
+ setIsLoading(true);
777
+ try {
778
+ setMembers(await relayService.fetchFollowList(publicKey));
779
+ } catch (error) {
780
+ console.error("Failed to load follow list:", error);
781
+ setSaveMessage("Failed to load membership list");
782
+ } finally {
783
+ setIsLoading(false);
784
+ }
785
+ };
786
+ const loadMemberProfiles = async () => {
787
+ if (members.length === 0) return;
788
+ try {
789
+ const pubkeys = members.map((m) => m.pubkey);
790
+ setMemberProfiles(await relayService.fetchMultipleProfiles(pubkeys));
791
+ } catch (error) {
792
+ console.error("Failed to load member profiles:", error);
793
+ }
794
+ };
795
+ const handleSearch = async () => {
796
+ if (!searchQuery.trim()) {
797
+ setIsLoading(true);
798
+ try {
799
+ const profilesMap = await relayService.queryProfiles([], 50);
800
+ const profilesList = [];
801
+ profilesMap.forEach((profile, pubkey) => {
802
+ profilesList.push({
803
+ ...profile,
804
+ pubkey
805
+ });
806
+ });
807
+ setProfiles(profilesList);
808
+ } catch (error) {
809
+ console.error("Failed to query profiles:", error);
810
+ setSaveMessage("Failed to search profiles");
811
+ } finally {
812
+ setIsLoading(false);
813
+ }
814
+ return;
815
+ }
816
+ const trimmedQuery = searchQuery.trim();
817
+ if (trimmedQuery.length !== 64 || !/^[0-9a-fA-F]+$/.test(trimmedQuery)) {
818
+ setSaveMessage("Invalid pubkey format. Must be 64 hex characters.");
819
+ setTimeout(() => setSaveMessage(null), 3e3);
820
+ return;
821
+ }
822
+ setIsLoading(true);
823
+ try {
824
+ const profilesMap = await relayService.queryProfiles([trimmedQuery], 1);
825
+ const profilesList = [];
826
+ profilesMap.forEach((profile, pubkey) => {
827
+ profilesList.push({
828
+ ...profile,
829
+ pubkey
830
+ });
831
+ });
832
+ setProfiles(profilesList);
833
+ if (profilesList.length === 0) {
834
+ setSaveMessage("No profile found for this pubkey");
835
+ setTimeout(() => setSaveMessage(null), 3e3);
836
+ }
837
+ } catch (error) {
838
+ console.error("Failed to query profile:", error);
839
+ setSaveMessage("Failed to search profile");
840
+ } finally {
841
+ setIsLoading(false);
842
+ }
843
+ };
844
+ const handleAddMember = async (pubkey) => {
845
+ if (!publicKey) return;
846
+ if (members.some((m) => m.pubkey === pubkey)) {
847
+ setSaveMessage("User is already a member");
848
+ setTimeout(() => setSaveMessage(null), 3e3);
849
+ return;
850
+ }
851
+ setIsSaving(true);
852
+ try {
853
+ const newMembers = [...members, { pubkey }];
854
+ await relayService.publishFollowList(publicKey, newMembers, (event) => authService.signEvent(event));
855
+ setMembers(newMembers);
856
+ setSaveMessage("Member added successfully!");
857
+ setTimeout(() => setSaveMessage(null), 3e3);
858
+ } catch (error) {
859
+ console.error("Failed to add member:", error);
860
+ setSaveMessage("Failed to add member. Please try again.");
861
+ } finally {
862
+ setIsSaving(false);
863
+ }
864
+ };
865
+ const handleRemoveMember = async (pubkey) => {
866
+ if (!publicKey) return;
867
+ setIsSaving(true);
868
+ try {
869
+ const newMembers = members.filter((m) => m.pubkey !== pubkey);
870
+ await relayService.publishFollowList(publicKey, newMembers, (event) => authService.signEvent(event));
871
+ setMembers(newMembers);
872
+ setSaveMessage("Member removed successfully!");
873
+ setTimeout(() => setSaveMessage(null), 3e3);
874
+ } catch (error) {
875
+ console.error("Failed to remove member:", error);
876
+ setSaveMessage("Failed to remove member. Please try again.");
877
+ } finally {
878
+ setIsSaving(false);
879
+ }
880
+ };
881
+ const getProfileDisplayName = (profile, pubkey) => {
882
+ return profile.display_name || profile.name || pubkey.slice(0, 16) + "...";
883
+ };
884
+ const formatPubkey = (pubkey) => {
885
+ return `${pubkey.slice(0, 8)}...${pubkey.slice(-8)}`;
886
+ };
887
+ if (isLoading && members.length === 0) return /* @__PURE__ */ jsx("div", {
888
+ className: "membership-container",
889
+ children: /* @__PURE__ */ jsxs("div", {
890
+ className: "loading-state",
891
+ children: [/* @__PURE__ */ jsx("div", { className: "spinner" }), /* @__PURE__ */ jsx("p", { children: "Loading membership list..." })]
892
+ })
893
+ });
894
+ return /* @__PURE__ */ jsx("div", {
895
+ className: "membership-container",
896
+ children: /* @__PURE__ */ jsxs("div", {
897
+ className: "membership-card",
898
+ children: [
899
+ /* @__PURE__ */ jsx("h1", { children: "Membership Management" }),
900
+ /* @__PURE__ */ jsx(TrustInfo, {}),
901
+ /* @__PURE__ */ jsx("p", {
902
+ className: "membership-description",
903
+ children: "Query applicants and manage the membership list."
904
+ }),
905
+ saveMessage && /* @__PURE__ */ jsx("div", {
906
+ className: `save-message ${saveMessage.includes("Error") || saveMessage.includes("Failed") ? "error" : "success"}`,
907
+ children: saveMessage
908
+ }),
909
+ /* @__PURE__ */ jsxs("div", {
910
+ className: "search-section",
911
+ children: [
912
+ /* @__PURE__ */ jsx("h2", { children: "Add Member" }),
913
+ /* @__PURE__ */ jsxs("div", {
914
+ className: "search-form",
915
+ children: [
916
+ /* @__PURE__ */ jsx("input", {
917
+ type: "text",
918
+ value: searchQuery,
919
+ onChange: (e) => setSearchQuery(e.target.value),
920
+ onKeyPress: (e) => e.key === "Enter" && handleSearch(),
921
+ placeholder: "Enter pubkey or leave empty for recent profiles",
922
+ className: "search-input",
923
+ disabled: isLoading
924
+ }),
925
+ /* @__PURE__ */ jsx("button", {
926
+ onClick: handleSearch,
927
+ className: "search-button",
928
+ disabled: isLoading || isSaving,
929
+ children: isLoading ? "Searching..." : "Search"
930
+ }),
931
+ /* @__PURE__ */ jsx("button", {
932
+ onClick: () => setShowScanner((prev) => !prev),
933
+ className: "scanner-toggle",
934
+ disabled: isLoading || isSaving,
935
+ children: showScanner ? "Close Scanner" : "Scan QR"
936
+ })
937
+ ]
938
+ }),
939
+ showScanner && /* @__PURE__ */ jsxs("div", {
940
+ style: { marginTop: "1rem" },
941
+ children: [/* @__PURE__ */ jsx(BarcodeScanner, {
942
+ onDecode: handleDecoded,
943
+ active: true
944
+ }), /* @__PURE__ */ jsx("p", {
945
+ style: {
946
+ fontSize: "0.85rem",
947
+ marginTop: "0.5rem"
948
+ },
949
+ children: "Point at QR‑code containing a pubkey"
950
+ })]
951
+ }),
952
+ profiles.length > 0 && /* @__PURE__ */ jsxs("div", {
953
+ className: "profiles-list",
954
+ children: [/* @__PURE__ */ jsx("h3", { children: "Search Results" }), profiles.map((profile) => {
955
+ const isMember = members.some((m) => m.pubkey === profile.pubkey);
956
+ return /* @__PURE__ */ jsxs("div", {
957
+ className: "profile-item",
958
+ children: [/* @__PURE__ */ jsxs("div", {
959
+ className: "profile-info",
960
+ children: [profile.picture && isValidHttpUrl(profile.picture) && /* @__PURE__ */ jsx("img", {
961
+ src: profile.picture,
962
+ alt: sanitizeText(getProfileDisplayName(profile, profile.pubkey)),
963
+ className: "profile-avatar",
964
+ loading: "lazy",
965
+ referrerPolicy: "no-referrer",
966
+ onError: (event) => {
967
+ event.currentTarget.style.display = "none";
968
+ }
969
+ }), /* @__PURE__ */ jsxs("div", {
970
+ className: "profile-details",
971
+ children: [
972
+ /* @__PURE__ */ jsx("div", {
973
+ className: "profile-name",
974
+ children: sanitizeText(getProfileDisplayName(profile, profile.pubkey))
975
+ }),
976
+ /* @__PURE__ */ jsx("div", {
977
+ className: "profile-pubkey",
978
+ children: formatPubkey(profile.pubkey)
979
+ }),
980
+ profile.about && /* @__PURE__ */ jsx("div", {
981
+ className: "profile-about",
982
+ children: sanitizeText(profile.about)
983
+ })
984
+ ]
985
+ })]
986
+ }), /* @__PURE__ */ jsx("button", {
987
+ onClick: () => isMember ? handleRemoveMember(profile.pubkey) : handleAddMember(profile.pubkey),
988
+ className: `member-button ${isMember ? "remove" : "add"}`,
989
+ disabled: isSaving,
990
+ children: isMember ? "Remove" : "Add Member"
991
+ })]
992
+ }, profile.pubkey);
993
+ })]
994
+ })
995
+ ]
996
+ }),
997
+ /* @__PURE__ */ jsxs("div", {
998
+ className: "members-section",
999
+ children: [/* @__PURE__ */ jsxs("h2", { children: [
1000
+ "Current Members (",
1001
+ members.length,
1002
+ ")"
1003
+ ] }), members.length === 0 ? /* @__PURE__ */ jsx("p", {
1004
+ className: "empty-message",
1005
+ children: "No members yet. Add members from search results above."
1006
+ }) : /* @__PURE__ */ jsx("div", {
1007
+ className: "members-list",
1008
+ children: members.map((member) => {
1009
+ const profile = memberProfiles.get(member.pubkey);
1010
+ return /* @__PURE__ */ jsxs("div", {
1011
+ className: "member-item",
1012
+ children: [/* @__PURE__ */ jsxs("div", {
1013
+ className: "profile-info",
1014
+ children: [profile?.picture && isValidHttpUrl(profile.picture) && /* @__PURE__ */ jsx("img", {
1015
+ src: profile.picture,
1016
+ alt: sanitizeText(getProfileDisplayName(profile || {}, member.pubkey)),
1017
+ className: "profile-avatar",
1018
+ loading: "lazy",
1019
+ referrerPolicy: "no-referrer",
1020
+ onError: (event) => {
1021
+ event.currentTarget.style.display = "none";
1022
+ }
1023
+ }), /* @__PURE__ */ jsxs("div", {
1024
+ className: "profile-details",
1025
+ children: [
1026
+ /* @__PURE__ */ jsx("div", {
1027
+ className: "profile-name",
1028
+ children: profile ? sanitizeText(getProfileDisplayName(profile, member.pubkey)) : formatPubkey(member.pubkey)
1029
+ }),
1030
+ /* @__PURE__ */ jsx("div", {
1031
+ className: "profile-pubkey",
1032
+ children: formatPubkey(member.pubkey)
1033
+ }),
1034
+ profile?.about && /* @__PURE__ */ jsx("div", {
1035
+ className: "profile-about",
1036
+ children: sanitizeText(profile.about)
1037
+ }),
1038
+ member.petname && /* @__PURE__ */ jsxs("div", {
1039
+ className: "profile-petname",
1040
+ children: ["Name: ", sanitizeText(member.petname)]
1041
+ })
1042
+ ]
1043
+ })]
1044
+ }), /* @__PURE__ */ jsx("button", {
1045
+ onClick: () => handleRemoveMember(member.pubkey),
1046
+ className: "member-button remove",
1047
+ disabled: isSaving,
1048
+ children: "Remove"
1049
+ })]
1050
+ }, member.pubkey);
1051
+ })
1052
+ })]
1053
+ })
1054
+ ]
1055
+ })
1056
+ });
959
1057
  }
960
- var PersonhoodInfo = () => /* @__PURE__ */ jsxs("section", { className: "personhood-info", children: [
961
- /* @__PURE__ */ jsxs("p", { children: [
962
- "Network\u2011state members receive a ",
963
- /* @__PURE__ */ jsx("strong", { children: "Personhood Credential (PHC)" }),
964
- " from a trusted authority. The PHC attests that the holder is a unique, real individual. Because the credential lives in your passport, you can present a ",
965
- /* @__PURE__ */ jsx("em", { children: "zero\u2011knowledge proof" }),
966
- " that you are verified."
967
- ] }),
968
- /* @__PURE__ */ jsx("p", { children: "In this form we compare the name you enter with the name disclosed by your verified passport proof. If the two match, the profile will be saved as your business card credential together with a passport tag that references the PHC's unique identifier." })
969
- ] });
970
- function ProfilePage({
971
- authService,
972
- relayService,
973
- publicKey,
974
- onUnauthenticated,
975
- onSuccess,
976
- onRoleSuggestion
977
- }) {
978
- const [isLoading, setIsLoading] = useState(false);
979
- const [isSaving, setIsSaving] = useState(false);
980
- const [saveMessage, setSaveMessage] = useState(null);
981
- const [suggestedRole, setSuggestedRole] = useState(null);
982
- const [isGettingRole, setIsGettingRole] = useState(false);
983
- const [formData, setFormData] = useState({
984
- name: "",
985
- display_name: "",
986
- about: "",
987
- picture: "",
988
- website: ""
989
- });
990
- useEffect(() => {
991
- if (!publicKey) {
992
- if (onUnauthenticated) {
993
- onUnauthenticated();
994
- }
995
- return;
996
- }
997
- loadProfile();
998
- }, [publicKey]);
999
- const loadProfile = async () => {
1000
- if (!publicKey) return;
1001
- setIsLoading(true);
1002
- try {
1003
- const [profile, roleTag] = await Promise.all([
1004
- relayService.fetchProfile(publicKey),
1005
- relayService.fetchProfileRoleTag(publicKey)
1006
- ]);
1007
- if (profile) {
1008
- setFormData({
1009
- name: profile.name || "",
1010
- display_name: profile.display_name || "",
1011
- about: profile.about || "",
1012
- picture: profile.picture || "",
1013
- website: profile.website || ""
1014
- });
1015
- }
1016
- if (roleTag) {
1017
- setSuggestedRole(roleTag);
1018
- }
1019
- } catch (error) {
1020
- console.error("Failed to load profile:", error);
1021
- } finally {
1022
- setIsLoading(false);
1023
- }
1024
- };
1025
- const handleSubmit = async (e) => {
1026
- e.preventDefault();
1027
- if (!publicKey) return;
1028
- setIsSaving(true);
1029
- setSaveMessage(null);
1030
- try {
1031
- const tags = [];
1032
- if (formData.about && formData.about.trim().length > 0 && onRoleSuggestion) {
1033
- setIsGettingRole(true);
1034
- try {
1035
- const roleSuggestion = await onRoleSuggestion(formData.about);
1036
- if (roleSuggestion) {
1037
- tags.push(["role", roleSuggestion]);
1038
- setSuggestedRole(roleSuggestion);
1039
- } else {
1040
- setSuggestedRole(null);
1041
- }
1042
- } catch (error) {
1043
- console.error("Failed to get role suggestion:", error);
1044
- setSuggestedRole(null);
1045
- } finally {
1046
- setIsGettingRole(false);
1047
- }
1048
- } else {
1049
- setSuggestedRole(null);
1050
- }
1051
- const profile = {
1052
- kind: 0,
1053
- content: JSON.stringify(formData),
1054
- created_at: Math.floor(Date.now() / 1e3),
1055
- tags
1056
- };
1057
- const follows = {
1058
- kind: 3,
1059
- content: "",
1060
- created_at: Math.floor(Date.now() / 1e3),
1061
- tags: [["p", publicKey, "wss://relay.damus.io", formData.name || ""]]
1062
- };
1063
- const signedProfile = await authService.signEvent(profile);
1064
- const signedFollows = await authService.signEvent(follows);
1065
- await relayService.publishEvent(signedProfile);
1066
- await relayService.publishEvent(signedFollows);
1067
- setSaveMessage("Profile saved successfully!");
1068
- setTimeout(() => {
1069
- setSaveMessage(null);
1070
- }, 3e3);
1071
- if (onSuccess) {
1072
- onSuccess();
1073
- }
1074
- } catch (error) {
1075
- console.error("Failed to save profile:", error);
1076
- setSaveMessage(
1077
- error instanceof Error ? `Error: ${error.message}` : "Failed to save profile"
1078
- );
1079
- } finally {
1080
- setIsSaving(false);
1081
- }
1082
- };
1083
- const handleChange = (e) => {
1084
- const { name, value } = e.target;
1085
- setFormData((prev) => ({
1086
- ...prev,
1087
- [name]: value
1088
- }));
1089
- };
1090
- if (isLoading) {
1091
- return /* @__PURE__ */ jsx("div", { className: "profile-container", children: /* @__PURE__ */ jsxs("div", { className: "loading-state", children: [
1092
- /* @__PURE__ */ jsx("div", { className: "spinner" }),
1093
- /* @__PURE__ */ jsx("p", { children: "Loading profile..." })
1094
- ] }) });
1095
- }
1096
- return /* @__PURE__ */ jsx("div", { className: "profile-container", children: /* @__PURE__ */ jsxs("div", { className: "profile-card", children: [
1097
- /* @__PURE__ */ jsx("h1", { children: "Profile Setup" }),
1098
- /* @__PURE__ */ jsx(PersonhoodInfo, {}),
1099
- /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "profile-form", children: [
1100
- /* @__PURE__ */ jsxs("div", { className: "form-group", children: [
1101
- /* @__PURE__ */ jsx("label", { htmlFor: "name", children: "First Name" }),
1102
- /* @__PURE__ */ jsx(
1103
- "input",
1104
- {
1105
- type: "text",
1106
- id: "name",
1107
- name: "name",
1108
- value: formData.name || "",
1109
- onChange: handleChange,
1110
- placeholder: "Your username"
1111
- }
1112
- )
1113
- ] }),
1114
- /* @__PURE__ */ jsxs("div", { className: "form-group", children: [
1115
- /* @__PURE__ */ jsx("label", { htmlFor: "display_name", children: "Last Name" }),
1116
- /* @__PURE__ */ jsx(
1117
- "input",
1118
- {
1119
- type: "text",
1120
- id: "display_name",
1121
- name: "display_name",
1122
- value: formData.display_name || "",
1123
- onChange: handleChange,
1124
- placeholder: "Your Last Name"
1125
- }
1126
- )
1127
- ] }),
1128
- /* @__PURE__ */ jsxs("div", { className: "form-group", children: [
1129
- /* @__PURE__ */ jsx("label", { htmlFor: "about", children: "About" }),
1130
- /* @__PURE__ */ jsx(
1131
- "textarea",
1132
- {
1133
- id: "about",
1134
- name: "about",
1135
- value: formData.about || "",
1136
- onChange: handleChange,
1137
- placeholder: "Tell us about yourself",
1138
- rows: 4
1139
- }
1140
- )
1141
- ] }),
1142
- /* @__PURE__ */ jsxs("div", { className: "form-group", children: [
1143
- /* @__PURE__ */ jsx("label", { htmlFor: "picture", children: "Profile Picture URL" }),
1144
- /* @__PURE__ */ jsx(
1145
- "input",
1146
- {
1147
- type: "url",
1148
- id: "picture",
1149
- name: "picture",
1150
- value: formData.picture || "",
1151
- onChange: handleChange,
1152
- placeholder: "https://example.com/avatar.jpg"
1153
- }
1154
- )
1155
- ] }),
1156
- /* @__PURE__ */ jsxs("div", { className: "form-group", children: [
1157
- /* @__PURE__ */ jsx("label", { htmlFor: "website", children: "LinkedIn" }),
1158
- /* @__PURE__ */ jsx(
1159
- "input",
1160
- {
1161
- type: "url",
1162
- id: "website",
1163
- name: "website",
1164
- value: formData.website || "",
1165
- onChange: handleChange,
1166
- placeholder: "https://linkedin.com/example"
1167
- }
1168
- )
1169
- ] }),
1170
- saveMessage && /* @__PURE__ */ jsx("div", { className: `save-message ${saveMessage.includes("Error") ? "error" : "success"}`, children: saveMessage }),
1171
- (isGettingRole || suggestedRole) && /* @__PURE__ */ jsx("div", { className: "role-tag-container", children: isGettingRole ? /* @__PURE__ */ jsxs(Fragment, { children: [
1172
- /* @__PURE__ */ jsx("div", { className: "role-tag-label", children: "Getting AI suggestion..." }),
1173
- /* @__PURE__ */ jsx("div", { className: "role-tag-loading", children: /* @__PURE__ */ jsx("div", { className: "role-tag-spinner" }) })
1174
- ] }) : suggestedRole ? /* @__PURE__ */ jsxs(Fragment, { children: [
1175
- /* @__PURE__ */ jsx("div", { className: "role-tag-label", children: "AI Suggested Role:" }),
1176
- /* @__PURE__ */ jsx("div", { className: "role-tag", children: suggestedRole })
1177
- ] }) : null }),
1178
- /* @__PURE__ */ jsx("div", { className: "form-actions", children: /* @__PURE__ */ jsx("button", { type: "submit", className: "save-button", disabled: isSaving, children: isSaving ? "Saving..." : "Save Profile" }) })
1179
- ] })
1180
- ] }) });
1058
+
1059
+ //#endregion
1060
+ //#region src/components/profile/ProfilePage.tsx
1061
+ const PersonhoodInfo = () => /* @__PURE__ */ jsxs("section", {
1062
+ className: "personhood-info",
1063
+ children: [/* @__PURE__ */ jsxs("p", { children: [
1064
+ "Network‑state members receive a ",
1065
+ /* @__PURE__ */ jsx("strong", { children: "Personhood Credential (PHC)" }),
1066
+ " from a trusted authority. The PHC attests that the holder is a unique, real individual. Because the credential lives in your passport, you can present a ",
1067
+ /* @__PURE__ */ jsx("em", { children: "zero‑knowledge proof" }),
1068
+ " that you are verified."
1069
+ ] }), /* @__PURE__ */ jsx("p", { children: "In this form we compare the name you enter with the name disclosed by your verified passport proof. If the two match, the profile will be saved as your business card credential together with a passport tag that references the PHC's unique identifier." })]
1070
+ });
1071
+ const MAX_NAME_LENGTH = 100;
1072
+ const MAX_ABOUT_LENGTH = 1e3;
1073
+ const MAX_URL_LENGTH = 2048;
1074
+ function ProfilePage({ authService, relayService, publicKey, onUnauthenticated, onSuccess, onRoleSuggestion }) {
1075
+ const [isLoading, setIsLoading] = useState(false);
1076
+ const [isSaving, setIsSaving] = useState(false);
1077
+ const [saveMessage, setSaveMessage] = useState(null);
1078
+ const [suggestedRole, setSuggestedRole] = useState(null);
1079
+ const [isGettingRole, setIsGettingRole] = useState(false);
1080
+ const [formData, setFormData] = useState({
1081
+ name: "",
1082
+ display_name: "",
1083
+ about: "",
1084
+ picture: "",
1085
+ website: ""
1086
+ });
1087
+ useEffect(() => {
1088
+ if (!publicKey) {
1089
+ if (onUnauthenticated) onUnauthenticated();
1090
+ return;
1091
+ }
1092
+ loadProfile();
1093
+ }, [publicKey]);
1094
+ const loadProfile = async () => {
1095
+ if (!publicKey) return;
1096
+ setIsLoading(true);
1097
+ try {
1098
+ const [profile, roleTag] = await Promise.all([relayService.fetchProfile(publicKey), relayService.fetchProfileRoleTag(publicKey)]);
1099
+ if (profile) setFormData({
1100
+ name: sanitizeText(profile.name || ""),
1101
+ display_name: sanitizeText(profile.display_name || ""),
1102
+ about: sanitizeText(profile.about || ""),
1103
+ picture: profile.picture || "",
1104
+ website: profile.website || ""
1105
+ });
1106
+ if (roleTag) setSuggestedRole(roleTag);
1107
+ } catch (error) {
1108
+ console.error("Failed to load profile:", error);
1109
+ } finally {
1110
+ setIsLoading(false);
1111
+ }
1112
+ };
1113
+ const handleSubmit = async (e) => {
1114
+ e.preventDefault();
1115
+ if (!publicKey) return;
1116
+ setIsSaving(true);
1117
+ setSaveMessage(null);
1118
+ try {
1119
+ const tags = [];
1120
+ if (!isValidPubkey(publicKey)) throw new Error("Invalid public key format");
1121
+ if (formData.about && formData.about.trim().length > 0 && onRoleSuggestion) {
1122
+ setIsGettingRole(true);
1123
+ try {
1124
+ const roleSuggestion = await onRoleSuggestion(formData.about);
1125
+ const candidate = roleSuggestion ? roleSuggestion.trim() : "";
1126
+ if (candidate && isValidRoleTag(candidate)) {
1127
+ tags.push(["role", candidate]);
1128
+ setSuggestedRole(candidate);
1129
+ } else setSuggestedRole(null);
1130
+ } catch (error) {
1131
+ console.error("Failed to get role suggestion:", error);
1132
+ setSuggestedRole(null);
1133
+ } finally {
1134
+ setIsGettingRole(false);
1135
+ }
1136
+ } else setSuggestedRole(null);
1137
+ const profileEvent = {
1138
+ kind: 0,
1139
+ content: JSON.stringify({
1140
+ ...formData,
1141
+ name: sanitizeText(formData.name || ""),
1142
+ display_name: sanitizeText(formData.display_name || ""),
1143
+ about: sanitizeText(formData.about || "")
1144
+ }),
1145
+ created_at: Math.floor(Date.now() / 1e3),
1146
+ tags
1147
+ };
1148
+ const follows = {
1149
+ kind: 3,
1150
+ content: "",
1151
+ created_at: Math.floor(Date.now() / 1e3),
1152
+ tags: [(() => {
1153
+ const followTag = ["p", publicKey];
1154
+ const relayUrl = relayService.getRelays()[0];
1155
+ if (relayUrl) followTag.push(relayUrl);
1156
+ if (formData.name) followTag.push(formData.name);
1157
+ return followTag;
1158
+ })()]
1159
+ };
1160
+ const signedProfile = await authService.signEvent(profileEvent);
1161
+ const signedFollows = await authService.signEvent(follows);
1162
+ await relayService.publishEvent(signedProfile);
1163
+ await relayService.publishEvent(signedFollows);
1164
+ setSaveMessage("Profile saved successfully!");
1165
+ setTimeout(() => {
1166
+ setSaveMessage(null);
1167
+ }, 3e3);
1168
+ if (onSuccess) onSuccess();
1169
+ } catch (error) {
1170
+ console.error("Failed to save profile:", error);
1171
+ setSaveMessage("Failed to save profile. Please try again.");
1172
+ } finally {
1173
+ setIsSaving(false);
1174
+ }
1175
+ };
1176
+ const handleChange = (e) => {
1177
+ const { name, value } = e.target;
1178
+ setFormData((prev) => ({
1179
+ ...prev,
1180
+ [name]: value
1181
+ }));
1182
+ };
1183
+ if (isLoading) return /* @__PURE__ */ jsx("div", {
1184
+ className: "profile-container",
1185
+ children: /* @__PURE__ */ jsxs("div", {
1186
+ className: "loading-state",
1187
+ children: [/* @__PURE__ */ jsx("div", { className: "spinner" }), /* @__PURE__ */ jsx("p", { children: "Loading profile..." })]
1188
+ })
1189
+ });
1190
+ return /* @__PURE__ */ jsx("div", {
1191
+ className: "profile-container",
1192
+ children: /* @__PURE__ */ jsxs("div", {
1193
+ className: "profile-card",
1194
+ children: [
1195
+ /* @__PURE__ */ jsx("h1", { children: "Profile Setup" }),
1196
+ /* @__PURE__ */ jsx(PersonhoodInfo, {}),
1197
+ /* @__PURE__ */ jsxs("form", {
1198
+ onSubmit: handleSubmit,
1199
+ className: "profile-form",
1200
+ children: [
1201
+ /* @__PURE__ */ jsxs("div", {
1202
+ className: "form-group",
1203
+ children: [/* @__PURE__ */ jsx("label", {
1204
+ htmlFor: "name",
1205
+ children: "First Name"
1206
+ }), /* @__PURE__ */ jsx("input", {
1207
+ type: "text",
1208
+ id: "name",
1209
+ name: "name",
1210
+ value: formData.name || "",
1211
+ onChange: handleChange,
1212
+ placeholder: "Your username",
1213
+ maxLength: MAX_NAME_LENGTH
1214
+ })]
1215
+ }),
1216
+ /* @__PURE__ */ jsxs("div", {
1217
+ className: "form-group",
1218
+ children: [/* @__PURE__ */ jsx("label", {
1219
+ htmlFor: "display_name",
1220
+ children: "Last Name"
1221
+ }), /* @__PURE__ */ jsx("input", {
1222
+ type: "text",
1223
+ id: "display_name",
1224
+ name: "display_name",
1225
+ value: formData.display_name || "",
1226
+ onChange: handleChange,
1227
+ placeholder: "Your Last Name",
1228
+ maxLength: MAX_NAME_LENGTH
1229
+ })]
1230
+ }),
1231
+ /* @__PURE__ */ jsxs("div", {
1232
+ className: "form-group",
1233
+ children: [/* @__PURE__ */ jsx("label", {
1234
+ htmlFor: "about",
1235
+ children: "About"
1236
+ }), /* @__PURE__ */ jsx("textarea", {
1237
+ id: "about",
1238
+ name: "about",
1239
+ value: formData.about || "",
1240
+ onChange: handleChange,
1241
+ placeholder: "Tell us about yourself",
1242
+ rows: 4,
1243
+ maxLength: MAX_ABOUT_LENGTH
1244
+ })]
1245
+ }),
1246
+ /* @__PURE__ */ jsxs("div", {
1247
+ className: "form-group",
1248
+ children: [/* @__PURE__ */ jsx("label", {
1249
+ htmlFor: "picture",
1250
+ children: "Profile Picture URL"
1251
+ }), /* @__PURE__ */ jsx("input", {
1252
+ type: "url",
1253
+ id: "picture",
1254
+ name: "picture",
1255
+ value: formData.picture || "",
1256
+ onChange: handleChange,
1257
+ placeholder: "https://example.com/avatar.jpg",
1258
+ maxLength: MAX_URL_LENGTH
1259
+ })]
1260
+ }),
1261
+ /* @__PURE__ */ jsxs("div", {
1262
+ className: "form-group",
1263
+ children: [/* @__PURE__ */ jsx("label", {
1264
+ htmlFor: "website",
1265
+ children: "LinkedIn"
1266
+ }), /* @__PURE__ */ jsx("input", {
1267
+ type: "url",
1268
+ id: "website",
1269
+ name: "website",
1270
+ value: formData.website || "",
1271
+ onChange: handleChange,
1272
+ placeholder: "https://linkedin.com/example",
1273
+ maxLength: MAX_URL_LENGTH
1274
+ })]
1275
+ }),
1276
+ saveMessage && /* @__PURE__ */ jsx("div", {
1277
+ className: `save-message ${saveMessage.includes("Error") ? "error" : "success"}`,
1278
+ children: saveMessage
1279
+ }),
1280
+ (isGettingRole || suggestedRole) && /* @__PURE__ */ jsx("div", {
1281
+ className: "role-tag-container",
1282
+ children: isGettingRole ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
1283
+ className: "role-tag-label",
1284
+ children: "Getting AI suggestion..."
1285
+ }), /* @__PURE__ */ jsx("div", {
1286
+ className: "role-tag-loading",
1287
+ children: /* @__PURE__ */ jsx("div", { className: "role-tag-spinner" })
1288
+ })] }) : suggestedRole ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
1289
+ className: "role-tag-label",
1290
+ children: "AI Suggested Role:"
1291
+ }), /* @__PURE__ */ jsx("div", {
1292
+ className: "role-tag",
1293
+ children: sanitizeText(suggestedRole)
1294
+ })] }) : null
1295
+ }),
1296
+ /* @__PURE__ */ jsx("div", {
1297
+ className: "form-actions",
1298
+ children: /* @__PURE__ */ jsx("button", {
1299
+ type: "submit",
1300
+ className: "save-button",
1301
+ disabled: isSaving,
1302
+ children: isSaving ? "Saving..." : "Save Profile"
1303
+ })
1304
+ })
1305
+ ]
1306
+ })
1307
+ ]
1308
+ })
1309
+ });
1181
1310
  }
1311
+
1312
+ //#endregion
1313
+ //#region src/hooks/useAuth.ts
1314
+ /**
1315
+ * Hook to initialize auth state on app load
1316
+ */
1182
1317
  function useAuthInit(authService, setAuthenticated) {
1183
- useEffect(() => {
1184
- if (authService.hasKeyInfo()) {
1185
- const keyInfo = authService.getCurrentKeyInfo();
1186
- if (keyInfo) {
1187
- setAuthenticated(keyInfo);
1188
- }
1189
- }
1190
- }, [authService, setAuthenticated]);
1318
+ useEffect(() => {
1319
+ if (authService.hasKeyInfo()) {
1320
+ const keyInfo = authService.getCurrentKeyInfo();
1321
+ if (keyInfo) setAuthenticated(keyInfo);
1322
+ }
1323
+ }, [authService, setAuthenticated]);
1191
1324
  }
1192
- var createAuthStore = () => {
1193
- return create((set) => ({
1194
- isAuthenticated: false,
1195
- publicKey: null,
1196
- keyInfo: null,
1197
- loginError: null,
1198
- setAuthenticated: (keyInfo) => {
1199
- set({
1200
- isAuthenticated: !!keyInfo,
1201
- publicKey: keyInfo?.pubkey || null,
1202
- keyInfo,
1203
- loginError: null
1204
- });
1205
- },
1206
- setLoginError: (error) => {
1207
- set({ loginError: error });
1208
- },
1209
- logout: () => {
1210
- set({
1211
- isAuthenticated: false,
1212
- publicKey: null,
1213
- keyInfo: null,
1214
- loginError: null
1215
- });
1216
- }
1217
- }));
1325
+
1326
+ //#endregion
1327
+ //#region src/store/authStore.ts
1328
+ const createAuthStore = () => {
1329
+ return create((set) => ({
1330
+ isAuthenticated: false,
1331
+ publicKey: null,
1332
+ keyInfo: null,
1333
+ loginError: null,
1334
+ setAuthenticated: (keyInfo) => {
1335
+ set({
1336
+ isAuthenticated: !!keyInfo,
1337
+ publicKey: keyInfo?.pubkey || null,
1338
+ keyInfo,
1339
+ loginError: null
1340
+ });
1341
+ },
1342
+ setLoginError: (error) => {
1343
+ set({ loginError: error });
1344
+ },
1345
+ logout: () => {
1346
+ set({
1347
+ isAuthenticated: false,
1348
+ publicKey: null,
1349
+ keyInfo: null,
1350
+ loginError: null
1351
+ });
1352
+ }
1353
+ }));
1218
1354
  };
1219
- var useAuthStore = createAuthStore();
1355
+ const useAuthStore = createAuthStore();
1220
1356
 
1357
+ //#endregion
1221
1358
  export { AuthService, BarcodeScanner, LoginButton, MembershipPage, ProfilePage, RegistrationFlow, RelayService, createAuthStore, useAuthInit, useAuthStore };
1222
- //# sourceMappingURL=index.mjs.map
1223
1359
  //# sourceMappingURL=index.mjs.map