Skip to content

Commit 23653ed

Browse files
committed
[docs] add JWT section to README
1 parent 6365bd8 commit 23653ed

File tree

1 file changed

+153
-55
lines changed

1 file changed

+153
-55
lines changed

README.md

Lines changed: 153 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 📱 SMS Gateway for Android™ JS/TS API Client
1+
# 📱 SMSGate JS/TS API Client
22

33
[![npm Version](https://img.shields.io/npm/v/android-sms-gateway.svg?style=for-the-badge)](https://www.npmjs.com/package/android-sms-gateway)
44
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=for-the-badge)](https://github.com/android-sms-gateway/client-ts/blob/master/LICENSE)
@@ -7,14 +7,17 @@
77
[![GitHub Stars](https://img.shields.io/github/stars/android-sms-gateway/client-ts.svg?style=for-the-badge)](https://github.com/android-sms-gateway/client-ts/stargazers)
88
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg?style=for-the-badge)](https://www.typescriptlang.org/)
99

10-
A TypeScript-first client for seamless integration with the [SMS Gateway for Android](https://sms-gate.app) API. Programmatically send SMS messages through your Android devices with strict typing and modern JavaScript features.
10+
A TypeScript-first client for seamless integration with the [SMSGate](https://sms-gate.app) API. Programmatically send SMS messages through your Android devices with strict typing and modern JavaScript features.
1111

1212
**Note**: The API doesn't provide CORS headers, so the library cannot be used in a browser environment directly.
1313

1414
## 📖 Table of Contents
1515

16-
- [📱 SMS Gateway for Android™ JS/TS API Client](#-sms-gateway-for-android-jsts-api-client)
16+
- [📱 SMSGate JS/TS API Client](#-smsgate-jsts-api-client)
1717
- [📖 Table of Contents](#-table-of-contents)
18+
- [🔐 Authentication](#-authentication)
19+
- [Basic Authentication](#basic-authentication)
20+
- [JWT Authentication](#jwt-authentication)
1821
- [✨ Features](#-features)
1922
- [⚙️ Requirements](#️-requirements)
2023
- [📦 Installation](#-installation)
@@ -28,6 +31,7 @@ A TypeScript-first client for seamless integration with the [SMS Gateway for And
2831
- [Settings Management](#settings-management)
2932
- [🤖 Client Guide](#-client-guide)
3033
- [Client Configuration](#client-configuration)
34+
- [Authentication Configuration](#authentication-configuration)
3135
- [Core Methods](#core-methods)
3236
- [Type Definitions](#type-definitions)
3337
- [🌐 HTTP Clients](#-http-clients)
@@ -37,6 +41,28 @@ A TypeScript-first client for seamless integration with the [SMS Gateway for And
3741
- [Development Setup](#development-setup)
3842
- [📄 License](#-license)
3943

44+
## 🔐 Authentication
45+
46+
The SMSGate client supports two authentication methods: **Basic Authentication** and **JWT (JSON Web Token) Authentication**. JWT is the recommended approach for production environments due to its enhanced security features and support for scoped permissions.
47+
48+
### Basic Authentication
49+
50+
Basic Authentication uses a username and password to access the API. This method is simple but less secure for production use.
51+
52+
**When to use:**
53+
- Simple integrations
54+
- Development and testing
55+
- Legacy systems
56+
57+
### JWT Authentication
58+
59+
JWT Authentication uses bearer tokens with configurable scopes to access the API. This method provides enhanced security and fine-grained access control.
60+
61+
**When to use:**
62+
- Production environments
63+
- Applications requiring scoped permissions
64+
- Systems with multiple components needing different access levels
65+
4066
## ✨ Features
4167

4268
- **TypeScript Ready**: Full type definitions out of the box
@@ -73,75 +99,80 @@ bun add android-sms-gateway
7399
```typescript
74100
import Client from 'android-sms-gateway';
75101

76-
// Create a fetch-based HTTP client
77-
const httpFetchClient = {
78-
get: async (url, headers) => {
79-
const response = await fetch(url, {
80-
method: "GET",
81-
headers
82-
});
83-
84-
return response.json();
85-
},
86-
post: async (url, body, headers) => {
87-
const response = await fetch(url, {
88-
method: "POST",
89-
headers,
90-
body: JSON.stringify(body)
91-
});
92-
93-
return response.json();
94-
},
95-
delete: async (url, headers) => {
96-
const response = await fetch(url, {
97-
method: "DELETE",
98-
headers
99-
});
100-
101-
return response.json();
102-
}
103-
};
104-
105-
// Initialize client
106-
const api = new Client(
102+
// First, create a client with Basic Auth to generate a JWT token
103+
const basicAuthClient = new Client(
107104
process.env.ANDROID_SMS_GATEWAY_LOGIN!,
108-
process.env.ANDROID_SMS_GATEWAY_PASSWORD!,
109-
httpFetchClient
105+
process.env.ANDROID_SMS_GATEWAY_PASSWORD!
110106
);
111107

112-
// Send message
113-
const message = {
114-
phoneNumbers: ['+1234567890'],
115-
message: 'Secure OTP: 123456 🔐'
116-
};
108+
// Generate a JWT token with specific scopes
109+
async function generateJWTToken() {
110+
try {
111+
const tokenRequest = {
112+
scopes: [
113+
"messages:send",
114+
"messages:read",
115+
"devices:list"
116+
],
117+
ttl: 3600 // Token expires in 1 hour
118+
};
119+
120+
const tokenResponse = await basicAuthClient.generateToken(tokenRequest);
121+
console.log('JWT Token generated, expires at:', tokenResponse.expires_at);
122+
return tokenResponse.access_token;
123+
} catch (error) {
124+
console.error('Token generation failed:', error);
125+
throw error;
126+
}
127+
}
117128

129+
// Initialize client with JWT Authentication
130+
async function initializeJWTClient() {
131+
const jwtToken = await generateJWTToken();
132+
133+
// Initialize client with JWT token (empty string for login, token for password)
134+
const jwtClient = new Client(
135+
"", // Empty string for login when using JWT
136+
jwtToken // JWT token
137+
);
138+
139+
return jwtClient;
140+
}
141+
142+
// Send message using JWT Authentication
118143
async function sendSMS() {
119144
try {
120-
const state = await api.send(message);
145+
const jwtClient = await initializeJWTClient();
146+
147+
const message = {
148+
phoneNumbers: ['+1234567890'],
149+
message: 'Secure OTP: 123456 🔐'
150+
};
151+
152+
const state = await jwtClient.send(message);
121153
console.log('Message ID:', state.id);
122-
154+
123155
// Check status after 5 seconds
124156
setTimeout(async () => {
125-
const updatedState = await api.getState(state.id);
126-
console.log('Message status:', updatedState.status);
157+
const updatedState = await jwtClient.getState(state.id);
158+
console.log('Message status:', updatedState.state);
127159
}, 5000);
128160
} catch (error) {
129161
console.error('Sending failed:', error);
130162
}
131163
}
132164

133-
// Send message with skipPhoneValidation
134-
async function sendSMSWithSkipValidation() {
165+
// Revoke a JWT token
166+
async function revokeJWTToken(jti: string) {
135167
try {
136-
const state = await api.send(message, { skipPhoneValidation: true });
137-
console.log('Message ID (with skip validation):', state.id);
168+
await basicAuthClient.revokeToken(jti);
169+
console.log('JWT token revoked successfully');
138170
} catch (error) {
139-
console.error('Sending failed:', error);
171+
console.error('Token revocation failed:', error);
140172
}
141173
}
142174

143175
sendSMS();
144-
sendSMSWithSkipValidation();
145176
```
146177

147178
### Webhook Management
@@ -248,11 +279,33 @@ The `Client` class accepts the following constructor arguments:
248279

249280
| Argument | Description | Default |
250281
| ------------ | -------------------------- | ---------------------------------------- |
251-
| `login` | Username | **Required** |
252-
| `password` | Password | **Required** |
253-
| `httpClient` | HTTP client implementation | **Required** |
282+
| `login` | Username or empty string | **Required** |
283+
| `password` | Password or JWT token | **Required** |
284+
| `httpClient` | HTTP client implementation | `fetch` |
254285
| `baseUrl` | API base URL | `"https://api.sms-gate.app/3rdparty/v1"` |
255286

287+
#### Authentication Configuration
288+
289+
**Basic Authentication:**
290+
```typescript
291+
const api = new Client(
292+
process.env.ANDROID_SMS_GATEWAY_LOGIN!, // Username
293+
process.env.ANDROID_SMS_GATEWAY_PASSWORD! // Password
294+
);
295+
```
296+
297+
**JWT Authentication:**
298+
```typescript
299+
const api = new Client(
300+
"", // Empty string for login when using JWT
301+
jwtToken // JWT token
302+
);
303+
```
304+
305+
The client automatically detects which authentication method to use based on the `login` parameter:
306+
- If `login` is a non-empty string: Uses Basic Authentication
307+
- If `login` is an empty string: Uses JWT Authentication with the provided token
308+
256309
### Core Methods
257310

258311
| Method | Description | Returns |
@@ -283,6 +336,10 @@ The `Client` class accepts the following constructor arguments:
283336
| `getSettings()` | Get settings | `Promise<DeviceSettings>` |
284337
| `updateSettings(settings: DeviceSettings)` | Update settings | `Promise<void>` |
285338
| `patchSettings(settings: Partial<DeviceSettings>)` | Partially update settings | `Promise<void>` |
339+
| | | |
340+
| **JWT Token Management** | | |
341+
| `generateToken(request: TokenRequest)` | Generate new JWT token | `Promise<TokenResponse>` |
342+
| `revokeToken(jti: string)` | Revoke JWT token by ID | `Promise<void>` |
286343

287344
### Type Definitions
288345

@@ -348,13 +405,49 @@ interface MessagesExportRequest {
348405
since: string;
349406
until: string;
350407
}
408+
409+
// JWT Authentication Types
410+
411+
interface TokenRequest {
412+
/**
413+
* The scopes to include in the token.
414+
*/
415+
scopes: string[];
416+
417+
/**
418+
* The time-to-live (TTL) of the token in seconds.
419+
*/
420+
ttl?: number;
421+
}
422+
423+
interface TokenResponse {
424+
/**
425+
* The JWT access token.
426+
*/
427+
access_token: string;
428+
429+
/**
430+
* The type of the token.
431+
*/
432+
token_type: string;
433+
434+
/**
435+
* The unique identifier of the token.
436+
*/
437+
id: string;
438+
439+
/**
440+
* The expiration time of the token.
441+
*/
442+
expires_at: string;
443+
}
351444
```
352445

353446
For more details, see the [`domain.ts`](./src/domain.ts).
354447

355448
## 🌐 HTTP Clients
356449

357-
The library doesn't come with built-in HTTP clients. Instead, you should provide your own implementation of the `HttpClient` interface:
450+
The library comes with fetch-based built-in HTTP client. You can provide your own implementation of the `HttpClient` interface:
358451

359452
```typescript
360453
interface HttpClient {
@@ -373,6 +466,11 @@ interface HttpClient {
373466
- Always store credentials in environment variables
374467
- Never expose credentials in client-side code
375468
- Use HTTPS for all production communications
469+
- Rotate passwords regularly
470+
- Use strong, unique passwords
471+
- Use appropriate TTL values based on your security requirements
472+
- Apply the principle of least privilege
473+
- Implement proper token revocation workflows
376474

377475
## 📚 API Reference
378476

0 commit comments

Comments
 (0)