@vaadin/hilla-frontend 24.7.0-alpha9 → 24.8.0-alpha1
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/Authentication.d.ts +53 -54
- package/Authentication.js +161 -145
- package/Authentication.js.map +1 -7
- package/Connect.d.ts +150 -146
- package/Connect.js +228 -177
- package/Connect.js.map +1 -7
- package/CookieManager.d.ts +2 -2
- package/CookieManager.js +5 -12
- package/CookieManager.js.map +1 -7
- package/CsrfUtils.d.ts +1 -13
- package/CsrfUtils.js +51 -51
- package/CsrfUtils.js.map +1 -7
- package/EndpointErrors.d.ts +73 -74
- package/EndpointErrors.js +108 -101
- package/EndpointErrors.js.map +1 -7
- package/FluxConnection.d.ts +51 -52
- package/FluxConnection.js +278 -259
- package/FluxConnection.js.map +1 -7
- package/FluxMessages.d.ts +14 -15
- package/FluxMessages.js +3 -6
- package/FluxMessages.js.map +1 -7
- package/index.d.ts +4 -5
- package/index.js +9 -15
- package/index.js.map +1 -7
- package/package.json +8 -28
- package/types.d.ts +17 -0
- package/Authentication.d.ts.map +0 -1
- package/Connect.d.ts.map +0 -1
- package/CookieManager.d.ts.map +0 -1
- package/CsrfUtils.d.ts.map +0 -1
- package/EndpointErrors.d.ts.map +0 -1
- package/FluxConnection.d.ts.map +0 -1
- package/FluxMessages.d.ts.map +0 -1
- package/index.d.ts.map +0 -1
package/Authentication.d.ts
CHANGED
|
@@ -1,71 +1,70 @@
|
|
|
1
|
-
import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from
|
|
1
|
+
import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from "./Connect.js";
|
|
2
2
|
export interface LoginResult {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
error: boolean;
|
|
4
|
+
token?: string;
|
|
5
|
+
errorTitle?: string;
|
|
6
|
+
errorMessage?: string;
|
|
7
|
+
redirectUrl?: string;
|
|
8
|
+
defaultUrl?: string;
|
|
9
9
|
}
|
|
10
10
|
export type SuccessCallback = () => Promise<void> | void;
|
|
11
11
|
export type NavigateFunction = (path: string) => void;
|
|
12
12
|
export interface LoginOptions {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
13
|
+
/**
|
|
14
|
+
* The URL for login request, defaults to `/login`.
|
|
15
|
+
*/
|
|
16
|
+
loginProcessingUrl?: URL | string;
|
|
17
|
+
/**
|
|
18
|
+
* The success callback.
|
|
19
|
+
*/
|
|
20
|
+
onSuccess?: SuccessCallback;
|
|
21
|
+
/**
|
|
22
|
+
* The navigation callback, called after successful login. The default
|
|
23
|
+
* reloads the page.
|
|
24
|
+
*/
|
|
25
|
+
navigate?: NavigateFunction;
|
|
26
26
|
}
|
|
27
27
|
export interface LogoutOptions {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
28
|
+
/**
|
|
29
|
+
* The URL for logout request, defaults to `/logout`.
|
|
30
|
+
*/
|
|
31
|
+
logoutUrl?: URL | string;
|
|
32
|
+
/**
|
|
33
|
+
* The success callback.
|
|
34
|
+
*/
|
|
35
|
+
onSuccess?: SuccessCallback;
|
|
36
|
+
/**
|
|
37
|
+
* The navigation callback, called after successful logout. The default
|
|
38
|
+
* reloads the page.
|
|
39
|
+
*/
|
|
40
|
+
navigate?: NavigateFunction;
|
|
41
41
|
}
|
|
42
42
|
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
43
|
+
* A helper method for Spring Security based form login.
|
|
44
|
+
* @param username - username
|
|
45
|
+
* @param password - password
|
|
46
|
+
* @param options - defines additional options, e.g, the loginProcessingUrl etc.
|
|
47
|
+
*/
|
|
48
48
|
export declare function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult>;
|
|
49
49
|
/**
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
* A helper method for Spring Security based form logout
|
|
51
|
+
* @param options - defines additional options, e.g, the logoutUrl.
|
|
52
|
+
*/
|
|
53
53
|
export declare function logout(options?: LogoutOptions): Promise<void>;
|
|
54
54
|
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
55
|
+
* It defines what to do when it detects a session is invalid. E.g.,
|
|
56
|
+
* show a login view.
|
|
57
|
+
* It takes an <code>EndpointCallContinue</code> parameter, which can be
|
|
58
|
+
* used to continue the endpoint call.
|
|
59
|
+
*/
|
|
60
60
|
export type OnInvalidSessionCallback = () => Promise<LoginResult>;
|
|
61
61
|
/**
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
* A helper class for handling invalid sessions during an endpoint call.
|
|
63
|
+
* E.g., you can use this to show user a login page when the session has
|
|
64
|
+
* expired.
|
|
65
|
+
*/
|
|
66
66
|
export declare class InvalidSessionMiddleware implements MiddlewareClass {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
private readonly onInvalidSessionCallback;
|
|
68
|
+
constructor(onInvalidSessionCallback: OnInvalidSessionCallback);
|
|
69
|
+
invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response>;
|
|
70
70
|
}
|
|
71
|
-
//# sourceMappingURL=Authentication.d.ts.map
|
package/Authentication.js
CHANGED
|
@@ -2,166 +2,182 @@ import CookieManager from "./CookieManager.js";
|
|
|
2
2
|
import { getSpringCsrfInfo, getSpringCsrfTokenHeadersForAuthRequest, VAADIN_CSRF_HEADER } from "./CsrfUtils.js";
|
|
3
3
|
const JWT_COOKIE_NAME = "jwt.headerAndPayload";
|
|
4
4
|
function getSpringCsrfTokenFromResponseBody(body) {
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
const doc = new DOMParser().parseFromString(body, "text/html");
|
|
6
|
+
return getSpringCsrfInfo(doc);
|
|
7
7
|
}
|
|
8
8
|
function clearSpringCsrfMetaTags() {
|
|
9
|
-
|
|
10
|
-
(el) => el.remove()
|
|
11
|
-
);
|
|
9
|
+
Array.from(document.head.querySelectorAll("meta[name=\"_csrf\"], meta[name=\"_csrf_header\"]")).forEach((el) => el.remove());
|
|
12
10
|
}
|
|
13
11
|
function updateSpringCsrfMetaTags(springCsrfInfo) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
12
|
+
clearSpringCsrfMetaTags();
|
|
13
|
+
const headerNameMeta = document.createElement("meta");
|
|
14
|
+
headerNameMeta.name = "_csrf_header";
|
|
15
|
+
headerNameMeta.content = springCsrfInfo._csrf_header;
|
|
16
|
+
document.head.appendChild(headerNameMeta);
|
|
17
|
+
const tokenMeta = document.createElement("meta");
|
|
18
|
+
tokenMeta.name = "_csrf";
|
|
19
|
+
tokenMeta.content = springCsrfInfo._csrf;
|
|
20
|
+
document.head.appendChild(tokenMeta);
|
|
23
21
|
}
|
|
24
22
|
const getVaadinCsrfTokenFromResponseBody = (body) => {
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
const match = /window\.Vaadin = \{TypeScript: \{"csrfToken":"([0-9a-zA-Z\\-]{36})"\}\};/iu.exec(body);
|
|
24
|
+
return match ? match[1] : undefined;
|
|
27
25
|
};
|
|
28
26
|
async function updateCsrfTokensBasedOnResponse(response) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
27
|
+
const responseText = await response.text();
|
|
28
|
+
const token = getVaadinCsrfTokenFromResponseBody(responseText);
|
|
29
|
+
const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);
|
|
30
|
+
updateSpringCsrfMetaTags(springCsrfTokenInfo);
|
|
31
|
+
return token;
|
|
34
32
|
}
|
|
35
33
|
async function doLogout(logoutUrl, headers) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
34
|
+
const response = await fetch(logoutUrl, {
|
|
35
|
+
headers,
|
|
36
|
+
method: "POST"
|
|
37
|
+
});
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
throw new Error(`failed to logout with response ${response.status}`);
|
|
40
|
+
}
|
|
41
|
+
await updateCsrfTokensBasedOnResponse(response);
|
|
42
|
+
return response;
|
|
42
43
|
}
|
|
43
44
|
function normalizePath(url) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
45
|
+
const effectiveBaseURL = new URL(".", document.baseURI);
|
|
46
|
+
const effectiveBaseURI = effectiveBaseURL.toString();
|
|
47
|
+
let normalized = url;
|
|
48
|
+
if (normalized.startsWith(effectiveBaseURL.pathname)) {
|
|
49
|
+
return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;
|
|
50
|
+
}
|
|
51
|
+
normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;
|
|
52
|
+
return normalized;
|
|
52
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Navigates to the provided path using page reload.
|
|
56
|
+
*
|
|
57
|
+
* @param to - navigation target path
|
|
58
|
+
*/
|
|
53
59
|
function navigateWithPageReload(to) {
|
|
54
|
-
|
|
55
|
-
|
|
60
|
+
const url = to.startsWith("/") ? new URL(`.${to}`, document.baseURI) : to;
|
|
61
|
+
window.location.replace(url);
|
|
56
62
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
63
|
+
/**
|
|
64
|
+
* A helper method for Spring Security based form login.
|
|
65
|
+
* @param username - username
|
|
66
|
+
* @param password - password
|
|
67
|
+
* @param options - defines additional options, e.g, the loginProcessingUrl etc.
|
|
68
|
+
*/
|
|
69
|
+
export async function login(username, password, options) {
|
|
70
|
+
try {
|
|
71
|
+
const data = new FormData();
|
|
72
|
+
data.append("username", username);
|
|
73
|
+
data.append("password", password);
|
|
74
|
+
const loginProcessingUrl = options?.loginProcessingUrl ?? "login";
|
|
75
|
+
const headers = getSpringCsrfTokenHeadersForAuthRequest(document);
|
|
76
|
+
headers.source = "typescript";
|
|
77
|
+
const response = await fetch(loginProcessingUrl, {
|
|
78
|
+
body: data,
|
|
79
|
+
headers,
|
|
80
|
+
method: "POST"
|
|
81
|
+
});
|
|
82
|
+
const result = response.headers.get("Result");
|
|
83
|
+
const savedUrl = response.headers.get("Saved-url") ?? undefined;
|
|
84
|
+
const defaultUrl = response.headers.get("Default-url") ?? undefined;
|
|
85
|
+
const loginSuccessful = response.ok && result === "success";
|
|
86
|
+
if (loginSuccessful) {
|
|
87
|
+
const vaadinCsrfToken = response.headers.get("Vaadin-CSRF") ?? undefined;
|
|
88
|
+
const springCsrfHeader = response.headers.get("Spring-CSRF-header") ?? undefined;
|
|
89
|
+
const springCsrfToken = response.headers.get("Spring-CSRF-token") ?? undefined;
|
|
90
|
+
if (springCsrfHeader && springCsrfToken) {
|
|
91
|
+
const springCsrfTokenInfo = {};
|
|
92
|
+
springCsrfTokenInfo._csrf = springCsrfToken;
|
|
93
|
+
springCsrfTokenInfo._csrf_header = springCsrfHeader;
|
|
94
|
+
updateSpringCsrfMetaTags(springCsrfTokenInfo);
|
|
95
|
+
}
|
|
96
|
+
if (options?.onSuccess) {
|
|
97
|
+
await options.onSuccess();
|
|
98
|
+
}
|
|
99
|
+
const url = savedUrl ?? defaultUrl ?? document.baseURI;
|
|
100
|
+
const toPath = normalizePath(url);
|
|
101
|
+
const navigate = options?.navigate ?? navigateWithPageReload;
|
|
102
|
+
navigate(toPath);
|
|
103
|
+
return {
|
|
104
|
+
defaultUrl,
|
|
105
|
+
error: false,
|
|
106
|
+
redirectUrl: savedUrl,
|
|
107
|
+
token: vaadinCsrfToken
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
error: true,
|
|
112
|
+
errorMessage: "Check that you have entered the correct username and password and try again.",
|
|
113
|
+
errorTitle: "Incorrect username or password."
|
|
114
|
+
};
|
|
115
|
+
} catch (e) {
|
|
116
|
+
if (e instanceof Error) {
|
|
117
|
+
return {
|
|
118
|
+
error: true,
|
|
119
|
+
errorMessage: e.message,
|
|
120
|
+
errorTitle: e.name
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
throw e;
|
|
124
|
+
}
|
|
113
125
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
126
|
+
/**
|
|
127
|
+
* A helper method for Spring Security based form logout
|
|
128
|
+
* @param options - defines additional options, e.g, the logoutUrl.
|
|
129
|
+
*/
|
|
130
|
+
export async function logout(options) {
|
|
131
|
+
const logoutUrl = options?.logoutUrl ?? "logout";
|
|
132
|
+
let response;
|
|
133
|
+
try {
|
|
134
|
+
const headers = getSpringCsrfTokenHeadersForAuthRequest(document);
|
|
135
|
+
response = await doLogout(logoutUrl, headers);
|
|
136
|
+
} catch {
|
|
137
|
+
try {
|
|
138
|
+
const noCacheResponse = await fetch("?nocache");
|
|
139
|
+
const responseText = await noCacheResponse.text();
|
|
140
|
+
const doc = new DOMParser().parseFromString(responseText, "text/html");
|
|
141
|
+
const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);
|
|
142
|
+
response = await doLogout(logoutUrl, headers);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
clearSpringCsrfMetaTags();
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
CookieManager.remove(JWT_COOKIE_NAME);
|
|
149
|
+
if (response && response.ok && response.redirected) {
|
|
150
|
+
if (options?.onSuccess) {
|
|
151
|
+
await options.onSuccess();
|
|
152
|
+
}
|
|
153
|
+
const toPath = normalizePath(response.url);
|
|
154
|
+
const navigate = options?.navigate ?? navigateWithPageReload;
|
|
155
|
+
navigate(toPath);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
142
158
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
159
|
+
/**
|
|
160
|
+
* A helper class for handling invalid sessions during an endpoint call.
|
|
161
|
+
* E.g., you can use this to show user a login page when the session has
|
|
162
|
+
* expired.
|
|
163
|
+
*/
|
|
164
|
+
export class InvalidSessionMiddleware {
|
|
165
|
+
onInvalidSessionCallback;
|
|
166
|
+
constructor(onInvalidSessionCallback) {
|
|
167
|
+
this.onInvalidSessionCallback = onInvalidSessionCallback;
|
|
168
|
+
}
|
|
169
|
+
async invoke(context, next) {
|
|
170
|
+
const clonedContext = { ...context };
|
|
171
|
+
clonedContext.request = context.request.clone();
|
|
172
|
+
const response = await next(context);
|
|
173
|
+
if (response.status === 401) {
|
|
174
|
+
const loginResult = await this.onInvalidSessionCallback();
|
|
175
|
+
if (loginResult.token) {
|
|
176
|
+
clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);
|
|
177
|
+
return next(clonedContext);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return response;
|
|
181
|
+
}
|
|
161
182
|
}
|
|
162
|
-
|
|
163
|
-
InvalidSessionMiddleware,
|
|
164
|
-
login,
|
|
165
|
-
logout
|
|
166
|
-
};
|
|
167
|
-
//# sourceMappingURL=Authentication.js.map
|
|
183
|
+
//# sourceMappingURL=./Authentication.js.map
|
package/Authentication.js.map
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["src/Authentication.ts"],
|
|
4
|
-
"sourcesContent": ["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport { getSpringCsrfInfo, getSpringCsrfTokenHeadersForAuthRequest, VAADIN_CSRF_HEADER } from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"]')).forEach((el) =>\n el.remove(),\n );\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doLogout(logoutUrl: URL | string, headers: Record<string, string>) {\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n\n return response;\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.source = 'typescript';\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n token: vaadinCsrfToken,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n let response: Response | undefined;\n try {\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n response = await doLogout(logoutUrl, headers);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n response = await doLogout(logoutUrl, headers);\n } catch (error) {\n // clear the token if the call fails\n clearSpringCsrfMetaTags();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext) as Promise<Response>;\n }\n }\n return response;\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,OAAO,mBAAmB;AAC1B,SAAS,mBAAmB,yCAAyC,0BAA0B;AAE/F,MAAM,kBAAkB;AAExB,SAAS,mCAAmC,MAAsC;AAChF,QAAM,MAAM,IAAI,UAAU,EAAE,gBAAgB,MAAM,WAAW;AAC7D,SAAO,kBAAkB,GAAG;AAC9B;AAEA,SAAS,0BAA0B;AACjC,QAAM,KAAK,SAAS,KAAK,iBAAiB,+CAA+C,CAAC,EAAE;AAAA,IAAQ,CAAC,OACnG,GAAG,OAAO;AAAA,EACZ;AACF;AAEA,SAAS,yBAAyB,gBAAwC;AACxE,0BAAwB;AACxB,QAAM,iBAAkC,SAAS,cAAc,MAAM;AACrE,iBAAe,OAAO;AACtB,iBAAe,UAAU,eAAe;AACxC,WAAS,KAAK,YAAY,cAAc;AACxC,QAAM,YAA6B,SAAS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,gBAAc,UAAU,QAAQ,QAAQ,OAAO;EAC/C,MAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,MAAI,SAAS,WAAW,KAAK;GAC3B,MAAM,cAAc,MAAM,KAAK,0BAA0B;AACzD,OAAI,YAAY,OAAO;AACrB,kBAAc,QAAQ,QAAQ,IAAI,oBAAoB,YAAY,MAAM;AACxE,WAAO,KAAK,cAAc;GAC3B;EACF;AACD,SAAO;CACR;AACF","names":["body: string","springCsrfInfo: Record<string, string>","headerNameMeta: HTMLMetaElement","tokenMeta: HTMLMetaElement","response: Response","logoutUrl: URL | string","headers: Record<string, string>","url: string","to: string","username: string","password: string","options?: LoginOptions","springCsrfTokenInfo: Record<string, string>","e: unknown","options?: LogoutOptions","response: Response | undefined","onInvalidSessionCallback: OnInvalidSessionCallback","context: MiddlewareContext","next: MiddlewareNext"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/Authentication.ts"],"sourcesContent":["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport { getSpringCsrfInfo, getSpringCsrfTokenHeadersForAuthRequest, VAADIN_CSRF_HEADER } from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"]')).forEach((el) =>\n el.remove(),\n );\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doLogout(logoutUrl: URL | string, headers: Record<string, string>) {\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n\n return response;\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.source = 'typescript';\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n token: vaadinCsrfToken,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n let response: Response | undefined;\n try {\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n response = await doLogout(logoutUrl, headers);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n response = await doLogout(logoutUrl, headers);\n } catch (error) {\n // clear the token if the call fails\n clearSpringCsrfMetaTags();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext) as Promise<Response>;\n }\n }\n return response;\n }\n}\n"],"version":3}
|