@mavenmm/teamwork-auth 2.0.3 → 2.0.4

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.
Files changed (2) hide show
  1. package/CLAUDE.md +491 -0
  2. package/package.json +3 -2
package/CLAUDE.md ADDED
@@ -0,0 +1,491 @@
1
+ # @mavenmm/teamwork-auth - AI Assistant Guide
2
+
3
+ This file provides guidance for AI assistants (like Claude Code) when helping developers use this package.
4
+
5
+ ## Package Overview
6
+
7
+ **@mavenmm/teamwork-auth** is a React authentication package for Maven Marketing's centralized SSO system. It provides zero-configuration authentication with automatic environment detection.
8
+
9
+ ## Quick Start
10
+
11
+ ```tsx
12
+ import { useTeamworkAuth, Login } from '@mavenmm/teamwork-auth';
13
+
14
+ function App() {
15
+ const { user, isAuthenticated, loading, logout } = useTeamworkAuth();
16
+
17
+ if (loading) return <div>Loading...</div>;
18
+
19
+ if (!isAuthenticated) {
20
+ return <Login
21
+ clientID={import.meta.env.VITE_CLIENT_ID}
22
+ redirectURI={window.location.origin}
23
+ />;
24
+ }
25
+
26
+ return (
27
+ <div>
28
+ <h1>Welcome {user?.firstName}!</h1>
29
+ <button onClick={logout}>Logout</button>
30
+ </div>
31
+ );
32
+ }
33
+ ```
34
+
35
+ ## Environment Detection (Zero Config!)
36
+
37
+ The package automatically detects the environment:
38
+ - `localhost` → uses `http://localhost:9100` (local auth service)
39
+ - `*.mavenmm.com` → uses `https://auth.mavenmm.com` (production)
40
+ - `*.netlify.app` → uses `https://auth.mavenmm.com` (staging)
41
+
42
+ **No manual configuration needed!**
43
+
44
+ ## Required Environment Variables
45
+
46
+ ### For Development (Local Auth Service)
47
+ ```bash
48
+ # In your app's .env file:
49
+ VITE_CLIENT_ID=<teamwork_oauth_client_id>
50
+ VITE_REDIRECT_URI=http://localhost:3000
51
+ VITE_DOMAIN_KEY=dev_localhost_3000 # Must match auth service's DEV_KEY
52
+ ```
53
+
54
+ ### For Production
55
+ ```bash
56
+ # In your deployed app's environment:
57
+ VITE_CLIENT_ID=<teamwork_oauth_client_id>
58
+ VITE_REDIRECT_URI=https://your-app.mavenmm.com
59
+ VITE_DOMAIN_KEY=<unique_key_for_your_app> # Provided by auth.mavenmm.com admin
60
+ ```
61
+
62
+ ## Core API
63
+
64
+ ### `useTeamworkAuth(config?): AuthState`
65
+
66
+ Main authentication hook.
67
+
68
+ **Parameters:**
69
+ - `config` (optional): `TeamworkAuthConfig`
70
+ - `authServiceUrl`: Override auto-detected auth service URL (rarely needed)
71
+ - `domainKey`: Domain authentication key (auto-loaded from env)
72
+
73
+ **Returns:** `AuthState`
74
+ - `user`: User object or null
75
+ - `isAuthenticated`: boolean
76
+ - `loading`: boolean
77
+ - `error`: string or null
78
+ - `authServiceUrl`: Current auth service URL
79
+ - `login(code: string)`: Function to complete OAuth login
80
+ - `logout()`: Function to logout
81
+ - `getAccessToken()`: Function to get current access token
82
+
83
+ **Example:**
84
+ ```tsx
85
+ const { user, isAuthenticated, getAccessToken } = useTeamworkAuth();
86
+
87
+ // Optional: override config
88
+ const { user } = useTeamworkAuth({
89
+ domainKey: import.meta.env.VITE_DOMAIN_KEY,
90
+ });
91
+ ```
92
+
93
+ ### `<Login />` Component
94
+
95
+ Pre-built Teamwork login button.
96
+
97
+ **Props:**
98
+ - `clientID` (required): Teamwork OAuth client ID
99
+ - `redirectURI` (required): OAuth redirect URI (usually `window.location.origin`)
100
+ - `clientSecret` (optional): Not needed in production (handled by auth service)
101
+
102
+ **Example:**
103
+ ```tsx
104
+ <Login
105
+ clientID={import.meta.env.VITE_CLIENT_ID}
106
+ redirectURI={import.meta.env.VITE_REDIRECT_URI}
107
+ />
108
+ ```
109
+
110
+ ### `<AuthProvider />` Component
111
+
112
+ Context provider for auth state. **Usually not needed** - `useTeamworkAuth` hook handles this internally.
113
+
114
+ **Important:** Must be placed inside React Router's Router context if used directly.
115
+
116
+ ```tsx
117
+ import { BrowserRouter, Routes, Route } from 'react-router-dom';
118
+ import { AuthProvider } from '@mavenmm/teamwork-auth';
119
+
120
+ function App() {
121
+ return (
122
+ <BrowserRouter>
123
+ <AuthProvider>
124
+ <Routes>
125
+ <Route path="/" element={<Home />} />
126
+ </Routes>
127
+ </AuthProvider>
128
+ </BrowserRouter>
129
+ );
130
+ }
131
+ ```
132
+
133
+ ## TypeScript Types
134
+
135
+ ```tsx
136
+ import type {
137
+ User,
138
+ TeamworkAuthConfig,
139
+ AuthState
140
+ } from '@mavenmm/teamwork-auth';
141
+ ```
142
+
143
+ ### User Type
144
+ ```typescript
145
+ interface User {
146
+ id: string;
147
+ firstName: string;
148
+ lastName: string;
149
+ email: string;
150
+ avatar?: string;
151
+ company?: {
152
+ id: string;
153
+ name: string;
154
+ };
155
+ }
156
+ ```
157
+
158
+ ### TeamworkAuthConfig Type
159
+ ```typescript
160
+ interface TeamworkAuthConfig {
161
+ authServiceUrl?: string; // Override auto-detection (rarely needed)
162
+ domainKey?: string; // Domain authentication key (auto-loaded from env)
163
+ }
164
+ ```
165
+
166
+ ## Development Workflow
167
+
168
+ ### Setup for Developers
169
+
170
+ 1. **Install the package:**
171
+ ```bash
172
+ npm install @mavenmm/teamwork-auth
173
+ ```
174
+
175
+ 2. **Set up environment variables:**
176
+ Create `.env` file:
177
+ ```bash
178
+ VITE_CLIENT_ID=<your_teamwork_client_id>
179
+ VITE_REDIRECT_URI=http://localhost:3000
180
+ VITE_DOMAIN_KEY=dev_localhost_3000
181
+ ```
182
+
183
+ 3. **Start local auth service:**
184
+ Clone the auth service repo and run:
185
+ ```bash
186
+ git clone <auth-service-repo>
187
+ cd <auth-service-repo>
188
+ netlify dev --port 9100
189
+ ```
190
+
191
+ 4. **Use in your app:**
192
+ ```tsx
193
+ import { useTeamworkAuth, Login } from '@mavenmm/teamwork-auth';
194
+ // Zero config - auto-detects localhost:9100!
195
+ ```
196
+
197
+ ### Common Issues & Solutions
198
+
199
+ **Issue: "Auth service unreachable"**
200
+ - Make sure local auth service is running on port 9100
201
+ - Run: `netlify dev --port 9100` in the auth service directory
202
+ - Check if port 9100 is available (not used by another process)
203
+
204
+ **Issue: "Invalid domain key"**
205
+ - Verify `VITE_DOMAIN_KEY` in your app matches `DEV_KEY` in auth service
206
+ - Both should be: `dev_localhost_3000` for localhost development
207
+
208
+ **Issue: "CORS errors"**
209
+ - Ensure your app's origin is registered in auth service's domain registry
210
+ - Check auth service logs for CORS-related errors
211
+ - For localhost, origin should be `http://localhost:3000` (or your port)
212
+
213
+ **Issue: "401 Unauthorized on refresh"**
214
+ - Normal on first load (no refresh token yet)
215
+ - If persists after login, check browser cookies for `maven_refresh_token`
216
+ - Ensure cookies are enabled in your browser
217
+
218
+ **Issue: "Cookies not working"**
219
+ - Development: Both app and auth service must be on localhost
220
+ - Production: Both must be on HTTPS
221
+ - Cannot test auth.mavenmm.com from localhost (browser security)
222
+
223
+ ## Architecture Notes
224
+
225
+ ### Token Strategy (v2.0)
226
+ - **Access tokens**: 15 minutes, stored in memory (not localStorage)
227
+ - **Refresh tokens**: 7 days, stored in httpOnly cookies
228
+ - **Auto-refresh**: Tokens refresh 1 minute before expiry
229
+ - **Token rotation**: Refresh tokens are single-use and blacklisted after use
230
+
231
+ ### Security Features
232
+ - HttpOnly cookies prevent XSS attacks
233
+ - Domain authentication keys prevent domain spoofing
234
+ - Rate limiting on all endpoints
235
+ - Automatic token rotation and blacklisting
236
+ - Content Security Policy headers
237
+ - Timing-safe key comparison to prevent timing attacks
238
+
239
+ ### Cookie Behavior
240
+ - **localhost**: Cookies work (same domain)
241
+ - **Production (*.mavenmm.com)**: Cookies work (shared domain `.mavenmm.com`)
242
+ - **Staging (*.netlify.app)**: Cookies work (HTTPS cross-site with CORS)
243
+ - **localhost ↔ auth.mavenmm.com**: Won't work (use local auth service instead)
244
+
245
+ ## Advanced Usage
246
+
247
+ ### Getting Access Token for API Calls
248
+ ```tsx
249
+ const { getAccessToken } = useTeamworkAuth();
250
+
251
+ async function callAPI() {
252
+ const token = getAccessToken();
253
+ if (!token) {
254
+ console.error('No access token available');
255
+ return;
256
+ }
257
+
258
+ const response = await fetch('https://api.example.com/data', {
259
+ headers: {
260
+ 'Authorization': `Bearer ${token}`,
261
+ },
262
+ });
263
+ return response.json();
264
+ }
265
+ ```
266
+
267
+ ### Manual Auth Service Override (Rare)
268
+ ```tsx
269
+ // Only needed for custom deployments
270
+ const { user } = useTeamworkAuth({
271
+ authServiceUrl: 'https://custom-auth.example.com',
272
+ domainKey: 'custom_domain_key',
273
+ });
274
+ ```
275
+
276
+ ### Handling OAuth Callback
277
+ The hook automatically handles OAuth callbacks. No manual intervention needed.
278
+
279
+ The OAuth flow:
280
+ 1. User clicks Login button → redirected to Teamwork
281
+ 2. User authenticates with Teamwork
282
+ 3. Teamwork redirects back to your app with `?code=xxx`
283
+ 4. useTeamworkAuth automatically detects the code and logs in
284
+ 5. URL is cleaned up (code parameter removed)
285
+
286
+ ## Environment-Specific Behavior
287
+
288
+ ### Development (localhost)
289
+ ```
290
+ Your App (localhost:3000)
291
+
292
+ Local Auth Service (localhost:9100)
293
+
294
+ Teamwork API
295
+ ```
296
+ - Cookies: Same domain, work perfectly
297
+ - No CORS issues (same origin)
298
+ - Fast development iteration
299
+
300
+ ### Production (*.mavenmm.com)
301
+ ```
302
+ Your App (home.mavenmm.com)
303
+
304
+ Auth Service (auth.mavenmm.com)
305
+
306
+ Teamwork API
307
+ ```
308
+ - Cookies: Shared domain `.mavenmm.com`, work perfectly
309
+ - CORS: Configured in auth service
310
+ - Single auth service for all Maven apps
311
+
312
+ ### Staging (*.netlify.app)
313
+ ```
314
+ Your App (preview.netlify.app)
315
+
316
+ Auth Service (auth.mavenmm.com)
317
+
318
+ Teamwork API
319
+ ```
320
+ - Cookies: Cross-site HTTPS, work with CORS
321
+ - Each preview needs to be registered in auth service
322
+ - Useful for testing before production deploy
323
+
324
+ ## Package Exports
325
+
326
+ ```typescript
327
+ // Main exports
328
+ export { useTeamworkAuth } from './hooks/useTeamworkAuth';
329
+ export { Login } from './components/Login';
330
+ export { AuthProvider } from './components/AuthProvider';
331
+
332
+ // Type exports
333
+ export type { User, TeamworkAuthConfig } from './types';
334
+ ```
335
+
336
+ ## Dependencies
337
+
338
+ ### Peer Dependencies (Required)
339
+ ```json
340
+ {
341
+ "react": ">=16.8.0",
342
+ "react-dom": ">=16.8.0",
343
+ "react-router-dom": ">=6.0.0"
344
+ }
345
+ ```
346
+
347
+ Your app must have these installed.
348
+
349
+ ### Package Dependencies
350
+ - `@teamwork/login-button`: Official Teamwork login component
351
+ - `buffer`: Browser polyfill
352
+ - `process`: Browser polyfill
353
+
354
+ ## Version Compatibility
355
+
356
+ - **v2.0.x**: Latest, with dual-token architecture and domain authentication
357
+ - **v1.x**: Legacy, deprecated
358
+
359
+ Always use the latest v2.x version for new projects.
360
+
361
+ ## When NOT to Use This Package
362
+
363
+ This package is specifically for Maven Marketing apps that:
364
+ 1. Use Teamwork for authentication
365
+ 2. Are part of the Maven ecosystem (*.mavenmm.com)
366
+ 3. Need centralized SSO across multiple apps
367
+
368
+ **Don't use this if:**
369
+ - You need a different OAuth provider
370
+ - You want standalone authentication (not centralized)
371
+ - Your app isn't part of Maven Marketing
372
+
373
+ ## Support & Troubleshooting
374
+
375
+ ### Debugging Steps
376
+
377
+ 1. **Check auth service logs:**
378
+ ```bash
379
+ # Local development
380
+ # Logs appear in terminal where you ran: netlify dev --port 9100
381
+ ```
382
+
383
+ 2. **Check browser console:**
384
+ - Look for error messages
385
+ - Check Network tab for failed requests
386
+ - Verify cookies in Application → Cookies
387
+
388
+ 3. **Verify environment variables:**
389
+ ```bash
390
+ console.log(import.meta.env.VITE_CLIENT_ID);
391
+ console.log(import.meta.env.VITE_DOMAIN_KEY);
392
+ ```
393
+
394
+ 4. **Check auth service URL:**
395
+ ```tsx
396
+ const { authServiceUrl } = useTeamworkAuth();
397
+ console.log('Using auth service:', authServiceUrl);
398
+ ```
399
+
400
+ ### Getting Help
401
+
402
+ For issues with the package:
403
+ 1. Check this CLAUDE.md file
404
+ 2. Check README.md for general usage
405
+ 3. Check auth service logs for backend errors
406
+ 4. Verify environment variables are correct
407
+ 5. Contact Maven DevOps team for domain key issues
408
+
409
+ ## Example Implementation
410
+
411
+ ```tsx
412
+ import React from 'react';
413
+ import { BrowserRouter, Routes, Route } from 'react-router-dom';
414
+ import { useTeamworkAuth, Login } from '@mavenmm/teamwork-auth';
415
+
416
+ function ProtectedApp() {
417
+ const { user, isAuthenticated, loading, logout } = useTeamworkAuth();
418
+
419
+ if (loading) {
420
+ return (
421
+ <div style={{ padding: '20px', textAlign: 'center' }}>
422
+ <h2>Loading...</h2>
423
+ <p>Checking authentication status...</p>
424
+ </div>
425
+ );
426
+ }
427
+
428
+ if (!isAuthenticated) {
429
+ return (
430
+ <div style={{ padding: '20px', textAlign: 'center' }}>
431
+ <h1>Welcome to Maven App</h1>
432
+ <p>Please sign in with your Teamwork account:</p>
433
+ <Login
434
+ clientID={import.meta.env.VITE_CLIENT_ID}
435
+ redirectURI={import.meta.env.VITE_REDIRECT_URI}
436
+ />
437
+ </div>
438
+ );
439
+ }
440
+
441
+ return (
442
+ <div>
443
+ <header>
444
+ <h1>Welcome, {user?.firstName}!</h1>
445
+ <button onClick={logout}>Logout</button>
446
+ </header>
447
+ <main>
448
+ {/* Your app content here */}
449
+ </main>
450
+ </div>
451
+ );
452
+ }
453
+
454
+ function App() {
455
+ return (
456
+ <BrowserRouter>
457
+ <Routes>
458
+ <Route path="/*" element={<ProtectedApp />} />
459
+ </Routes>
460
+ </BrowserRouter>
461
+ );
462
+ }
463
+
464
+ export default App;
465
+ ```
466
+
467
+ ## Migration from v1.x
468
+
469
+ If migrating from v1.x:
470
+
471
+ 1. **Update package:**
472
+ ```bash
473
+ npm install @mavenmm/teamwork-auth@latest
474
+ ```
475
+
476
+ 2. **Update environment variables:**
477
+ - Add `VITE_DOMAIN_KEY` (required in v2.0)
478
+
479
+ 3. **Remove manual authServiceUrl config:**
480
+ - v2.0 auto-detects environment
481
+
482
+ 4. **Update auth service:**
483
+ - Must use v2.0 auth service with domain authentication
484
+
485
+ See MIGRATION_V2.md in the auth service repo for detailed migration guide.
486
+
487
+ ---
488
+
489
+ **Last Updated:** v2.0.3
490
+ **Package:** @mavenmm/teamwork-auth
491
+ **Auth Service:** auth.mavenmm.com (v2.0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mavenmm/teamwork-auth",
3
- "version": "2.0.3",
3
+ "version": "2.0.4",
4
4
  "description": "Centralized Teamwork SSO authentication system for React applications with zero backend code required",
5
5
  "type": "module",
6
6
  "main": "dist/index.esm.js",
@@ -16,7 +16,8 @@
16
16
  "files": [
17
17
  "dist",
18
18
  "README.md",
19
- "CHANGELOG.md"
19
+ "CHANGELOG.md",
20
+ "CLAUDE.md"
20
21
  ],
21
22
  "scripts": {
22
23
  "build": "rollup -c",