@konemono/nostr-login 1.9.13 → 1.10.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.
@@ -1,180 +0,0 @@
1
- import { EventEmitter } from 'tseep';
2
- import { Nip46Client } from './Nip46Client';
3
- import { PrivateKeySigner } from '../Signer';
4
-
5
- export class Nip46Adapter extends EventEmitter {
6
- private client: Nip46Client;
7
- private localSigner: PrivateKeySigner;
8
- public userPubkey: string = '';
9
- public remotePubkey: string;
10
-
11
- constructor(client: Nip46Client, localSigner: PrivateKeySigner) {
12
- super();
13
- this.client = client;
14
- this.localSigner = localSigner;
15
- this.remotePubkey = (client as any).remotePubkey || '';
16
-
17
- // forward events
18
- this.client.on('authUrl', (url: string) => {
19
- this.emit('authUrl', url);
20
- });
21
- this.client.on('response', ({ response, pubkey }: any) => {
22
- this.emit('response', response, pubkey);
23
- });
24
- }
25
-
26
- async initUserPubkey(hintPubkey?: string) {
27
- if (this.userPubkey) throw new Error('Already called initUserPubkey');
28
- if (hintPubkey) {
29
- this.userPubkey = hintPubkey;
30
- console.log('[Nip46Adapter] User pubkey set from hint:', hintPubkey);
31
- return;
32
- }
33
-
34
- console.log('[Nip46Adapter] Fetching user pubkey');
35
- try {
36
- const res = await this.client.sendRequest('get_public_key', []);
37
- if (!res) throw new Error('No public key returned');
38
- this.userPubkey = res;
39
- console.log('[Nip46Adapter] User pubkey fetched:', res);
40
- } catch (error: any) {
41
- console.error('[Nip46Adapter] Failed to get user pubkey:', error.message);
42
- throw error;
43
- }
44
- }
45
-
46
- /**
47
- * nostrconnect:// フロー - 受信待機
48
- * サイナーからの接続を待つ
49
- */
50
- async listen(nostrConnectSecret: string, timeoutMs: number = 60000): Promise<string> {
51
- console.log('[Nip46Adapter] Starting listen mode, timeout:', timeoutMs);
52
-
53
- return new Promise<string>((resolve, reject) => {
54
- const timer = setTimeout(() => {
55
- cleanup();
56
- const error = new Error(`Listen timeout after ${timeoutMs}ms`);
57
- console.error('[Nip46Adapter]', error.message);
58
- reject(error);
59
- }, timeoutMs);
60
-
61
- const cleanup = () => {
62
- clearTimeout(timer);
63
- this.client.off('response', onResponse);
64
- };
65
-
66
- const onResponse = ({ response, pubkey }: any) => {
67
- if (!response) return;
68
-
69
- // auth_urlは無視(別のハンドラが処理)
70
- if (response.result === 'auth_url') return;
71
-
72
- // 成功: ack または secret が返される
73
- if (response.result === 'ack' || response.result === nostrConnectSecret) {
74
- cleanup();
75
- console.log('[Nip46Adapter] Listen succeeded, signer pubkey:', pubkey);
76
- resolve(pubkey);
77
- } else if (response.error) {
78
- cleanup();
79
- console.error('[Nip46Adapter] Listen failed:', response.error);
80
- reject(new Error(response.error));
81
- }
82
- };
83
-
84
- this.client.on('response', onResponse);
85
- });
86
- }
87
-
88
- /**
89
- * bunker:// フロー - 能動的接続
90
- * サイナーに接続リクエストを送る
91
- */
92
- async connect(token?: string, perms?: string, timeoutMs: number = 30000): Promise<void> {
93
- console.log('[Nip46Adapter] Connecting with token, timeout:', timeoutMs);
94
-
95
- try {
96
- const result = await this.client.sendRequest('connect', [this.localSigner.pubkey, token || '', perms || ''], timeoutMs);
97
-
98
- if (result !== 'ack') {
99
- throw new Error(`Connect failed: ${result || 'unknown error'}`);
100
- }
101
-
102
- console.log('[Nip46Adapter] Connected successfully');
103
- } catch (error: any) {
104
- console.error('[Nip46Adapter] Connect failed:', error.message);
105
- throw error;
106
- }
107
- }
108
-
109
- async setListenReply(reply: any, nostrConnectSecret: string) {
110
- // reply is expected to be a raw event object; we'll try to parse its content
111
- // Attempt to decrypt via the client flow by treating it as a response
112
- try {
113
- const decoded = reply && reply.content ? JSON.parse(reply.content) : null;
114
- if (!decoded) throw new Error('Bad reply');
115
- if (decoded.result === nostrConnectSecret) {
116
- this.userPubkey = reply.pubkey;
117
- } else {
118
- throw new Error('Bad reply');
119
- }
120
- } catch (e) {
121
- throw new Error('Failed to set listen reply');
122
- }
123
- }
124
-
125
- async createAccount2({ bunkerPubkey, name, domain, perms = '' }: { bunkerPubkey: string; name: string; domain: string; perms?: string }) {
126
- const params = [name, domain, '', perms];
127
-
128
- console.log('[Nip46Adapter] Creating account:', { name, domain });
129
- try {
130
- const r = await this.client.sendRequest('create_account', params);
131
- if (!r) throw new Error('create_account returned empty result');
132
- if (r === 'error') throw new Error('create_account failed');
133
- console.log('[Nip46Adapter] Account created successfully');
134
- return r;
135
- } catch (error: any) {
136
- console.error('[Nip46Adapter] Failed to create account:', error.message);
137
- throw error;
138
- }
139
- }
140
-
141
- async encrypt(recipientPubkey: string, plaintext: string) {
142
- const r = await this.client.sendRequest('nip04_encrypt', [recipientPubkey, plaintext]);
143
- return r;
144
- }
145
-
146
- async decrypt(recipientPubkey: string, ciphertext: string) {
147
- const r = await this.client.sendRequest('nip04_decrypt', [recipientPubkey, ciphertext]);
148
- return r;
149
- }
150
-
151
- async sign(event: any) {
152
- try {
153
- const r = await this.client.sendRequest('sign_event', [JSON.stringify(event)]);
154
- try {
155
- const parsed = typeof r === 'string' ? JSON.parse(r) : r;
156
- if (parsed && parsed.sig) return parsed.sig;
157
- } catch (e) {
158
- // not JSON
159
- }
160
- return r;
161
- } catch (error: any) {
162
- console.error('[Nip46Adapter] Failed to sign event:', error.message);
163
- throw error;
164
- }
165
- }
166
-
167
- // provide rpc compatibility
168
- get rpc() {
169
- return {
170
- sendRequest: async (remotePubkey: string, method: string, params: string[], kind: number, cb: (res: any) => void) => {
171
- try {
172
- const res = await this.client.sendRequest(method, params);
173
- cb({ result: res });
174
- } catch (err: any) {
175
- cb({ error: err.message });
176
- }
177
- },
178
- };
179
- }
180
- }
@@ -1,363 +0,0 @@
1
- import { SimplePool, Event as NostrEvent, getPublicKey, nip04 } from 'nostr-tools';
2
- import { Nip44 } from '../../utils/nip44';
3
- import { EventEmitter } from 'tseep';
4
- import { Nip46Request, Nip46Response, PendingRequest, Nip46ClientOptions } from './types';
5
- import { getEventHash, getSignature } from 'nostr-tools';
6
-
7
- // Ensure crypto.subtle is available
8
- if (typeof globalThis.crypto === 'undefined' || !globalThis.crypto.subtle) {
9
- if (typeof globalThis.crypto !== 'undefined' && (globalThis.crypto as any).webcrypto) {
10
- (globalThis.crypto as any).subtle = (globalThis.crypto as any).webcrypto.subtle;
11
- }
12
- }
13
-
14
- export class Nip46Client extends EventEmitter {
15
- private pool: SimplePool;
16
- private localPrivateKey: string;
17
- private remotePubkey: string;
18
- private relays: string[];
19
- private pendingRequests: Map<string, PendingRequest> = new Map();
20
- private defaultTimeoutMs: number;
21
- private useNip44: boolean;
22
- private subscription: any = null;
23
- private isSubscribed: boolean = false;
24
- private nip44Codec: Nip44 = new Nip44();
25
- private iframeConfig?: { origin: string; port?: MessagePort };
26
- private retryConfig: { maxRetries: number; retryDelayMs: number };
27
- private iframeKeepaliveInterval?: NodeJS.Timeout;
28
-
29
- constructor(options: Nip46ClientOptions) {
30
- super();
31
- this.pool = new SimplePool();
32
- this.localPrivateKey = options.localPrivateKey;
33
- this.remotePubkey = options.remotePubkey;
34
- this.relays = options.relays;
35
- this.defaultTimeoutMs = options.timeoutMs || 30000;
36
- this.useNip44 = options.useNip44 || false;
37
- this.iframeConfig = options.iframeConfig;
38
- this.retryConfig = options.retryConfig || { maxRetries: 3, retryDelayMs: 1000 };
39
-
40
- // iframe用のメッセージハンドラを設定
41
- if (this.iframeConfig?.port) {
42
- this.setupIframePort(this.iframeConfig.port);
43
- }
44
- }
45
-
46
- get localPubkey(): string {
47
- return getPublicKey(this.localPrivateKey);
48
- }
49
-
50
- /**
51
- * NIP-46リクエストを送信(リトライ機能付き)
52
- */
53
- async sendRequest(method: string, params: string[] = [], timeoutMs?: number): Promise<string> {
54
- let lastError: Error | null = null;
55
-
56
- for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
57
- try {
58
- if (attempt > 0) {
59
- const delay = this.retryConfig.retryDelayMs * attempt;
60
- console.log(`[Nip46Client] Retry attempt ${attempt}/${this.retryConfig.maxRetries} for ${method} after ${delay}ms`);
61
- await new Promise(resolve => setTimeout(resolve, delay));
62
- }
63
-
64
- return await this.sendRequestInternal(method, params, timeoutMs);
65
- } catch (error: any) {
66
- lastError = error;
67
-
68
- // タイムアウトまたはネットワークエラーの場合のみリトライ
69
- const shouldRetry = error.message.includes('timed out') || error.message.includes('network') || error.message.includes('publish');
70
-
71
- if (!shouldRetry || attempt === this.retryConfig.maxRetries) {
72
- console.error(`[Nip46Client] Request failed after ${attempt + 1} attempts:`, error.message);
73
- throw error;
74
- }
75
- }
76
- }
77
-
78
- throw lastError || new Error('Request failed after retries');
79
- }
80
-
81
- /**
82
- * NIP-46リクエストを送信(内部実装)
83
- */
84
- private async sendRequestInternal(method: string, params: string[] = [], timeoutMs?: number): Promise<string> {
85
- const timeout = timeoutMs || this.defaultTimeoutMs;
86
- const id = this.generateId();
87
- const request: Nip46Request = { id, method, params };
88
-
89
- console.log('[Nip46Client] Sending request:', { id, method, params });
90
-
91
- // レスポンス購読を開始(まだの場合)
92
- if (!this.isSubscribed) {
93
- this.subscribeToResponses();
94
- }
95
-
96
- // リクエストイベントを作成・送信
97
- await this.publishRequest(request);
98
-
99
- // レスポンスを待つPromise
100
- return new Promise<string>((resolve, reject) => {
101
- const timer = setTimeout(() => {
102
- this.pendingRequests.delete(id);
103
- const error = new Error(`Request ${id} (${method}) timed out after ${timeout}ms`);
104
- console.error('[Nip46Client]', error.message);
105
- reject(error);
106
- }, timeout);
107
-
108
- this.pendingRequests.set(id, {
109
- resolve,
110
- reject,
111
- timer,
112
- method,
113
- });
114
- });
115
- }
116
-
117
- /**
118
- * リクエストイベントを作成して送信
119
- */
120
- private async publishRequest(request: Nip46Request): Promise<void> {
121
- const content = JSON.stringify(request);
122
-
123
- // 暗号化
124
- const encrypted = this.useNip44
125
- ? await this.nip44Codec.encrypt(this.localPrivateKey, this.remotePubkey, content)
126
- : await nip04.encrypt(this.localPrivateKey, this.remotePubkey, content);
127
-
128
- // イベント作成
129
- const event: NostrEvent = {
130
- kind: 24133,
131
- pubkey: this.localPubkey,
132
- created_at: Math.floor(Date.now() / 1000),
133
- tags: [['p', this.remotePubkey]],
134
- content: encrypted,
135
- id: '',
136
- sig: '',
137
- };
138
-
139
- // ID計算
140
- event.id = getEventHash(event);
141
-
142
- // 署名
143
- event.sig = getSignature(event, this.localPrivateKey);
144
-
145
- // iframeがある場合は優先的に使用
146
- if (this.iframeConfig?.port) {
147
- try {
148
- this.iframeConfig.port.postMessage(event);
149
- console.log('[Nip46Client] Request sent via iframe:', request.id);
150
- return;
151
- } catch (e) {
152
- console.warn('[Nip46Client] Iframe send failed, falling back to relays:', e);
153
- }
154
- }
155
-
156
- // リレーに送信
157
- try {
158
- await Promise.any(this.pool.publish(this.relays, event));
159
- console.log('[Nip46Client] Request published to relays:', request.id);
160
- } catch (e) {
161
- console.error('[Nip46Client] Failed to publish to relays:', e);
162
- throw new Error('Failed to publish request to relays');
163
- }
164
- }
165
-
166
- /**
167
- * レスポンスイベントを購読
168
- */
169
- private subscribeToResponses(): void {
170
- if (this.isSubscribed) return;
171
-
172
- const filter = {
173
- 'kinds': [24133],
174
- '#p': [this.localPubkey],
175
- 'since': Math.floor(Date.now() / 1000) - 60,
176
- };
177
-
178
- console.log('[Nip46Client] Subscribing to responses');
179
-
180
- // SimplePool subscription
181
- this.subscription = this.pool.sub(this.relays, [filter]);
182
- this.subscription.on('event', async (event: NostrEvent) => {
183
- await this.handleResponseEvent(event);
184
- });
185
- this.subscription.on('eose', () => {
186
- console.log('[Nip46Client] EOSE received');
187
- });
188
-
189
- this.isSubscribed = true;
190
- }
191
-
192
- /**
193
- * レスポンスイベントを処理
194
- */
195
- private async handleResponseEvent(event: NostrEvent): Promise<void> {
196
- try {
197
- // 復号化
198
- const decrypted = this.isNip04(event.content)
199
- ? await nip04.decrypt(this.localPrivateKey, event.pubkey, event.content)
200
- : await this.nip44Codec.decrypt(this.localPrivateKey, event.pubkey, event.content);
201
-
202
- const response: Nip46Response = JSON.parse(decrypted);
203
-
204
- console.log('[Nip46Client] Response received:', {
205
- id: response.id,
206
- hasResult: !!response.result,
207
- hasError: !!response.error,
208
- });
209
-
210
- // Emit response event for consumers (include sender pubkey)
211
- this.emit('response', { response, pubkey: event.pubkey });
212
-
213
- // auth_urlの特別処理: OAuth完了後に実際のレスポンスが来るまで待つ
214
- if (response.result === 'auth_url') {
215
- console.log('[Nip46Client] Auth URL received:', response.error);
216
- this.emit('authUrl', response.error);
217
- // 注意: pendingRequestsは削除しない
218
- // OAuth完了後に同じIDで実際のレスポンスが返ってくる
219
- return;
220
- }
221
-
222
- // 保留中のリクエストを解決
223
- const pending = this.pendingRequests.get(response.id);
224
- if (pending) {
225
- clearTimeout(pending.timer);
226
- this.pendingRequests.delete(response.id);
227
-
228
- if (response.error) {
229
- console.error('[Nip46Client] Request failed:', {
230
- id: response.id,
231
- method: pending.method,
232
- error: response.error,
233
- });
234
- pending.reject(new Error(response.error));
235
- } else if (response.result !== undefined) {
236
- console.log('[Nip46Client] Request succeeded:', {
237
- id: response.id,
238
- method: pending.method,
239
- });
240
- pending.resolve(response.result);
241
- } else {
242
- pending.reject(new Error('Invalid response: no result or error'));
243
- }
244
- } else {
245
- console.warn('[Nip46Client] Received response for unknown request:', response.id);
246
- }
247
- } catch (error) {
248
- console.error('[Nip46Client] Failed to parse response event:', error);
249
- }
250
- }
251
-
252
- /**
253
- * NIP-04かNIP-44かを判定
254
- */
255
- private isNip04(ciphertext: string): boolean {
256
- const l = ciphertext.length;
257
- if (l < 28) return false;
258
- return ciphertext[l - 28] === '?' && ciphertext[l - 27] === 'i' && ciphertext[l - 26] === 'v' && ciphertext[l - 25] === '=';
259
- }
260
-
261
- /**
262
- * ランダムIDを生成
263
- */
264
- private generateId(): string {
265
- return Math.random().toString(36).substring(2, 15);
266
- }
267
-
268
- /**
269
- * NIP-44を使用するかどうかを設定
270
- */
271
- setUseNip44(useNip44: boolean): void {
272
- this.useNip44 = useNip44;
273
- }
274
-
275
- /**
276
- * クリーンアップ
277
- */
278
- cleanup(): void {
279
- console.log('[Nip46Client] Cleaning up');
280
-
281
- // すべての保留中リクエストをキャンセル
282
- for (const [id, pending] of this.pendingRequests) {
283
- clearTimeout(pending.timer);
284
- pending.reject(new Error('Client cleanup'));
285
- }
286
- this.pendingRequests.clear();
287
-
288
- // 購読を停止
289
- if (this.subscription) {
290
- // SimplePool subscriptions may use `unsub` or `close`
291
- try {
292
- if (typeof this.subscription.unsub === 'function') this.subscription.unsub();
293
- if (typeof this.subscription.close === 'function') this.subscription.close();
294
- } catch (e) {
295
- // ignore
296
- }
297
- this.subscription = null;
298
- this.isSubscribed = false;
299
- }
300
-
301
- // iframeのkeepaliveをクリア
302
- if (this.iframeKeepaliveInterval) {
303
- clearInterval(this.iframeKeepaliveInterval);
304
- this.iframeKeepaliveInterval = undefined;
305
- }
306
-
307
- // リレー接続を閉じる
308
- this.pool.close(this.relays);
309
-
310
- // イベントリスナーをクリア
311
- this.removeAllListeners();
312
- }
313
-
314
- /**
315
- * 接続状態を確認
316
- */
317
- isConnected(): boolean {
318
- return this.isSubscribed;
319
- }
320
-
321
- /**
322
- * iframeポートを設定
323
- */
324
- setIframePort(port: MessagePort): void {
325
- if (!this.iframeConfig) {
326
- throw new Error('Iframe config not set');
327
- }
328
- this.iframeConfig.port = port;
329
- this.setupIframePort(port);
330
- }
331
-
332
- /**
333
- * iframe用のメッセージハンドラを設定
334
- */
335
- private setupIframePort(port: MessagePort): void {
336
- port.onmessage = async (ev: MessageEvent) => {
337
- if (ev.data === 'ping') return;
338
-
339
- try {
340
- const event = ev.data;
341
- // validate and handle event
342
- if (!event || typeof event !== 'object') {
343
- console.warn('[Nip46Client] Invalid message from iframe');
344
- return;
345
- }
346
- await this.handleResponseEvent(event);
347
- } catch (e) {
348
- console.error('[Nip46Client] Iframe message error:', e);
349
- }
350
- };
351
-
352
- // Keep alive
353
- this.iframeKeepaliveInterval = setInterval(() => {
354
- try {
355
- port.postMessage('ping');
356
- } catch (e) {
357
- console.warn('[Nip46Client] Failed to send keepalive ping:', e);
358
- }
359
- }, 5000);
360
-
361
- console.log('[Nip46Client] Iframe port setup complete');
362
- }
363
- }
@@ -1,34 +0,0 @@
1
- export interface Nip46Request {
2
- id: string;
3
- method: string;
4
- params: string[];
5
- }
6
-
7
- export interface Nip46Response {
8
- id: string;
9
- result?: string;
10
- error?: string;
11
- }
12
-
13
- export interface PendingRequest {
14
- resolve: (result: string) => void;
15
- reject: (error: Error) => void;
16
- timer: NodeJS.Timeout;
17
- method: string;
18
- }
19
-
20
- export interface Nip46ClientOptions {
21
- localPrivateKey: string;
22
- remotePubkey: string;
23
- relays: string[];
24
- timeoutMs?: number;
25
- useNip44?: boolean;
26
- iframeConfig?: {
27
- origin: string;
28
- port?: MessagePort;
29
- };
30
- retryConfig?: {
31
- maxRetries: number;
32
- retryDelayMs: number;
33
- };
34
- }
package/vitest.config.ts DELETED
@@ -1,9 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
-
3
- export default defineConfig({
4
- test: {
5
- globals: true,
6
- environment: 'node',
7
- include: ['src/**/*.test.ts'],
8
- },
9
- });