@microcosmmoney/auth-core 1.1.1 → 1.2.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/client.d.ts CHANGED
@@ -16,6 +16,7 @@ export declare class MicrocosmAuthClient {
16
16
  getAccessToken(): Promise<string | null>;
17
17
  getApiClient(): ApiClient;
18
18
  onAuthStateChange(callback: (user: User | null) => void): () => void;
19
+ private handleTokenExpired;
19
20
  private fetchUserProfile;
20
21
  private mapProfileToUser;
21
22
  private resolveRedirectUri;
package/dist/client.js CHANGED
@@ -23,6 +23,7 @@ class MicrocosmAuthClient {
23
23
  this.apiClient = new api_client_1.ApiClient(this.tokenManager);
24
24
  if (this.config.autoRefresh && this.tokenManager.hasValidToken()) {
25
25
  this.tokenManager.scheduleRefresh();
26
+ this.tokenManager.startMonitor(() => this.handleTokenExpired());
26
27
  }
27
28
  this.log('Initialized', { clientId: this.config.clientId });
28
29
  }
@@ -62,7 +63,8 @@ class MicrocosmAuthClient {
62
63
  throw new Error('Missing authorization code');
63
64
  }
64
65
  const savedState = this.storage.get(storage_1.STORAGE_KEYS.OAUTH_STATE);
65
- if (state && savedState && state !== savedState) {
66
+ if (!state || !savedState || state !== savedState) {
67
+ this.storage.remove(storage_1.STORAGE_KEYS.OAUTH_STATE);
66
68
  throw new Error('Invalid state parameter (possible CSRF)');
67
69
  }
68
70
  this.storage.remove(storage_1.STORAGE_KEYS.OAUTH_STATE);
@@ -77,12 +79,17 @@ class MicrocosmAuthClient {
77
79
  throw new Error(errorData.error_description || errorData.error || 'Token exchange failed');
78
80
  }
79
81
  const tokenData = await tokenResponse.json();
82
+ const MAX_EXPIRY = 86400;
83
+ const expiresIn = Math.min(Math.max(Number(tokenData.expires_in) || 3600, 60), MAX_EXPIRY);
80
84
  const tokens = {
81
85
  accessToken: tokenData.access_token,
82
86
  refreshToken: tokenData.refresh_token,
83
- expiresAt: Date.now() + (tokenData.expires_in || 3600) * 1000,
87
+ expiresAt: Date.now() + expiresIn * 1000,
84
88
  };
85
89
  this.tokenManager.setTokens(tokens);
90
+ if (this.config.autoRefresh) {
91
+ this.tokenManager.startMonitor(() => this.handleTokenExpired());
92
+ }
86
93
  const user = await this.fetchUserProfile(tokens.accessToken);
87
94
  this.storage.set(storage_1.STORAGE_KEYS.USER, JSON.stringify(user));
88
95
  this.notifyListeners(user);
@@ -90,6 +97,7 @@ class MicrocosmAuthClient {
90
97
  return user;
91
98
  }
92
99
  async logout() {
100
+ this.tokenManager.stopMonitor();
93
101
  this.tokenManager.clear();
94
102
  this.storage.remove(storage_1.STORAGE_KEYS.USER);
95
103
  this.notifyListeners(null);
@@ -123,6 +131,12 @@ class MicrocosmAuthClient {
123
131
  this.listeners.add(callback);
124
132
  return () => this.listeners.delete(callback);
125
133
  }
134
+ handleTokenExpired() {
135
+ this.tokenManager.stopMonitor();
136
+ this.storage.remove(storage_1.STORAGE_KEYS.USER);
137
+ this.notifyListeners(null);
138
+ this.log('Token expired, session cleared');
139
+ }
126
140
  async fetchUserProfile(accessToken) {
127
141
  const response = await fetch(this.config.profileUri, {
128
142
  headers: { Authorization: `Bearer ${accessToken}` },
@@ -5,14 +5,19 @@ export declare class TokenManager {
5
5
  private storage;
6
6
  private refreshTimer;
7
7
  private refreshPromise;
8
+ private monitorInterval;
9
+ private onTokenExpired;
8
10
  constructor(config: ResolvedConfig, storage: Storage);
9
11
  setTokens(data: TokenData): void;
10
12
  getAccessToken(): Promise<string | null>;
11
13
  getRawAccessToken(): string | null;
12
14
  hasValidToken(): boolean;
13
15
  isExpired(): boolean;
16
+ startMonitor(onExpired: () => void): void;
17
+ stopMonitor(): void;
14
18
  clear(): void;
15
19
  scheduleRefresh(): void;
20
+ private handleVisibilityChange;
16
21
  private refreshToken;
17
22
  private doRefresh;
18
23
  }
@@ -2,10 +2,25 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TokenManager = void 0;
4
4
  const storage_1 = require("./storage");
5
+ const TOKEN_CHECK_INTERVAL_MS = 30000;
5
6
  class TokenManager {
6
7
  constructor(config, storage) {
7
8
  this.refreshTimer = null;
8
9
  this.refreshPromise = null;
10
+ this.monitorInterval = null;
11
+ this.onTokenExpired = null;
12
+ this.handleVisibilityChange = async () => {
13
+ if (document.visibilityState !== 'visible')
14
+ return;
15
+ if (!this.storage.get(storage_1.STORAGE_KEYS.REFRESH_TOKEN))
16
+ return;
17
+ if (!this.isExpired())
18
+ return;
19
+ const newToken = await this.getAccessToken();
20
+ if (!newToken) {
21
+ this.onTokenExpired?.();
22
+ }
23
+ };
9
24
  this.config = config;
10
25
  this.storage = storage;
11
26
  }
@@ -38,6 +53,34 @@ class TokenManager {
38
53
  const expiresAt = parseInt(this.storage.get(storage_1.STORAGE_KEYS.EXPIRES_AT) || '0', 10);
39
54
  return Date.now() >= expiresAt;
40
55
  }
56
+ startMonitor(onExpired) {
57
+ this.onTokenExpired = onExpired;
58
+ if (this.monitorInterval)
59
+ return;
60
+ this.monitorInterval = setInterval(async () => {
61
+ if (!this.storage.get(storage_1.STORAGE_KEYS.REFRESH_TOKEN))
62
+ return;
63
+ if (!this.isExpired())
64
+ return;
65
+ const newToken = await this.getAccessToken();
66
+ if (!newToken) {
67
+ this.onTokenExpired?.();
68
+ }
69
+ }, TOKEN_CHECK_INTERVAL_MS);
70
+ if (typeof document !== 'undefined') {
71
+ document.addEventListener('visibilitychange', this.handleVisibilityChange);
72
+ }
73
+ }
74
+ stopMonitor() {
75
+ if (this.monitorInterval) {
76
+ clearInterval(this.monitorInterval);
77
+ this.monitorInterval = null;
78
+ }
79
+ if (typeof document !== 'undefined') {
80
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
81
+ }
82
+ this.onTokenExpired = null;
83
+ }
41
84
  clear() {
42
85
  if (this.refreshTimer) {
43
86
  clearTimeout(this.refreshTimer);
@@ -85,22 +128,27 @@ class TokenManager {
85
128
  });
86
129
  if (!response.ok) {
87
130
  this.clear();
131
+ this.onTokenExpired?.();
88
132
  return null;
89
133
  }
90
134
  const contentType = response.headers.get('content-type');
91
135
  if (!contentType?.includes('application/json')) {
92
136
  this.clear();
137
+ this.onTokenExpired?.();
93
138
  return null;
94
139
  }
95
140
  const data = await response.json();
96
141
  if (!data.access_token) {
97
142
  this.clear();
143
+ this.onTokenExpired?.();
98
144
  return null;
99
145
  }
146
+ const MAX_EXPIRY = 86400;
147
+ const expiresIn = Math.min(Math.max(Number(data.expires_in) || 3600, 60), MAX_EXPIRY);
100
148
  this.setTokens({
101
149
  accessToken: data.access_token,
102
150
  refreshToken: data.refresh_token || refreshToken,
103
- expiresAt: Date.now() + (data.expires_in || 3600) * 1000,
151
+ expiresAt: Date.now() + expiresIn * 1000,
104
152
  });
105
153
  return data.access_token;
106
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microcosmmoney/auth-core",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "Microcosm OAuth 2.0 authentication core library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",