@apptimate/core-lib 1.0.0 → 1.2.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.
@@ -1,161 +1,192 @@
1
- import { IApiResponse } from "../common/interfaces/ICommon";
2
- import Cookies from 'js-cookie';
3
- import { cookie } from '../constants/storageKeys';
4
- import { decrypt, replacePlaceholders } from './commonService';
5
-
6
- /**
7
- * Handles 401 Unauthorized responses globally.
8
- * Clears the auth cookie and localStorage, then redirects to the login page.
9
- */
10
- export function handleUnauthorized(): void {
11
- // Clear auth cookie explicitly to avoid clearing cookies from other apps on localhost
12
- const cookieName = replacePlaceholders(
13
- cookie.access_token.encrypted ? cookie.access_token.secretName : cookie.access_token.name,
14
- {}
15
- );
16
- Cookies.remove(cookieName, { path: '/' });
17
-
18
- // Clear localStorage
19
- if (typeof window !== 'undefined') {
20
- localStorage.clear();
21
- window.location.href = '/auth/login';
22
- }
23
- }
24
-
25
-
26
- export interface RequestOptions {
27
- url: string;
28
- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
29
- data?: any;
30
- params?: Record<string, any>;
31
- headers?: Record<string, string>;
32
- signal?: AbortSignal;
33
- }
34
-
35
- export interface ClientResponse<T = any> {
36
- ok: boolean;
37
- status: number;
38
- responseData: IApiResponse<T>;
39
- }
40
-
41
- export async function sendRequest<T = any>({ url, method, data, params, headers, signal }: RequestOptions): Promise<ClientResponse<T>> {
42
- const defaultHeaders: Record<string, string> = {
43
- 'Accept': 'application/json',
44
- };
45
-
46
- // Serialize params into query string
47
- let finalUrl = url;
48
- if (params) {
49
- const queryParams = new URLSearchParams();
50
- Object.entries(params).forEach(([key, value]) => {
51
- if (value !== undefined && value !== null && value !== '') {
52
- queryParams.append(key, String(value));
53
- }
54
- });
55
- const queryString = queryParams.toString();
56
- if (queryString) {
57
- finalUrl += (url.includes('?') ? '&' : '?') + queryString;
58
- }
59
- }
60
-
61
- // Automatically add Authorization header on the client side
62
- if (typeof window !== 'undefined') {
63
- const name = replacePlaceholders(
64
- cookie.access_token.encrypted ? cookie.access_token.secretName : cookie.access_token.name,
65
- {}
66
- );
67
- const tokenValue = Cookies.get(name);
68
-
69
- if (tokenValue) {
70
- try {
71
- const token = cookie.access_token.encrypted ? decrypt(tokenValue) : tokenValue;
72
- if (token) {
73
- defaultHeaders['Authorization'] = `Bearer ${token}`;
74
- }
75
- } catch (error) {
76
- console.error("Failed to process auth token:", error);
77
- }
78
- }
79
- }
80
-
81
- if (data && !(data instanceof FormData)) {
82
- defaultHeaders['Content-Type'] = 'application/json';
83
- }
84
-
85
- try {
86
- const response = await fetch(finalUrl, {
87
- method,
88
- headers: { ...defaultHeaders, ...headers },
89
- body: data instanceof FormData ? data : (data ? JSON.stringify(data) : undefined),
90
- signal,
91
- });
92
-
93
- // Handle 401 Unauthorized globally clear auth and redirect to login
94
- const isAuthEndpoint = finalUrl.includes('/auth/login') || finalUrl.includes('/auth/register');
95
-
96
- if (response.status === 401 && typeof window !== 'undefined' && !isAuthEndpoint) {
97
- handleUnauthorized();
98
- return {
99
- ok: false,
100
- status: 401,
101
- responseData: {
102
- is_success: false,
103
- message: 'Unauthenticated.',
104
- result: null,
105
- system_code: 'unauthenticated'
106
- } as IApiResponse<T>,
107
- };
108
- }
109
-
110
- let responseData: any;
111
- const contentType = response.headers.get('content-type');
112
-
113
- if (contentType && contentType.includes('application/json')) {
114
- responseData = await response.json();
115
- } else {
116
- responseData = {
117
- is_success: response.ok,
118
- message: response.statusText,
119
- result: null,
120
- system_code: ''
121
- };
122
- }
123
-
124
- // Handle inactive userforce logout and redirect to login
125
- // Skip for auth endpoints so the login form can display the error
126
- if (responseData?.system_code === 'user_inactive' && typeof window !== 'undefined' && !isAuthEndpoint) {
127
- handleUnauthorized();
128
- return {
129
- ok: false,
130
- status: 403,
131
- responseData: {
132
- is_success: false,
133
- message: responseData.message || 'Your account has been deactivated.',
134
- result: null,
135
- system_code: 'user_inactive'
136
- } as IApiResponse<T>,
137
- };
138
- }
139
-
140
- return {
141
- ok: response.ok,
142
- status: response.status,
143
- responseData: responseData as IApiResponse<T>,
144
- };
145
- } catch (error: any) {
146
- if (error.name === 'AbortError') {
147
- throw error; // Rethrow to be caught by specific timeout handling
148
- }
149
-
150
- return {
151
- ok: false,
152
- status: 0,
153
- responseData: {
154
- is_success: false,
155
- message: error.message || 'Network error',
156
- result: null,
157
- system_code: 'network_failure'
158
- },
159
- };
160
- }
161
- }
1
+ import { IApiResponse } from "../common/interfaces/ICommon";
2
+
3
+ /**
4
+ * Handles 401 Unauthorized responses globally.
5
+ * Clears the server-managed session and app-owned local state, then redirects
6
+ * to the login page.
7
+ */
8
+ export function handleUnauthorized(): void {
9
+ // Best-effort server-side cookie clear for HttpOnly auth cookies.
10
+ if (typeof window !== 'undefined') {
11
+ fetch('/api/session/logout', {
12
+ method: 'POST',
13
+ credentials: 'same-origin',
14
+ keepalive: true,
15
+ }).catch(() => {
16
+ // Ignore logout cleanup failures and proceed with client-side reset.
17
+ });
18
+ }
19
+
20
+ // Clear only app-owned localStorage keys instead of wiping the entire origin
21
+ if (typeof window !== 'undefined') {
22
+ const appKeys = ['selected_organization'];
23
+ // Also clear any key from our storageKeys registry
24
+ try {
25
+ const allKeys = Object.keys(localStorage);
26
+ allKeys.forEach(key => {
27
+ if (appKeys.includes(key) || key.startsWith('apptimate_') || key.startsWith('app_')) {
28
+ localStorage.removeItem(key);
29
+ }
30
+ });
31
+ } catch {
32
+ // Silently ignore storage access errors
33
+ }
34
+ window.location.href = '/auth/login';
35
+ }
36
+ }
37
+
38
+
39
+ export interface RequestOptions {
40
+ url: string;
41
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
42
+ data?: any;
43
+ params?: Record<string, any>;
44
+ headers?: Record<string, string>;
45
+ signal?: AbortSignal;
46
+ }
47
+
48
+ export interface ClientResponse<T = any> {
49
+ ok: boolean;
50
+ status: number;
51
+ responseData: IApiResponse<T>;
52
+ }
53
+
54
+ function buildBrowserProxyUrl(rawUrl: string): string {
55
+ if (typeof window === 'undefined') {
56
+ return rawUrl;
57
+ }
58
+
59
+ try {
60
+ const parsedUrl = new URL(rawUrl, window.location.origin);
61
+
62
+ if (parsedUrl.origin === window.location.origin) {
63
+ return parsedUrl.toString();
64
+ }
65
+
66
+ const proxyPath = parsedUrl.pathname.replace(/^\/+/, '');
67
+ return `/api/proxy/${proxyPath}${parsedUrl.search}`;
68
+ } catch {
69
+ return rawUrl;
70
+ }
71
+ }
72
+
73
+ export async function sendRequest<T = any>({ url, method, data, params, headers, signal }: RequestOptions): Promise<ClientResponse<T>> {
74
+ const defaultHeaders: Record<string, string> = {
75
+ 'Accept': 'application/json',
76
+ };
77
+
78
+ // Serialize params into query string
79
+ let finalUrl = url;
80
+ if (params) {
81
+ const queryParams = new URLSearchParams();
82
+ Object.entries(params).forEach(([key, value]) => {
83
+ if (value !== undefined && value !== null && value !== '') {
84
+ queryParams.append(key, String(value));
85
+ }
86
+ });
87
+ const queryString = queryParams.toString();
88
+ if (queryString) {
89
+ finalUrl += (url.includes('?') ? '&' : '?') + queryString;
90
+ }
91
+ }
92
+
93
+ // Client-side requests are routed through a same-origin proxy so the
94
+ // browser never needs direct access to the bearer token.
95
+ if (typeof window !== 'undefined') {
96
+ finalUrl = buildBrowserProxyUrl(finalUrl);
97
+
98
+ // Automatically inject selected organization ID into every request
99
+ try {
100
+ const orgRaw = localStorage.getItem('selected_organization');
101
+ if (orgRaw) {
102
+ const org = JSON.parse(orgRaw);
103
+ if (org?.id) {
104
+ defaultHeaders['X-Organization-Id'] = String(org.id);
105
+ }
106
+ }
107
+ } catch {
108
+ // silently ignore parse errors
109
+ }
110
+ }
111
+
112
+ if (data && !(data instanceof FormData)) {
113
+ defaultHeaders['Content-Type'] = 'application/json';
114
+ }
115
+
116
+ try {
117
+ const response = await fetch(finalUrl, {
118
+ method,
119
+ headers: { ...defaultHeaders, ...headers },
120
+ body: data instanceof FormData ? data : (data ? JSON.stringify(data) : undefined),
121
+ signal,
122
+ });
123
+
124
+ // Handle 401 Unauthorized globally clear auth and redirect to login
125
+ const isAuthEndpoint = finalUrl.includes('/auth/login') || finalUrl.includes('/auth/register') || finalUrl.includes('/auth/me');
126
+
127
+ if (response.status === 401 && typeof window !== 'undefined' && !isAuthEndpoint) {
128
+ handleUnauthorized();
129
+ return {
130
+ ok: false,
131
+ status: 401,
132
+ responseData: {
133
+ is_success: false,
134
+ message: 'Unauthenticated.',
135
+ result: null,
136
+ system_code: 'unauthenticated'
137
+ } as IApiResponse<T>,
138
+ };
139
+ }
140
+
141
+ let responseData: any;
142
+ const contentType = response.headers.get('content-type');
143
+
144
+ if (contentType && contentType.includes('application/json')) {
145
+ responseData = await response.json();
146
+ } else {
147
+ responseData = {
148
+ is_success: response.ok,
149
+ message: response.statusText,
150
+ result: null,
151
+ system_code: ''
152
+ };
153
+ }
154
+
155
+ // Handle inactive user — force logout and redirect to login
156
+ // Skip for auth endpoints so the login form can display the error
157
+ if (responseData?.system_code === 'user_inactive' && typeof window !== 'undefined' && !isAuthEndpoint) {
158
+ handleUnauthorized();
159
+ return {
160
+ ok: false,
161
+ status: 403,
162
+ responseData: {
163
+ is_success: false,
164
+ message: responseData.message || 'Your account has been deactivated.',
165
+ result: null,
166
+ system_code: 'user_inactive'
167
+ } as IApiResponse<T>,
168
+ };
169
+ }
170
+
171
+ return {
172
+ ok: response.ok,
173
+ status: response.status,
174
+ responseData: responseData as IApiResponse<T>,
175
+ };
176
+ } catch (error: any) {
177
+ if (error.name === 'AbortError') {
178
+ throw error; // Rethrow to be caught by specific timeout handling
179
+ }
180
+
181
+ return {
182
+ ok: false,
183
+ status: 0,
184
+ responseData: {
185
+ is_success: false,
186
+ message: error.message || 'Network error',
187
+ result: null,
188
+ system_code: 'network_failure'
189
+ },
190
+ };
191
+ }
192
+ }
@@ -1,49 +1,59 @@
1
- 'use client';
2
-
3
- import { IStorageOptions } from '../constants/storageKeys';
4
- import { decrypt, encrypt, replacePlaceholders } from './commonService';
5
-
6
- export function getLocalStorage<T = any>(storageKey: IStorageOptions, options?: { replacements?: Record<string, string | number> }): T | null {
7
- if (typeof window === 'undefined') return null;
8
-
9
- const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
10
- const value = localStorage.getItem(name);
11
-
12
- if (!value) return null;
13
-
14
- if (storageKey.encrypted) {
15
- return decrypt(value) as T;
16
- }
17
-
18
- try {
19
- return JSON.parse(value) as T;
20
- } catch {
21
- return value as unknown as T;
22
- }
23
- }
24
-
25
- export function setLocalStorage(storageKey: IStorageOptions, value: any, options?: { replacements?: Record<string, string | number> }): void {
26
- if (typeof window === 'undefined') return;
27
-
28
- const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
29
-
30
- let finalValue = typeof value === 'string' ? value : JSON.stringify(value);
31
- if (storageKey.encrypted) {
32
- finalValue = encrypt(value);
33
- }
34
-
35
- localStorage.setItem(name, finalValue);
36
- }
37
-
38
- export function clearLocalStorage(storageKey: IStorageOptions, options?: { replacements?: Record<string, string | number> }): void {
39
- if (typeof window === 'undefined') return;
40
-
41
- const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
42
- localStorage.removeItem(name);
43
- }
44
-
45
- export function clearAllLocalStorage(): void {
46
- if (typeof window !== 'undefined') {
47
- localStorage.clear();
48
- }
49
- }
1
+ 'use client';
2
+
3
+ import { IStorageOptions } from '../constants/storageKeys';
4
+ import { decrypt, encrypt, replacePlaceholders } from './commonService';
5
+
6
+ export function getLocalStorage<T = any>(storageKey: IStorageOptions, options?: { replacements?: Record<string, string | number> }): T | null {
7
+ if (typeof window === 'undefined') return null;
8
+
9
+ const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
10
+ const value = localStorage.getItem(name);
11
+
12
+ if (!value) return null;
13
+
14
+ if (storageKey.encrypted) {
15
+ return decrypt(value) as T;
16
+ }
17
+
18
+ try {
19
+ return JSON.parse(value) as T;
20
+ } catch {
21
+ return value as unknown as T;
22
+ }
23
+ }
24
+
25
+ export function setLocalStorage(storageKey: IStorageOptions, value: any, options?: { replacements?: Record<string, string | number> }): void {
26
+ if (typeof window === 'undefined') return;
27
+
28
+ const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
29
+
30
+ let finalValue = typeof value === 'string' ? value : JSON.stringify(value);
31
+ if (storageKey.encrypted) {
32
+ finalValue = encrypt(value);
33
+ }
34
+
35
+ localStorage.setItem(name, finalValue);
36
+ }
37
+
38
+ export function clearLocalStorage(storageKey: IStorageOptions, options?: { replacements?: Record<string, string | number> }): void {
39
+ if (typeof window === 'undefined') return;
40
+
41
+ const name = replacePlaceholders(storageKey.encrypted ? storageKey.secretName : storageKey.name, options?.replacements || {});
42
+ localStorage.removeItem(name);
43
+ }
44
+
45
+ export function clearAllLocalStorage(): void {
46
+ if (typeof window !== 'undefined') {
47
+ const appKeys = ['selected_organization'];
48
+ try {
49
+ const allKeys = Object.keys(localStorage);
50
+ allKeys.forEach(key => {
51
+ if (appKeys.includes(key) || key.startsWith('apptimate_') || key.startsWith('app_')) {
52
+ localStorage.removeItem(key);
53
+ }
54
+ });
55
+ } catch {
56
+ // Silently ignore storage access errors
57
+ }
58
+ }
59
+ }