@smarthivelabs-devs/auth-sdk 0.1.0 → 1.0.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/README.md +402 -0
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
# @smarthivelabs-devs/auth-sdk
|
|
2
|
+
|
|
3
|
+
Core JavaScript/TypeScript SDK for SmartHive Auth. Framework-agnostic — works in the browser, Node.js 18+, and React Native. This is the foundation that `auth-react`, `auth-expo`, and `auth-server` are all built on.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @smarthivelabs-devs/auth-sdk
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @smarthivelabs-devs/auth-sdk
|
|
13
|
+
# or
|
|
14
|
+
yarn add @smarthivelabs-devs/auth-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Prerequisites
|
|
20
|
+
|
|
21
|
+
You need a SmartHive Auth project. From your SmartHive dashboard grab:
|
|
22
|
+
|
|
23
|
+
- `projectId` — e.g. `proj_abc123`
|
|
24
|
+
- `publishableKey` — e.g. `pk_live_abc123`
|
|
25
|
+
- `baseUrl` — the URL of your SmartHive Auth service instance
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { initAuth } from "@smarthivelabs-devs/auth-sdk";
|
|
33
|
+
|
|
34
|
+
const client = initAuth({
|
|
35
|
+
projectId: "proj_abc123",
|
|
36
|
+
publishableKey: "pk_live_abc123",
|
|
37
|
+
baseUrl: "https://auth.myapp.com",
|
|
38
|
+
redirectUri: "https://myapp.com/auth/callback",
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Initialize (validates your project config against the server)
|
|
42
|
+
await client.initialize();
|
|
43
|
+
|
|
44
|
+
// Redirect the user to the SmartHive login page
|
|
45
|
+
await client.login();
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Configuration
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
interface SmartHiveAuthConfig {
|
|
54
|
+
/** Your SmartHive project ID */
|
|
55
|
+
projectId: string;
|
|
56
|
+
|
|
57
|
+
/** Your publishable (public) key */
|
|
58
|
+
publishableKey: string;
|
|
59
|
+
|
|
60
|
+
/** Base URL of your SmartHive Auth service */
|
|
61
|
+
baseUrl: string;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Custom branded auth domain (e.g. "https://auth.myapp.com").
|
|
65
|
+
* Used as the entry point for login/token flows.
|
|
66
|
+
* Falls back to baseUrl if not set.
|
|
67
|
+
*/
|
|
68
|
+
authDomain?: string;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Fallback auth domain if authDomain is unreachable.
|
|
72
|
+
* Useful for high-availability setups.
|
|
73
|
+
*/
|
|
74
|
+
fallbackAuthDomain?: string;
|
|
75
|
+
|
|
76
|
+
/** Default OAuth redirect URI after login */
|
|
77
|
+
redirectUri?: string;
|
|
78
|
+
|
|
79
|
+
/** Custom persistent storage adapter (default: localStorage in browser) */
|
|
80
|
+
storage?: AuthStorage;
|
|
81
|
+
|
|
82
|
+
/** Custom temporary storage for PKCE values (default: sessionStorage in browser) */
|
|
83
|
+
temporaryStorage?: AuthStorage;
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## API Reference
|
|
90
|
+
|
|
91
|
+
### `initAuth(config)`
|
|
92
|
+
|
|
93
|
+
Creates and returns a `SmartHiveAuthClient`. Call this once at your app's entry point.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
const client = initAuth({
|
|
97
|
+
projectId: "proj_abc123",
|
|
98
|
+
publishableKey: "pk_live_abc123",
|
|
99
|
+
baseUrl: "https://auth.myapp.com",
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
### `client.initialize()`
|
|
106
|
+
|
|
107
|
+
Validates your project configuration with the SmartHive server. Call this before any auth operations.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
await client.initialize();
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Throws `SmartHiveAuthError` with code `project_not_found` if the project or key is invalid.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
### `client.login(options?)`
|
|
118
|
+
|
|
119
|
+
Starts the OAuth 2.0 + PKCE login flow by redirecting the user to the SmartHive login page.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
// Basic login (uses redirectUri from config)
|
|
123
|
+
await client.login();
|
|
124
|
+
|
|
125
|
+
// Override the redirect URI for this login attempt
|
|
126
|
+
await client.login({ redirectUri: "https://myapp.com/auth/callback" });
|
|
127
|
+
|
|
128
|
+
// Pass custom state (returned in the callback URL)
|
|
129
|
+
await client.login({ state: "my-custom-state" });
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
### `client.handleCallback(options?)`
|
|
135
|
+
|
|
136
|
+
Completes the OAuth flow on your callback route. Exchanges the authorization code for tokens and persists the session.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// In your /auth/callback page — reads from window.location automatically
|
|
140
|
+
const session = await client.handleCallback();
|
|
141
|
+
|
|
142
|
+
// Or pass the URL explicitly (useful in SSR or React Native)
|
|
143
|
+
const session = await client.handleCallback({ url: "https://myapp.com/auth/callback?code=...&state=..." });
|
|
144
|
+
|
|
145
|
+
console.log(session.accessToken);
|
|
146
|
+
console.log(session.refreshToken);
|
|
147
|
+
console.log(session.expiresAt); // Unix timestamp in ms
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Throws `SmartHiveAuthError` with codes:
|
|
151
|
+
- `callback_failed` — missing code or URL
|
|
152
|
+
- `state_mismatch` — possible CSRF attack
|
|
153
|
+
- `pkce_missing` — PKCE verifier not found (session expired between steps)
|
|
154
|
+
- `token_error` — server rejected the code exchange
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
### `client.getSession()`
|
|
159
|
+
|
|
160
|
+
Returns the current session from storage, or `null` if not signed in. Does not refresh expired tokens automatically.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
const session = await client.getSession();
|
|
164
|
+
if (session) {
|
|
165
|
+
console.log("Signed in:", session.accessToken);
|
|
166
|
+
} else {
|
|
167
|
+
console.log("Not signed in");
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
### `client.getAccessToken()`
|
|
174
|
+
|
|
175
|
+
Returns a valid access token. Automatically refreshes using the refresh token if the access token is within 30 seconds of expiry.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
const token = await client.getAccessToken();
|
|
179
|
+
if (token) {
|
|
180
|
+
// token is always fresh when truthy
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
### `client.getAuthorizationHeader()`
|
|
187
|
+
|
|
188
|
+
Returns a `{ authorization: "Bearer <token>" }` header object ready to spread into fetch options. Returns an empty object if not signed in.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
const headers = await client.getAuthorizationHeader();
|
|
192
|
+
const res = await fetch("/api/protected", { headers });
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
### `client.fetch(input, init?)`
|
|
198
|
+
|
|
199
|
+
Drop-in replacement for `fetch` that automatically injects the `Authorization` header.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
// Identical to native fetch, but auth is handled automatically
|
|
203
|
+
const res = await client.fetch("/api/user/profile");
|
|
204
|
+
const res2 = await client.fetch("https://api.myapp.com/data", {
|
|
205
|
+
method: "POST",
|
|
206
|
+
body: JSON.stringify({ name: "Alice" }),
|
|
207
|
+
headers: { "content-type": "application/json" },
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
### `client.refreshSession()`
|
|
214
|
+
|
|
215
|
+
Explicitly refreshes the session using the stored refresh token. Returns the new session, or `null` if the refresh token is missing or expired (which also clears the stored session).
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
const newSession = await client.refreshSession();
|
|
219
|
+
if (!newSession) {
|
|
220
|
+
// Refresh token expired — user must log in again
|
|
221
|
+
await client.login();
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
### `client.logout()`
|
|
228
|
+
|
|
229
|
+
Clears the local session and calls the server-side sign-out endpoint.
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
await client.logout();
|
|
233
|
+
// User is now signed out — redirect them to your home/login page
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
### `client.getUser()`
|
|
239
|
+
|
|
240
|
+
Fetches the current user's profile from the SmartHive userinfo endpoint. Returns `null` if not signed in.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
const user = await client.getUser();
|
|
244
|
+
console.log(user); // { sub: "user_123", email: "alice@example.com", ... }
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
### `client.verifyToken(token)`
|
|
250
|
+
|
|
251
|
+
Verifies a raw access token against the SmartHive userinfo endpoint. Returns `true` if the token is valid and accepted by the server.
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
const isValid = await client.verifyToken(rawToken);
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
## Custom Storage Adapter
|
|
260
|
+
|
|
261
|
+
By default the SDK uses `localStorage` for persistent storage and `sessionStorage` for PKCE state. Provide your own adapter to use any other storage backend (IndexedDB, AsyncStorage, SecureStore, Redis, etc.).
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { initAuth, type AuthStorage } from "@smarthivelabs-devs/auth-sdk";
|
|
265
|
+
|
|
266
|
+
const myStorage: AuthStorage = {
|
|
267
|
+
getItem: async (key) => {
|
|
268
|
+
return await myDatabase.get(key);
|
|
269
|
+
},
|
|
270
|
+
setItem: async (key, value) => {
|
|
271
|
+
await myDatabase.set(key, value);
|
|
272
|
+
},
|
|
273
|
+
removeItem: async (key) => {
|
|
274
|
+
await myDatabase.delete(key);
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
const client = initAuth({
|
|
279
|
+
projectId: "proj_abc123",
|
|
280
|
+
publishableKey: "pk_live_abc123",
|
|
281
|
+
baseUrl: "https://auth.myapp.com",
|
|
282
|
+
storage: myStorage,
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
## PKCE Helpers
|
|
289
|
+
|
|
290
|
+
Low-level PKCE utilities exported for advanced use cases (e.g. building your own auth client on top of this SDK).
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
import {
|
|
294
|
+
generateCodeVerifier,
|
|
295
|
+
generateCodeChallenge,
|
|
296
|
+
} from "@smarthivelabs-devs/auth-sdk";
|
|
297
|
+
|
|
298
|
+
const verifier = await generateCodeVerifier(); // random 32-byte base64url string
|
|
299
|
+
const challenge = await generateCodeChallenge(verifier); // SHA-256(verifier), base64url encoded
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
Uses the Web Crypto API — works in browsers and Node.js 18+.
|
|
303
|
+
|
|
304
|
+
---
|
|
305
|
+
|
|
306
|
+
## Error Handling
|
|
307
|
+
|
|
308
|
+
All async methods throw `SmartHiveAuthError` on failure.
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
import { SmartHiveAuthError } from "@smarthivelabs-devs/auth-sdk";
|
|
312
|
+
|
|
313
|
+
try {
|
|
314
|
+
await client.login();
|
|
315
|
+
} catch (err) {
|
|
316
|
+
if (err instanceof SmartHiveAuthError) {
|
|
317
|
+
console.error(err.code); // e.g. "project_not_found"
|
|
318
|
+
console.error(err.message); // human-readable description
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Common error codes:
|
|
324
|
+
|
|
325
|
+
| Code | When |
|
|
326
|
+
|---|---|
|
|
327
|
+
| `project_not_found` | `initialize()` — invalid projectId or publishableKey |
|
|
328
|
+
| `callback_failed` | `handleCallback()` — no code in URL |
|
|
329
|
+
| `state_mismatch` | `handleCallback()` — OAuth state doesn't match (CSRF) |
|
|
330
|
+
| `pkce_missing` | `handleCallback()` — PKCE verifier not in storage |
|
|
331
|
+
| `token_error` | `handleCallback()` — server rejected code exchange |
|
|
332
|
+
|
|
333
|
+
---
|
|
334
|
+
|
|
335
|
+
## Vanilla JS/TS Example (Full Flow)
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import { initAuth, SmartHiveAuthError } from "@smarthivelabs-devs/auth-sdk";
|
|
339
|
+
|
|
340
|
+
const client = initAuth({
|
|
341
|
+
projectId: import.meta.env.VITE_AUTH_PROJECT_ID,
|
|
342
|
+
publishableKey: import.meta.env.VITE_AUTH_PUBLISHABLE_KEY,
|
|
343
|
+
baseUrl: import.meta.env.VITE_AUTH_BASE_URL,
|
|
344
|
+
redirectUri: `${window.location.origin}/auth/callback`,
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
// Entry point — runs on every page load
|
|
348
|
+
await client.initialize();
|
|
349
|
+
const session = await client.getSession();
|
|
350
|
+
|
|
351
|
+
// Login button
|
|
352
|
+
document.getElementById("login-btn")?.addEventListener("click", () => {
|
|
353
|
+
client.login();
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
// Logout button
|
|
357
|
+
document.getElementById("logout-btn")?.addEventListener("click", async () => {
|
|
358
|
+
await client.logout();
|
|
359
|
+
window.location.href = "/";
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
// Callback page (e.g. /auth/callback)
|
|
363
|
+
if (window.location.pathname === "/auth/callback") {
|
|
364
|
+
try {
|
|
365
|
+
await client.handleCallback();
|
|
366
|
+
window.location.href = "/dashboard";
|
|
367
|
+
} catch (err) {
|
|
368
|
+
if (err instanceof SmartHiveAuthError) {
|
|
369
|
+
console.error("Auth failed:", err.code, err.message);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
---
|
|
376
|
+
|
|
377
|
+
## TypeScript Types
|
|
378
|
+
|
|
379
|
+
```ts
|
|
380
|
+
import type {
|
|
381
|
+
SmartHiveAuthConfig,
|
|
382
|
+
SmartHiveAuthClient,
|
|
383
|
+
AuthSession,
|
|
384
|
+
AuthStorage,
|
|
385
|
+
} from "@smarthivelabs-devs/auth-sdk";
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
---
|
|
389
|
+
|
|
390
|
+
## Related Packages
|
|
391
|
+
|
|
392
|
+
| Package | Use case |
|
|
393
|
+
|---|---|
|
|
394
|
+
| [`@smarthivelabs-devs/auth-react`](https://www.npmjs.com/package/@smarthivelabs-devs/auth-react) | React web apps — provider, hooks, components |
|
|
395
|
+
| [`@smarthivelabs-devs/auth-expo`](https://www.npmjs.com/package/@smarthivelabs-devs/auth-expo) | React Native / Expo apps |
|
|
396
|
+
| [`@smarthivelabs-devs/auth-server`](https://www.npmjs.com/package/@smarthivelabs-devs/auth-server) | Express / Next.js server-side JWT verification |
|
|
397
|
+
|
|
398
|
+
---
|
|
399
|
+
|
|
400
|
+
## License
|
|
401
|
+
|
|
402
|
+
MIT © SmartHive Labs
|
package/package.json
CHANGED