@minimoth/sdk-node 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) 2026 MiniMoth
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,216 @@
1
+ # @minimoth/sdk-node
2
+
3
+ Official Node.js SDK for [MiniMoth](https://minimoth.dev) — SMS and WhatsApp OTP authentication for Indian developers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @minimoth/sdk-node
9
+ ```
10
+
11
+ Requires Node.js 18+.
12
+
13
+ ## Quick Start
14
+
15
+ ```ts
16
+ import { MiniMoth } from '@minimoth/sdk-node'
17
+
18
+ const client = new MiniMoth({
19
+ apiKey: 'mm_live_...', // from app.minimoth.dev
20
+ })
21
+
22
+ // Send OTP
23
+ await client.otp.send({ phone: '919876543210' })
24
+
25
+ // Verify OTP
26
+ const result = await client.otp.verify({ phone: '919876543210', otp: '123456' })
27
+ if (result.valid) {
28
+ // Store tokens — SDK auto-stores in memory by default
29
+ console.log(result.accessToken, result.refreshToken, result.sessionId)
30
+ }
31
+
32
+ // Validate on every request
33
+ const session = await client.session.validate(req.headers['x-access-token'])
34
+ // session.phone, session.projectId, session.sessionId, session.expiresAt
35
+ // If session.newTokens is set, send new tokens back to client
36
+
37
+ // Safe variant — never throws
38
+ const safe = await client.session.safeValidate(token)
39
+ if (!safe.valid) {
40
+ res.status(401).json({ error: safe.code })
41
+ return
42
+ }
43
+
44
+ // Refresh — SDK handles this automatically on validate(); call manually only if needed proactively
45
+ const tokens = await client.session.refresh(refreshToken)
46
+
47
+ // Logout (auto-refreshes if access token is expired)
48
+ await client.session.logout({ accessToken, refreshToken })
49
+ ```
50
+
51
+ ## Configuration
52
+
53
+ ```ts
54
+ const client = new MiniMoth({
55
+ apiKey: 'mm_live_...', // required
56
+
57
+ // Logging
58
+ logLevel: 'info', // 'debug' | 'info' | 'warn' | 'error' | 'silent'
59
+ logger: pinoInstance, // optional — any { debug, info, warn, error } object
60
+
61
+ // Session
62
+ session: {
63
+ validateMode: 'instant', // see validateMode below
64
+ store: myRedisStore, // optional — see Session Store below
65
+ }
66
+ })
67
+
68
+ client.setLogLevel('warn') // update at runtime (only affects built-in console logger)
69
+ ```
70
+
71
+ ## validateMode
72
+
73
+ | Mode | What it does | On network error |
74
+ |---|---|---|
75
+ | `instant` (default) | Local JWT verify only — zero network round trip | n/a |
76
+ | `recheck_1m` | JWT verify + revocation check, cached 60s per token | Fail open (warn + allow) |
77
+ | `recheck_3m` | JWT verify + revocation check, cached 180s per token | Fail open (warn + allow) |
78
+ | `strict` | JWT verify + revocation check on every call | Fail closed (throw) |
79
+
80
+ ## Session Store
81
+
82
+ By default, the SDK uses an in-memory Map. In production with multiple server replicas, provide a shared store (e.g. Redis):
83
+
84
+ ```ts
85
+ const client = new MiniMoth({
86
+ apiKey: 'mm_live_...',
87
+ session: {
88
+ store: {
89
+ async getRefreshToken(sessionId) {
90
+ return redis.get(`mm:rt:${sessionId}`)
91
+ },
92
+ async setTokens(sessionId, { accessToken, refreshToken }) {
93
+ await redis.set(`mm:rt:${sessionId}`, refreshToken, 'EX', 30 * 24 * 60 * 60)
94
+ },
95
+ async deleteSession(sessionId) {
96
+ await redis.del(`mm:rt:${sessionId}`)
97
+ },
98
+ }
99
+ }
100
+ })
101
+ ```
102
+
103
+ ## Error Handling
104
+
105
+ ```ts
106
+ import { MiniMothError } from '@minimoth/sdk-node'
107
+
108
+ try {
109
+ await client.session.validate(token)
110
+ } catch (err) {
111
+ if (err instanceof MiniMothError) {
112
+ // err.code: 'TOKEN_EXPIRED' | 'TOKEN_REVOKED' | 'INVALID_TOKEN' | ...
113
+ // err.statusCode: HTTP status (0 for network errors)
114
+ res.status(401).json({ error: err.code })
115
+ }
116
+ }
117
+ ```
118
+
119
+ Use `safeValidate` / `otp.verify` to avoid try/catch:
120
+
121
+ ```ts
122
+ const result = await client.session.safeValidate(token)
123
+ if (!result.valid) return res.status(401).json({ error: result.code })
124
+ const { session } = result
125
+ ```
126
+
127
+ ## API Reference
128
+
129
+ ### OtpClient
130
+
131
+ #### `send(options)`
132
+
133
+ Send an OTP to the given phone number.
134
+
135
+ - `phone` (string, required): Indian phone number (e.g. `919876543210`)
136
+ - Returns: Promise<void>
137
+ - Throws: `MiniMothError` on rate limit or network error
138
+
139
+ #### `verify(options)`
140
+
141
+ Verify the OTP code and establish a session.
142
+
143
+ - `phone` (string, required): Indian phone number
144
+ - `otp` (string, required): 6-digit OTP
145
+ - Returns: Promise<{ valid: boolean; accessToken?: string; refreshToken?: string; sessionId?: string }>
146
+ - Does not throw; always returns a result object
147
+
148
+ ### SessionClient
149
+
150
+ #### `validate(accessToken)`
151
+
152
+ Validate an access token and return the session.
153
+
154
+ - `accessToken` (string, required): JWT access token
155
+ - Returns: Promise<Session> where Session includes `phone`, `projectId`, `sessionId`, `expiresAt`, and optionally `newTokens`
156
+ - Throws: `MiniMothError` on invalid, expired, or revoked token
157
+
158
+ #### `safeValidate(accessToken)`
159
+
160
+ Non-throwing variant of `validate`.
161
+
162
+ - `accessToken` (string, required): JWT access token
163
+ - Returns: Promise<{ valid: boolean; session?: Session; code?: string }>
164
+
165
+ #### `refresh(refreshToken)`
166
+
167
+ Manually rotate access and refresh tokens ahead of expiry. The SDK handles refresh automatically when `session.validate()` encounters an expired access token — use this method only when you need to refresh proactively (e.g. before a long-running job).
168
+
169
+ - `refreshToken` (string, required): Refresh token from verify or previous refresh
170
+ - Returns: Promise<{ accessToken: string; refreshToken: string }>
171
+ - Throws: `MiniMothError` on invalid or expired token
172
+
173
+ #### `logout(options)`
174
+
175
+ Revoke all tokens for a session.
176
+
177
+ - `accessToken` (string, required): Current access token (will be auto-refreshed if expired)
178
+ - `refreshToken` (string, required): Current refresh token
179
+ - Returns: Promise<void>
180
+ - Does not throw; logs errors instead
181
+
182
+ ## Error Codes
183
+
184
+ Common `MiniMothError.code` values:
185
+
186
+ - `INVALID_OTP`: OTP code does not match
187
+ - `OTP_EXPIRED`: OTP has expired (max 10 minutes)
188
+ - `INVALID_TOKEN`: Token could not be decoded
189
+ - `TOKEN_EXPIRED`: Access token has expired (use refresh to get new token)
190
+ - `TOKEN_REVOKED`: Token was revoked (session logout or theft detected)
191
+ - `RATE_LIMITED`: Too many requests — wait before retrying
192
+ - `INSUFFICIENT_BALANCE`: Account has insufficient credits/balance
193
+ - `NETWORK_ERROR`: Network request failed
194
+ - `UNKNOWN_ERROR`: Unexpected server error
195
+
196
+ ## TypeScript
197
+
198
+ The SDK is fully typed. All client methods include inline JSDoc and return properly typed objects:
199
+
200
+ ```ts
201
+ import { MiniMoth, MiniMothError } from '@minimoth/sdk-node'
202
+
203
+ const client = new MiniMoth({ apiKey: 'mm_live_...' })
204
+
205
+ // All methods are fully typed
206
+ const result = await client.otp.verify({
207
+ phone: '919876543210',
208
+ otp: '123456',
209
+ })
210
+
211
+ const session: Session = await client.session.validate(token)
212
+ ```
213
+
214
+ ## License
215
+
216
+ MIT