bitcoincash-oauth-client 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,267 @@
1
+ # Bitcoin Cash OAuth Client
2
+
3
+ Universal JavaScript client library for Bitcoin Cash OAuth authentication. Works in both **browser** and **Node.js** environments using the same API.
4
+
5
+ ## Features
6
+
7
+ - 🔐 **Bitcoin Cash Authentication** - Uses ECDSA signatures for secure authentication
8
+ - 🌐 **Universal** - Works in browser and Node.js without changes
9
+ - 📦 **Lightweight** - Minimal dependencies using libauth
10
+ - 🎯 **TypeScript** - Full TypeScript support with type definitions
11
+ - ⚡ **Modern** - Supports ES modules and CommonJS
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install bitcoincash-oauth-client
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### Browser (ES Modules)
22
+
23
+ ```html
24
+ <script type="module">
25
+ import { BitcoinCashOAuthClient } from './node_modules/bitcoincash-oauth-client/dist/index.mjs';
26
+
27
+ const client = new BitcoinCashOAuthClient({
28
+ serverUrl: 'http://localhost:8000',
29
+ network: 'mainnet',
30
+ secureStorage: localStorage
31
+ });
32
+
33
+ // Generate keypair
34
+ const keypair = await client.generateKeypair();
35
+ console.log('Address:', keypair.address);
36
+
37
+ // Register and authenticate
38
+ const registration = await client.register(keypair.address);
39
+ const auth = await client.authenticate(
40
+ registration.user_id,
41
+ keypair.privateKey,
42
+ keypair.publicKey
43
+ );
44
+
45
+ console.log('Access token:', auth.access_token);
46
+ </script>
47
+ ```
48
+
49
+ ### Node.js
50
+
51
+ ```javascript
52
+ import { BitcoinCashOAuthClient } from 'bitcoincash-oauth-client';
53
+
54
+ const client = new BitcoinCashOAuthClient({
55
+ serverUrl: 'http://localhost:8000',
56
+ network: 'mainnet'
57
+ // secureStorage is optional in Node.js
58
+ });
59
+
60
+ async function main() {
61
+ // Generate keypair
62
+ const keypair = await client.generateKeypair();
63
+ console.log('Address:', keypair.address);
64
+
65
+ // Register and authenticate
66
+ const registration = await client.register(keypair.address);
67
+ const auth = await client.authenticate(
68
+ registration.user_id,
69
+ keypair.privateKey,
70
+ keypair.publicKey
71
+ );
72
+
73
+ console.log('Authenticated! Token:', auth.access_token);
74
+
75
+ // Make authenticated request
76
+ const response = await client.authenticatedRequest('/api/protected-resource');
77
+ const data = await response.json();
78
+ console.log(data);
79
+ }
80
+
81
+ main();
82
+ ```
83
+
84
+ ### CommonJS (Node.js)
85
+
86
+ ```javascript
87
+ const { BitcoinCashOAuthClient } = require('bitcoincash-oauth-client');
88
+
89
+ const client = new BitcoinCashOAuthClient({
90
+ serverUrl: 'http://localhost:8000',
91
+ network: 'mainnet'
92
+ });
93
+
94
+ // ... same usage as ES module version
95
+ ```
96
+
97
+ ## API Reference
98
+
99
+ ### Constructor Options
100
+
101
+ ```javascript
102
+ const client = new BitcoinCashOAuthClient({
103
+ serverUrl: 'http://localhost:8000', // OAuth server URL
104
+ network: 'mainnet', // 'mainnet' or 'testnet'
105
+ secureStorage: localStorage, // Optional: storage for tokens
106
+ fetch: customFetch // Optional: custom fetch implementation
107
+ });
108
+ ```
109
+
110
+ ### Methods
111
+
112
+ #### `init()`
113
+ Initialize the client (automatically called by other methods).
114
+
115
+ ```javascript
116
+ await client.init();
117
+ ```
118
+
119
+ #### `generateKeypair()`
120
+ Generate a new Bitcoin Cash keypair.
121
+
122
+ ```javascript
123
+ const { privateKey, publicKey, address } = await client.generateKeypair();
124
+ ```
125
+
126
+ **Returns:**
127
+ - `privateKey` (string): Hex-encoded private key
128
+ - `publicKey` (string): Hex-encoded compressed public key
129
+ - `address` (string): Bitcoin Cash CashAddr address
130
+
131
+ #### `register(address, userId?)`
132
+ Register a new user with the OAuth server.
133
+
134
+ ```javascript
135
+ const result = await client.register('bitcoincash:qz...', 'optional-user-id');
136
+ console.log(result.user_id);
137
+ ```
138
+
139
+ #### `authenticate(userId, privateKey, publicKey, timestamp?, domain?)`
140
+ Authenticate with the server using ECDSA signature.
141
+
142
+ ```javascript
143
+ const auth = await client.authenticate(
144
+ userId,
145
+ privateKeyHex,
146
+ publicKeyHex,
147
+ null, // Optional: custom timestamp
148
+ 'app.example.com' // Optional: domain for message binding (defaults to window.location.host)
149
+ );
150
+
151
+ console.log(auth.access_token);
152
+ console.log(auth.refresh_token);
153
+ console.log(auth.expires_in);
154
+ ```
155
+
156
+ **Message Format:** The signed message uses the format `bitcoincash-oauth|domain|userId|timestamp`:
157
+ - `bitcoincash-oauth`: Protocol identifier (prevents cross-protocol replay)
158
+ - `domain`: Domain/host binding (prevents phishing, defaults to current host)
159
+ - `userId`: User's unique identifier
160
+ - `timestamp`: Unix timestamp for replay protection
161
+
162
+ #### `authenticatedRequest(endpoint, options?)`
163
+ Make an authenticated HTTP request.
164
+
165
+ ```javascript
166
+ const response = await client.authenticatedRequest('/api/user/profile', {
167
+ method: 'GET'
168
+ });
169
+ const data = await response.json();
170
+ ```
171
+
172
+ #### `refreshToken(refreshToken)`
173
+ Refresh an expired access token.
174
+
175
+ ```javascript
176
+ const newAuth = await client.refreshToken(refreshToken);
177
+ ```
178
+
179
+ #### `revokeToken(token)`
180
+ Revoke a token on the server.
181
+
182
+ ```javascript
183
+ await client.revokeToken(token);
184
+ ```
185
+
186
+ #### `getToken()`
187
+ Get the currently stored token from secure storage.
188
+
189
+ ```javascript
190
+ const token = client.getToken();
191
+ ```
192
+
193
+ #### `createAuthMessage(userId, timestamp?, domain?)`
194
+ Create the authentication message format used for signing.
195
+
196
+ ```javascript
197
+ const message = client.createAuthMessage('user_123', 1234567890, 'app.example.com');
198
+ // Returns: "bitcoincash-oauth|app.example.com|user_123|1234567890"
199
+ ```
200
+
201
+ **Parameters:**
202
+ - `userId` (string): The user's unique identifier
203
+ - `timestamp` (number, optional): Unix timestamp (defaults to current time)
204
+ - `domain` (string, optional): Domain for message binding (defaults to `window.location.host` or 'oauth')
205
+
206
+ **Returns:** Message string in format `bitcoincash-oauth|domain|userId|timestamp`
207
+
208
+ #### `signAuthMessage(message, privateKeyHex)`
209
+ Sign an authentication message with a private key.
210
+
211
+ ```javascript
212
+ const message = client.createAuthMessage('user_123', 1234567890, 'app.example.com');
213
+ // Returns: "bitcoincash-oauth|app.example.com|user_123|1234567890"
214
+
215
+ const signature = await client.signAuthMessage(message, privateKeyHex);
216
+ ```
217
+
218
+ ## Storage Interface
219
+
220
+ The `secureStorage` option accepts any object implementing this interface:
221
+
222
+ ```javascript
223
+ interface SecureStorage {
224
+ getItem(key: string): string | null;
225
+ setItem(key: string, value: string): void;
226
+ removeItem(key: string): void;
227
+ }
228
+ ```
229
+
230
+ ### Browser Example (localStorage)
231
+
232
+ ```javascript
233
+ const client = new BitcoinCashOAuthClient({
234
+ secureStorage: localStorage
235
+ });
236
+ ```
237
+
238
+ ### Node.js Example (custom)
239
+
240
+ ```javascript
241
+ const client = new BitcoinCashOAuthClient({
242
+ secureStorage: {
243
+ storage: new Map(),
244
+ getItem(key) { return this.storage.get(key) || null; },
245
+ setItem(key, value) { this.storage.set(key, value); },
246
+ removeItem(key) { this.storage.delete(key); }
247
+ }
248
+ });
249
+ ```
250
+
251
+ ## Requirements
252
+
253
+ - **Node.js**: 14.0.0 or higher
254
+ - **Browser**: Modern browsers with ES2018+ support
255
+ - **Fetch API**: Available natively in Node.js 18+ and all modern browsers
256
+
257
+ ## Build from Source
258
+
259
+ ```bash
260
+ cd packages/bitcoincash-oauth-js
261
+ npm install
262
+ npm run build
263
+ ```
264
+
265
+ ## License
266
+
267
+ MIT