@tonycodes/auth-react 1.0.1 → 1.1.1
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/dist/AuthProvider.d.ts +2 -2
- package/dist/AuthProvider.d.ts.map +1 -1
- package/dist/AuthProvider.js +113 -23
- package/dist/AuthProvider.js.map +1 -1
- package/dist/SignInForm.d.ts +5 -8
- package/dist/SignInForm.d.ts.map +1 -1
- package/dist/SignInForm.js +21 -27
- package/dist/SignInForm.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types.d.ts +17 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/useAuth.d.ts +2 -2
- package/dist/useAuth.d.ts.map +1 -1
- package/dist/useProviders.d.ts +7 -3
- package/dist/useProviders.d.ts.map +1 -1
- package/dist/useProviders.js +77 -21
- package/dist/useProviders.js.map +1 -1
- package/dist/validateConfig.d.ts +14 -0
- package/dist/validateConfig.d.ts.map +1 -0
- package/dist/validateConfig.js +71 -0
- package/dist/validateConfig.js.map +1 -0
- package/package.json +2 -25
- package/src/AuthCallback.tsx +128 -0
- package/src/AuthProvider.tsx +331 -0
- package/src/OrganizationSwitcher.tsx +75 -0
- package/src/SignInForm.tsx +202 -0
- package/src/components.tsx +40 -0
- package/src/index.ts +9 -0
- package/src/style.css +1 -0
- package/src/types.ts +66 -0
- package/src/useAuth.ts +19 -0
- package/src/useProviders.ts +136 -0
- package/src/validateConfig.ts +94 -0
- package/tailwind.config.js +7 -0
- package/tsconfig.json +18 -0
- package/LICENSE +0 -21
package/src/types.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export interface AuthConfig {
|
|
2
|
+
/** Client ID registered with auth service */
|
|
3
|
+
clientId: string;
|
|
4
|
+
/** Auth service URL. Defaults to https://auth.tony.codes */
|
|
5
|
+
authUrl?: string;
|
|
6
|
+
/** This app's base URL. Auto-discovered from server or defaults to window.location.origin */
|
|
7
|
+
appUrl?: string;
|
|
8
|
+
/**
|
|
9
|
+
* API base URL for proxied auth endpoints (callback, refresh, logout).
|
|
10
|
+
* Required if your API runs on a different subdomain than your frontend
|
|
11
|
+
* (e.g., api.myapp.test vs myapp.test).
|
|
12
|
+
* Auto-discovered from server or defaults to appUrl.
|
|
13
|
+
*/
|
|
14
|
+
apiUrl?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Whether to require an organization for the user to be considered authenticated.
|
|
17
|
+
* Defaults to true. Set to false for single-user apps without org context.
|
|
18
|
+
*/
|
|
19
|
+
requireOrg?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Resolved config with all URLs populated (after discovery) */
|
|
23
|
+
export interface ResolvedAuthConfig {
|
|
24
|
+
clientId: string;
|
|
25
|
+
authUrl: string;
|
|
26
|
+
appUrl: string;
|
|
27
|
+
apiUrl: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface AuthUser {
|
|
31
|
+
id: string;
|
|
32
|
+
email: string;
|
|
33
|
+
name: string;
|
|
34
|
+
role: string;
|
|
35
|
+
imageUrl: string | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface AuthOrganization {
|
|
39
|
+
id: string;
|
|
40
|
+
name: string;
|
|
41
|
+
slug: string;
|
|
42
|
+
imageUrl: string | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface AuthState {
|
|
46
|
+
isAuthenticated: boolean;
|
|
47
|
+
isLoading: boolean;
|
|
48
|
+
user: AuthUser | null;
|
|
49
|
+
organization: AuthOrganization | null;
|
|
50
|
+
tenant: { id: string; name: string; slug: string } | null; // legacy alias
|
|
51
|
+
isAdmin: boolean;
|
|
52
|
+
isOwner: boolean;
|
|
53
|
+
orgRole: string;
|
|
54
|
+
isSuperAdmin: boolean;
|
|
55
|
+
isPlatformAdmin: boolean;
|
|
56
|
+
accessToken: string | null;
|
|
57
|
+
getAccessToken: () => Promise<string | null>;
|
|
58
|
+
login: (provider?: string) => void;
|
|
59
|
+
logout: () => Promise<void>;
|
|
60
|
+
switchOrganization: (orgId: string) => Promise<void>;
|
|
61
|
+
organizations: AuthOrganization[];
|
|
62
|
+
isLoggingOut: boolean;
|
|
63
|
+
isLoggingIn: boolean;
|
|
64
|
+
loginError: string | null;
|
|
65
|
+
impersonating: boolean;
|
|
66
|
+
}
|
package/src/useAuth.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { useContext } from 'react';
|
|
2
|
+
import { AuthContext, AuthConfigContext } from './AuthProvider.js';
|
|
3
|
+
import type { ResolvedAuthConfig, AuthState } from './types.js';
|
|
4
|
+
|
|
5
|
+
export function useAuth(): AuthState {
|
|
6
|
+
const context = useContext(AuthContext);
|
|
7
|
+
if (!context) {
|
|
8
|
+
throw new Error('useAuth must be used within an AuthProvider');
|
|
9
|
+
}
|
|
10
|
+
return context;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function useAuthConfig(): ResolvedAuthConfig {
|
|
14
|
+
const config = useContext(AuthConfigContext);
|
|
15
|
+
if (!config) {
|
|
16
|
+
throw new Error('useAuthConfig must be used within an AuthProvider');
|
|
17
|
+
}
|
|
18
|
+
return config;
|
|
19
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
2
|
+
import { useAuthConfig } from './useAuth.js';
|
|
3
|
+
|
|
4
|
+
export type SSOProvider = 'github' | 'google' | 'apple' | 'bitbucket';
|
|
5
|
+
|
|
6
|
+
export interface ProviderInfo {
|
|
7
|
+
id: SSOProvider;
|
|
8
|
+
name: string;
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UseProvidersResult {
|
|
13
|
+
providers: ProviderInfo[];
|
|
14
|
+
isLoading: boolean;
|
|
15
|
+
error: string | null;
|
|
16
|
+
/** Force refetch, bypassing cache */
|
|
17
|
+
refresh: () => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ─── Module-level cache ──────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
interface CacheEntry {
|
|
23
|
+
providers: ProviderInfo[];
|
|
24
|
+
fetchedAt: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const CACHE_TTL = 60_000; // 60 seconds
|
|
28
|
+
const cache = new Map<string, CacheEntry>();
|
|
29
|
+
|
|
30
|
+
function getCacheKey(authUrl: string, clientId: string): string {
|
|
31
|
+
return `${authUrl}::${clientId}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function getCachedProviders(key: string): CacheEntry | null {
|
|
35
|
+
const entry = cache.get(key);
|
|
36
|
+
if (!entry) return null;
|
|
37
|
+
return entry;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isStale(entry: CacheEntry): boolean {
|
|
41
|
+
return Date.now() - entry.fetchedAt > CACHE_TTL;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function fetchProviders(authUrl: string, clientId: string): Promise<ProviderInfo[]> {
|
|
45
|
+
const url = new URL(`${authUrl}/providers`);
|
|
46
|
+
url.searchParams.set('client_id', clientId);
|
|
47
|
+
|
|
48
|
+
const res = await fetch(url.toString());
|
|
49
|
+
if (!res.ok) {
|
|
50
|
+
throw new Error('Failed to fetch providers');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const data = await res.json();
|
|
54
|
+
return data.providers || [];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ─── Hook ────────────────────────────────────────────────────────────────
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Hook to fetch available SSO providers from the auth service.
|
|
61
|
+
* Uses module-level cache with 60s TTL and stale-while-revalidate.
|
|
62
|
+
* Clears cache on window.focus for admin changes to take effect.
|
|
63
|
+
*/
|
|
64
|
+
export function useProviders(): UseProvidersResult {
|
|
65
|
+
const config = useAuthConfig();
|
|
66
|
+
const cacheKey = getCacheKey(config.authUrl, config.clientId);
|
|
67
|
+
|
|
68
|
+
// Initialize from cache if available
|
|
69
|
+
const cached = getCachedProviders(cacheKey);
|
|
70
|
+
const [providers, setProviders] = useState<ProviderInfo[]>(cached?.providers || []);
|
|
71
|
+
const [isLoading, setIsLoading] = useState(!cached);
|
|
72
|
+
const [error, setError] = useState<string | null>(null);
|
|
73
|
+
const [refreshCounter, setRefreshCounter] = useState(0);
|
|
74
|
+
|
|
75
|
+
const refresh = useCallback(() => {
|
|
76
|
+
cache.delete(cacheKey);
|
|
77
|
+
setRefreshCounter((c: number) => c + 1);
|
|
78
|
+
}, [cacheKey]);
|
|
79
|
+
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
let mounted = true;
|
|
82
|
+
|
|
83
|
+
async function doFetch(showLoading: boolean) {
|
|
84
|
+
if (showLoading) setIsLoading(true);
|
|
85
|
+
try {
|
|
86
|
+
const result = await fetchProviders(config.authUrl, config.clientId);
|
|
87
|
+
cache.set(cacheKey, { providers: result, fetchedAt: Date.now() });
|
|
88
|
+
if (mounted) {
|
|
89
|
+
setProviders(result);
|
|
90
|
+
setError(null);
|
|
91
|
+
}
|
|
92
|
+
} catch (err) {
|
|
93
|
+
if (mounted) {
|
|
94
|
+
setError(err instanceof Error ? err.message : 'Failed to fetch providers');
|
|
95
|
+
// Keep stale data if we have it
|
|
96
|
+
if (!cached) setProviders([]);
|
|
97
|
+
}
|
|
98
|
+
} finally {
|
|
99
|
+
if (mounted) setIsLoading(false);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const entry = getCachedProviders(cacheKey);
|
|
104
|
+
|
|
105
|
+
if (!entry) {
|
|
106
|
+
// No cache — fetch with loading state
|
|
107
|
+
doFetch(true);
|
|
108
|
+
} else if (isStale(entry)) {
|
|
109
|
+
// Stale cache — show cached data, refresh in background
|
|
110
|
+
setProviders(entry.providers);
|
|
111
|
+
setIsLoading(false);
|
|
112
|
+
doFetch(false);
|
|
113
|
+
} else {
|
|
114
|
+
// Fresh cache — use it directly
|
|
115
|
+
setProviders(entry.providers);
|
|
116
|
+
setIsLoading(false);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Refetch on window focus (admin changes take effect when tab refocused)
|
|
120
|
+
function handleFocus() {
|
|
121
|
+
const current = getCachedProviders(cacheKey);
|
|
122
|
+
if (!current || isStale(current)) {
|
|
123
|
+
doFetch(false);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
window.addEventListener('focus', handleFocus);
|
|
128
|
+
|
|
129
|
+
return () => {
|
|
130
|
+
mounted = false;
|
|
131
|
+
window.removeEventListener('focus', handleFocus);
|
|
132
|
+
};
|
|
133
|
+
}, [config.authUrl, config.clientId, cacheKey, refreshCounter]);
|
|
134
|
+
|
|
135
|
+
return { providers, isLoading, error, refresh };
|
|
136
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { AuthConfig } from './types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Configuration validation errors for better developer experience.
|
|
5
|
+
*/
|
|
6
|
+
export class AuthConfigError extends Error {
|
|
7
|
+
constructor(message: string) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'AuthConfigError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Validates AuthConfig and throws descriptive errors if invalid.
|
|
15
|
+
* Called at initialization time to fail fast with helpful messages.
|
|
16
|
+
* Only clientId is required — authUrl and appUrl can be auto-discovered.
|
|
17
|
+
*/
|
|
18
|
+
export function validateConfig(config: AuthConfig): void {
|
|
19
|
+
if (!config) {
|
|
20
|
+
throw new AuthConfigError(
|
|
21
|
+
'AuthProvider requires a config prop. ' +
|
|
22
|
+
'At minimum, provide { clientId: "your-app-id" }.',
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Required field
|
|
27
|
+
if (!config.clientId) {
|
|
28
|
+
throw new AuthConfigError(
|
|
29
|
+
'Missing required config: clientId. ' +
|
|
30
|
+
'This is the client ID registered with the auth service.',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// URL format validation (only if provided)
|
|
35
|
+
if (config.authUrl) {
|
|
36
|
+
try {
|
|
37
|
+
new URL(config.authUrl);
|
|
38
|
+
} catch {
|
|
39
|
+
throw new AuthConfigError(
|
|
40
|
+
`Invalid authUrl: "${config.authUrl}" is not a valid URL. ` +
|
|
41
|
+
'It should include the protocol (e.g., "https://auth.tony.codes").',
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (config.appUrl) {
|
|
47
|
+
try {
|
|
48
|
+
new URL(config.appUrl);
|
|
49
|
+
} catch {
|
|
50
|
+
throw new AuthConfigError(
|
|
51
|
+
`Invalid appUrl: "${config.appUrl}" is not a valid URL. ` +
|
|
52
|
+
'It should include the protocol (e.g., "https://myapp.tony.codes").',
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (config.apiUrl) {
|
|
58
|
+
try {
|
|
59
|
+
new URL(config.apiUrl);
|
|
60
|
+
} catch {
|
|
61
|
+
throw new AuthConfigError(
|
|
62
|
+
`Invalid apiUrl: "${config.apiUrl}" is not a valid URL. ` +
|
|
63
|
+
'It should include the protocol (e.g., "https://api.myapp.tony.codes").',
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Common misconfiguration warnings (logged but don't throw)
|
|
69
|
+
if (typeof window !== 'undefined') {
|
|
70
|
+
const isProduction = !window.location.hostname.includes('test') &&
|
|
71
|
+
!window.location.hostname.includes('localhost');
|
|
72
|
+
|
|
73
|
+
if (isProduction && config.authUrl?.includes('localhost')) {
|
|
74
|
+
console.warn(
|
|
75
|
+
'[auth-react] Warning: authUrl contains "localhost" but app appears to be in production. ' +
|
|
76
|
+
'Make sure to update authUrl for production.',
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (config.authUrl?.endsWith('/')) {
|
|
81
|
+
console.warn(
|
|
82
|
+
'[auth-react] Warning: authUrl has a trailing slash. ' +
|
|
83
|
+
'This may cause double slashes in URLs.',
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (config.appUrl?.endsWith('/')) {
|
|
88
|
+
console.warn(
|
|
89
|
+
'[auth-react] Warning: appUrl has a trailing slash. ' +
|
|
90
|
+
'This may cause double slashes in URLs.',
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2020",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"jsx": "react-jsx",
|
|
7
|
+
"strict": true,
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"outDir": "dist",
|
|
10
|
+
"rootDir": "src",
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"declaration": true,
|
|
13
|
+
"declarationMap": true,
|
|
14
|
+
"sourceMap": true
|
|
15
|
+
},
|
|
16
|
+
"include": ["src"],
|
|
17
|
+
"exclude": ["node_modules", "dist"]
|
|
18
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Tony
|
|
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.
|