@molecule/app-angular 3.3.1 → 3.6.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.
- package/README.md +4049 -1255
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +3 -2
- package/dist/chat.js.map +1 -1
- package/dist/hooks/external-store.d.ts +32 -0
- package/dist/hooks/external-store.d.ts.map +1 -0
- package/dist/hooks/external-store.js +62 -0
- package/dist/hooks/external-store.js.map +1 -0
- package/dist/hooks/index.d.ts +24 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +24 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/use-ai-models.d.ts +53 -0
- package/dist/hooks/use-ai-models.d.ts.map +1 -0
- package/dist/hooks/use-ai-models.js +167 -0
- package/dist/hooks/use-ai-models.js.map +1 -0
- package/dist/hooks/use-async.d.ts +129 -0
- package/dist/hooks/use-async.d.ts.map +1 -0
- package/dist/hooks/use-async.js +194 -0
- package/dist/hooks/use-async.js.map +1 -0
- package/dist/hooks/use-auth-flows.d.ts +226 -0
- package/dist/hooks/use-auth-flows.d.ts.map +1 -0
- package/dist/hooks/use-auth-flows.js +481 -0
- package/dist/hooks/use-auth-flows.js.map +1 -0
- package/dist/hooks/use-auth.d.ts +85 -0
- package/dist/hooks/use-auth.d.ts.map +1 -0
- package/dist/hooks/use-auth.js +104 -0
- package/dist/hooks/use-auth.js.map +1 -0
- package/dist/hooks/use-forms.d.ts +174 -0
- package/dist/hooks/use-forms.d.ts.map +1 -0
- package/dist/hooks/use-forms.js +221 -0
- package/dist/hooks/use-forms.js.map +1 -0
- package/dist/hooks/use-http.d.ts +163 -0
- package/dist/hooks/use-http.d.ts.map +1 -0
- package/dist/hooks/use-http.js +198 -0
- package/dist/hooks/use-http.js.map +1 -0
- package/dist/hooks/use-ide.d.ts +208 -0
- package/dist/hooks/use-ide.d.ts.map +1 -0
- package/dist/hooks/use-ide.js +217 -0
- package/dist/hooks/use-ide.js.map +1 -0
- package/dist/hooks/use-logger.d.ts +40 -0
- package/dist/hooks/use-logger.d.ts.map +1 -0
- package/dist/hooks/use-logger.js +56 -0
- package/dist/hooks/use-logger.js.map +1 -0
- package/dist/hooks/use-native.d.ts +218 -0
- package/dist/hooks/use-native.d.ts.map +1 -0
- package/dist/hooks/use-native.js +173 -0
- package/dist/hooks/use-native.js.map +1 -0
- package/dist/hooks/use-profile-form.d.ts +113 -0
- package/dist/hooks/use-profile-form.d.ts.map +1 -0
- package/dist/hooks/use-profile-form.js +253 -0
- package/dist/hooks/use-profile-form.js.map +1 -0
- package/dist/hooks/use-router.d.ts +219 -0
- package/dist/hooks/use-router.d.ts.map +1 -0
- package/dist/hooks/use-router.js +266 -0
- package/dist/hooks/use-router.js.map +1 -0
- package/dist/hooks/use-storage.d.ts +142 -0
- package/dist/hooks/use-storage.d.ts.map +1 -0
- package/dist/hooks/use-storage.js +299 -0
- package/dist/hooks/use-storage.js.map +1 -0
- package/dist/hooks/use-store.d.ts +81 -0
- package/dist/hooks/use-store.d.ts.map +1 -0
- package/dist/hooks/use-store.js +143 -0
- package/dist/hooks/use-store.js.map +1 -0
- package/dist/hooks/use-theme.d.ts +59 -0
- package/dist/hooks/use-theme.d.ts.map +1 -0
- package/dist/hooks/use-theme.js +117 -0
- package/dist/hooks/use-theme.js.map +1 -0
- package/dist/hooks/use-translation.d.ts +91 -0
- package/dist/hooks/use-translation.d.ts.map +1 -0
- package/dist/hooks/use-translation.js +152 -0
- package/dist/hooks/use-translation.js.map +1 -0
- package/dist/hooks/use-verify-payment-return.d.ts +86 -0
- package/dist/hooks/use-verify-payment-return.d.ts.map +1 -0
- package/dist/hooks/use-verify-payment-return.js +167 -0
- package/dist/hooks/use-verify-payment-return.js.map +1 -0
- package/dist/hooks/use-version.d.ts +49 -0
- package/dist/hooks/use-version.d.ts.map +1 -0
- package/dist/hooks/use-version.js +70 -0
- package/dist/hooks/use-version.js.map +1 -0
- package/dist/i18n-reactive.d.ts +2 -5
- package/dist/i18n-reactive.d.ts.map +1 -1
- package/dist/i18n-reactive.js.map +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/inject.d.ts +24 -0
- package/dist/inject.d.ts.map +1 -0
- package/dist/inject.js +33 -0
- package/dist/inject.js.map +1 -0
- package/dist/link.d.ts +63 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +82 -0
- package/dist/link.js.map +1 -0
- package/dist/maybe-signal.d.ts +26 -0
- package/dist/maybe-signal.d.ts.map +1 -0
- package/dist/maybe-signal.js +20 -0
- package/dist/maybe-signal.js.map +1 -0
- package/dist/providers.d.ts +24 -0
- package/dist/providers.d.ts.map +1 -1
- package/dist/providers.js +44 -3
- package/dist/providers.js.map +1 -1
- package/dist/session-ready.d.ts +41 -0
- package/dist/session-ready.d.ts.map +1 -0
- package/dist/session-ready.js +79 -0
- package/dist/session-ready.js.map +1 -0
- package/dist/tokens.d.ts +15 -0
- package/dist/tokens.d.ts.map +1 -1
- package/dist/tokens.js +12 -0
- package/dist/tokens.js.map +1 -1
- package/dist/types.d.ts +14 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Angular functions for the auth flows, mirroring `useLogin`, `useSignup`,
|
|
3
|
+
* `useChangePassword`, `usePasswordReset` and `useOAuth` from
|
|
4
|
+
* `@molecule/app-react`.
|
|
5
|
+
*
|
|
6
|
+
* The state fields of the tracked hooks are LIVE getters over the underlying
|
|
7
|
+
* `usePromise` state object: the result object is built once per instance (an
|
|
8
|
+
* Angular instantiation runs once), and every later read must show the
|
|
9
|
+
* current state, which React re-renders into a fresh result object.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { DestroyRef, effect, inject, untracked } from '@angular/core';
|
|
14
|
+
import { t } from '@molecule/app-i18n';
|
|
15
|
+
import { readMaybeSignal } from '../maybe-signal.js';
|
|
16
|
+
import { usePromise } from './use-async.js';
|
|
17
|
+
import { useAuthClient } from './use-auth.js';
|
|
18
|
+
/**
|
|
19
|
+
* Login with async state tracking. Call it in an injection context.
|
|
20
|
+
*
|
|
21
|
+
* Registration is available through `const { register } = useAuth()`;
|
|
22
|
+
* call `register({ email, password, name })` to create an account. There is
|
|
23
|
+
* no separate `useRegister` hook. Use `usePromise(register)` when the form
|
|
24
|
+
* needs the same pending/error tracking as this login hook.
|
|
25
|
+
*
|
|
26
|
+
* @returns Login state and action.
|
|
27
|
+
*/
|
|
28
|
+
export function useLogin() {
|
|
29
|
+
const client = useAuthClient();
|
|
30
|
+
const loginFn = (credentials) => client.login(credentials);
|
|
31
|
+
const [state, call] = usePromise(loginFn);
|
|
32
|
+
return {
|
|
33
|
+
get status() {
|
|
34
|
+
return state.status;
|
|
35
|
+
},
|
|
36
|
+
get value() {
|
|
37
|
+
return state.value;
|
|
38
|
+
},
|
|
39
|
+
get error() {
|
|
40
|
+
return state.error;
|
|
41
|
+
},
|
|
42
|
+
login: call,
|
|
43
|
+
reset: state.reset,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Registration with async state tracking. Call it in an injection context.
|
|
48
|
+
*
|
|
49
|
+
* @returns Signup state and action.
|
|
50
|
+
*/
|
|
51
|
+
export function useSignup() {
|
|
52
|
+
const client = useAuthClient();
|
|
53
|
+
const registerFn = (data) => client.register(data);
|
|
54
|
+
const [state, call] = usePromise(registerFn);
|
|
55
|
+
return {
|
|
56
|
+
get status() {
|
|
57
|
+
return state.status;
|
|
58
|
+
},
|
|
59
|
+
get value() {
|
|
60
|
+
return state.value;
|
|
61
|
+
},
|
|
62
|
+
get error() {
|
|
63
|
+
return state.error;
|
|
64
|
+
},
|
|
65
|
+
signup: call,
|
|
66
|
+
reset: state.reset,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Changing a password with async state tracking. Call it in an injection
|
|
71
|
+
* context.
|
|
72
|
+
*
|
|
73
|
+
* @returns Change-password state and action.
|
|
74
|
+
*/
|
|
75
|
+
export function useChangePassword() {
|
|
76
|
+
const client = useAuthClient();
|
|
77
|
+
const changeFn = (oldPassword, newPassword) => client.changePassword(oldPassword, newPassword);
|
|
78
|
+
const [state, call] = usePromise(changeFn);
|
|
79
|
+
return {
|
|
80
|
+
get status() {
|
|
81
|
+
return state.status;
|
|
82
|
+
},
|
|
83
|
+
get error() {
|
|
84
|
+
return state.error;
|
|
85
|
+
},
|
|
86
|
+
changePassword: call,
|
|
87
|
+
reset: state.reset,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The password reset flow with async state tracking, one tracker per step.
|
|
92
|
+
* Call it in an injection context.
|
|
93
|
+
*
|
|
94
|
+
* @returns Password reset state and actions.
|
|
95
|
+
*/
|
|
96
|
+
export function usePasswordReset() {
|
|
97
|
+
const client = useAuthClient();
|
|
98
|
+
const requestFn = (data) => client.requestPasswordReset(data);
|
|
99
|
+
const confirmFn = (data) => client.confirmPasswordReset(data);
|
|
100
|
+
const [requestState, requestCall] = usePromise(requestFn);
|
|
101
|
+
const [confirmState, confirmCall] = usePromise(confirmFn);
|
|
102
|
+
return {
|
|
103
|
+
get requestStatus() {
|
|
104
|
+
return requestState.status;
|
|
105
|
+
},
|
|
106
|
+
get requestError() {
|
|
107
|
+
return requestState.error;
|
|
108
|
+
},
|
|
109
|
+
get confirmStatus() {
|
|
110
|
+
return confirmState.status;
|
|
111
|
+
},
|
|
112
|
+
get confirmError() {
|
|
113
|
+
return confirmState.error;
|
|
114
|
+
},
|
|
115
|
+
requestReset: requestCall,
|
|
116
|
+
confirmReset: confirmCall,
|
|
117
|
+
reset: () => {
|
|
118
|
+
requestState.reset();
|
|
119
|
+
confirmState.reset();
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** What `onError` gets when the server gives no reason of its own. */
|
|
124
|
+
const oauthFailed = () => t('angular.error.oauthFailed', undefined, { defaultValue: 'OAuth login failed' });
|
|
125
|
+
/**
|
|
126
|
+
* `window.open` name for the OAuth popup. The callback page relays its result
|
|
127
|
+
* to the opener ONLY when its own `window.name` equals this AND
|
|
128
|
+
* `window.opener` exists — so a normal (full-page) callback never takes the
|
|
129
|
+
* relay path.
|
|
130
|
+
*/
|
|
131
|
+
const OAUTH_POPUP_WINDOW_NAME = 'molecule-oauth-popup';
|
|
132
|
+
/** Private `postMessage` type for the popup→opener result relay. */
|
|
133
|
+
const OAUTH_RESULT_MESSAGE_TYPE = 'molecule:oauth-result';
|
|
134
|
+
/** Hard cap on how long the opener waits for the popup before giving up. */
|
|
135
|
+
const OAUTH_POPUP_TIMEOUT_MS = 5 * 60 * 1000;
|
|
136
|
+
/**
|
|
137
|
+
* OAuth authentication. Call it in an injection context.
|
|
138
|
+
*
|
|
139
|
+
* Reads OAuth configuration from the provided config and provides helpers to
|
|
140
|
+
* build OAuth URLs and start a login (full-page or popup). Automatically
|
|
141
|
+
* handles OAuth callbacks by detecting `code` and `state` URL parameters and
|
|
142
|
+
* exchanging them for a session — and, when the callback is running inside a
|
|
143
|
+
* popup we opened, relaying the result to the opener instead.
|
|
144
|
+
*
|
|
145
|
+
* The config may be a signal, and the result follows it the way React's
|
|
146
|
+
* re-render does: `providers` reads the config at the moment it is read,
|
|
147
|
+
* `getOAuthUrl` builds from the config at call time, and a flow (`redirect`,
|
|
148
|
+
* `loginViaPopup`, a callback exchange) uses the config it was started with,
|
|
149
|
+
* like the render closure React started it from.
|
|
150
|
+
*
|
|
151
|
+
* Unmounting does not cancel a flow that has started. A popup result or a
|
|
152
|
+
* callback exchange that settles afterwards still establishes the session on
|
|
153
|
+
* the shared auth client, because the user did sign in. `onSuccess` and
|
|
154
|
+
* `onError` are not called after unmount: they belong to the unmounted view.
|
|
155
|
+
*
|
|
156
|
+
* @param config - Optional OAuth configuration override (see
|
|
157
|
+
* {@link UseOAuthConfig}), or a signal of it.
|
|
158
|
+
* @returns OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.
|
|
159
|
+
*/
|
|
160
|
+
export function useOAuth(config) {
|
|
161
|
+
const authClient = useAuthClient();
|
|
162
|
+
// Whether the host is mounted, read when a flow settles (an Angular
|
|
163
|
+
// instantiation is never re-run, so one DestroyRef flag mirrors React's
|
|
164
|
+
// mounted ref).
|
|
165
|
+
const destroyRef = inject(DestroyRef);
|
|
166
|
+
let mounted = true;
|
|
167
|
+
destroyRef.onDestroy(() => {
|
|
168
|
+
mounted = false;
|
|
169
|
+
});
|
|
170
|
+
const getOAuthUrl = (provider) => {
|
|
171
|
+
// Encode the provider as a single path segment so a (future) caller passing an
|
|
172
|
+
// untrusted value can never inject a path/query/scheme into the opened URL —
|
|
173
|
+
// defense-in-depth on top of the upstream static provider allowlist. Plain
|
|
174
|
+
// provider names ('github', 'google') pass through unchanged.
|
|
175
|
+
const current = readMaybeSignal(config);
|
|
176
|
+
return `${current?.baseURL ?? ''}${current?.oauthEndpoint ?? '/oauth'}/${encodeURIComponent(provider)}`;
|
|
177
|
+
};
|
|
178
|
+
/** Stash which provider initiated the flow so the callback knows it's ours. */
|
|
179
|
+
const stashProvider = (provider) => {
|
|
180
|
+
try {
|
|
181
|
+
sessionStorage.setItem('oauth_provider', provider);
|
|
182
|
+
}
|
|
183
|
+
catch (_error) {
|
|
184
|
+
/* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Append the current page's PATH as `redirect_to` so the api's initiation
|
|
189
|
+
* endpoint (`GET /users/oauth/:provider`) builds a provider `redirect_uri`
|
|
190
|
+
* that lands the callback back on THIS page — the one with `useOAuth`
|
|
191
|
+
* mounted (e.g. `/login`) — instead of the app root, where nothing may be
|
|
192
|
+
* listening for the `code` param. Path only (no origin/query): the server
|
|
193
|
+
* validates it as a same-origin absolute path, so it can never become an
|
|
194
|
+
* open redirect. Servers that predate the param simply ignore it.
|
|
195
|
+
*/
|
|
196
|
+
const withReturnPath = (url) => {
|
|
197
|
+
const path = typeof window !== 'undefined' ? window.location.pathname : '';
|
|
198
|
+
if (!path || path === '/')
|
|
199
|
+
return url;
|
|
200
|
+
return `${url}${url.includes('?') ? '&' : '?'}redirect_to=${encodeURIComponent(path)}`;
|
|
201
|
+
};
|
|
202
|
+
/**
|
|
203
|
+
* Establish the authenticated session from an exchange result: seed the
|
|
204
|
+
* access token + user and let `initialize()` flip `authenticated`. Mirrors
|
|
205
|
+
* what `authClient.login()` does for password login. Returns whether a user
|
|
206
|
+
* was set (a result with no user is not a real session).
|
|
207
|
+
*/
|
|
208
|
+
const establishSession = async (token, user) => {
|
|
209
|
+
// Seed the token via the auth client's configured token storage adapter
|
|
210
|
+
// (in-memory by default) — NOT localStorage directly. Writing the bearer
|
|
211
|
+
// token to localStorage violates the in-memory-default storage contract and
|
|
212
|
+
// makes it JS-readable (XSS-exfiltratable).
|
|
213
|
+
if (token)
|
|
214
|
+
authClient.setAccessToken(token);
|
|
215
|
+
if (user && typeof user === 'object') {
|
|
216
|
+
authClient.setUser(user);
|
|
217
|
+
await authClient.initialize();
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
return false;
|
|
221
|
+
};
|
|
222
|
+
/** Leaves the page for the provider: the `navigate` option, else a full-page navigation. */
|
|
223
|
+
const leaveFor = (url, navigateOption) => {
|
|
224
|
+
if (navigateOption)
|
|
225
|
+
navigateOption(url);
|
|
226
|
+
else
|
|
227
|
+
window.location.href = url;
|
|
228
|
+
};
|
|
229
|
+
const redirect = (provider) => {
|
|
230
|
+
stashProvider(provider);
|
|
231
|
+
leaveFor(withReturnPath(getOAuthUrl(provider)), readMaybeSignal(config)?.navigate);
|
|
232
|
+
};
|
|
233
|
+
// The currently-open OAuth popup, so a second click focuses it instead of
|
|
234
|
+
// stacking a second flow (the relay gates already fail safe, but one window is
|
|
235
|
+
// cleaner and avoids an orphaned listener until the timeout reaps it).
|
|
236
|
+
let activePopup = null;
|
|
237
|
+
const loginViaPopup = (provider) => {
|
|
238
|
+
// The config this flow was started with, like the render closure React
|
|
239
|
+
// starts a flow from; a config change after that does not reach it.
|
|
240
|
+
const flowConfig = readMaybeSignal(config);
|
|
241
|
+
// A flow is already open — focus it rather than starting another.
|
|
242
|
+
if (activePopup && !activePopup.closed) {
|
|
243
|
+
try {
|
|
244
|
+
activePopup.focus();
|
|
245
|
+
}
|
|
246
|
+
catch (_error) {
|
|
247
|
+
/* best-effort focus */
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
stashProvider(provider);
|
|
252
|
+
const url = withReturnPath(getOAuthUrl(provider));
|
|
253
|
+
// A named popup. We intentionally do NOT pass `noopener` — the popup needs
|
|
254
|
+
// `window.opener` to relay its result back. The window only ever navigates
|
|
255
|
+
// to OUR api → the trusted provider → OUR origin, so this is the standard
|
|
256
|
+
// OAuth-popup trade-off (a malicious *provider* could touch `window.opener`,
|
|
257
|
+
// which is out of scope; we don't open attacker-controlled URLs here).
|
|
258
|
+
const features = 'popup=yes,width=520,height=680,menubar=no,toolbar=no,location=yes';
|
|
259
|
+
const popup = window.open(url, OAUTH_POPUP_WINDOW_NAME, features);
|
|
260
|
+
// Popup blocked (or unavailable) → fall back to a full-page redirect so login
|
|
261
|
+
// still works. No listener is registered in this branch.
|
|
262
|
+
if (!popup) {
|
|
263
|
+
leaveFor(url, flowConfig?.navigate);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
activePopup = popup;
|
|
267
|
+
let settled = false;
|
|
268
|
+
const timers = {};
|
|
269
|
+
const cleanup = () => {
|
|
270
|
+
window.removeEventListener('message', onMessage);
|
|
271
|
+
if (timers.closed)
|
|
272
|
+
clearInterval(timers.closed);
|
|
273
|
+
if (timers.timeout)
|
|
274
|
+
clearTimeout(timers.timeout);
|
|
275
|
+
if (activePopup === popup)
|
|
276
|
+
activePopup = null;
|
|
277
|
+
};
|
|
278
|
+
const onMessage = (event) => {
|
|
279
|
+
// SECURITY — accept the result ONLY from our own origin, ONLY from the exact
|
|
280
|
+
// popup window we opened, and ONLY when it carries our private type. Any one
|
|
281
|
+
// failing means a forged / unrelated message: ignore it silently. This is
|
|
282
|
+
// what prevents a malicious page from injecting a session.
|
|
283
|
+
if (event.origin !== window.location.origin)
|
|
284
|
+
return;
|
|
285
|
+
if (event.source !== popup)
|
|
286
|
+
return;
|
|
287
|
+
const data = event.data;
|
|
288
|
+
if (!data || typeof data !== 'object' || data.type !== OAUTH_RESULT_MESSAGE_TYPE)
|
|
289
|
+
return;
|
|
290
|
+
if (settled)
|
|
291
|
+
return;
|
|
292
|
+
settled = true;
|
|
293
|
+
cleanup();
|
|
294
|
+
try {
|
|
295
|
+
popup.close();
|
|
296
|
+
}
|
|
297
|
+
catch (_error) {
|
|
298
|
+
/* already closed — nothing to do */
|
|
299
|
+
}
|
|
300
|
+
if (data.ok) {
|
|
301
|
+
void establishSession(data.token, data.user).then((ok) => {
|
|
302
|
+
if (!mounted)
|
|
303
|
+
return;
|
|
304
|
+
if (ok)
|
|
305
|
+
flowConfig?.onSuccess?.();
|
|
306
|
+
else
|
|
307
|
+
flowConfig?.onError?.(oauthFailed());
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
else if (mounted) {
|
|
311
|
+
flowConfig?.onError?.(typeof data.error === 'string' ? data.error : oauthFailed());
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
window.addEventListener('message', onMessage);
|
|
315
|
+
// The user closed the popup without completing — silently stop waiting (no
|
|
316
|
+
// error toast for a deliberate cancel) and release the listener.
|
|
317
|
+
timers.closed = setInterval(() => {
|
|
318
|
+
if (popup.closed && !settled) {
|
|
319
|
+
settled = true;
|
|
320
|
+
cleanup();
|
|
321
|
+
}
|
|
322
|
+
}, 500);
|
|
323
|
+
// Hard safety timeout so a wedged popup never leaks a listener forever.
|
|
324
|
+
timers.timeout = setTimeout(() => {
|
|
325
|
+
if (!settled) {
|
|
326
|
+
settled = true;
|
|
327
|
+
cleanup();
|
|
328
|
+
try {
|
|
329
|
+
popup.close();
|
|
330
|
+
}
|
|
331
|
+
catch (_error) {
|
|
332
|
+
/* best-effort */
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}, OAUTH_POPUP_TIMEOUT_MS);
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Handles the OAuth callback — detects `code` and `state` in the URL params
|
|
339
|
+
* and exchanges the code for a session (or relays it to the opener), reading
|
|
340
|
+
* the config the detection runs for.
|
|
341
|
+
*/
|
|
342
|
+
const detectCallback = (callbackConfig) => {
|
|
343
|
+
const baseURL = callbackConfig?.baseURL ?? '';
|
|
344
|
+
const loginEndpoint = callbackConfig?.loginEndpoint ?? '/users/log-in/oauth';
|
|
345
|
+
const params = new URLSearchParams(window.location.search);
|
|
346
|
+
const code = params.get('code');
|
|
347
|
+
const state = params.get('state');
|
|
348
|
+
if (!code)
|
|
349
|
+
return;
|
|
350
|
+
// Retrieve the provider that initiated the flow.
|
|
351
|
+
let provider = null;
|
|
352
|
+
try {
|
|
353
|
+
provider = sessionStorage.getItem('oauth_provider');
|
|
354
|
+
}
|
|
355
|
+
catch (_error) {
|
|
356
|
+
/* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
|
|
357
|
+
}
|
|
358
|
+
if (!provider)
|
|
359
|
+
return;
|
|
360
|
+
// Are we the OAuth popup we opened? Relay the result to the opener instead of
|
|
361
|
+
// establishing the session in this (about-to-close) window. Gated on BOTH the
|
|
362
|
+
// window name AND window.opener so a normal full-page callback never relays.
|
|
363
|
+
const inPopup = typeof window !== 'undefined' && !!window.opener && window.name === OAUTH_POPUP_WINDOW_NAME;
|
|
364
|
+
// Clean up URL (remove code/state params) and sessionStorage.
|
|
365
|
+
const cleanUrl = new URL(window.location.href);
|
|
366
|
+
cleanUrl.searchParams.delete('code');
|
|
367
|
+
cleanUrl.searchParams.delete('state');
|
|
368
|
+
window.history.replaceState({}, '', cleanUrl.toString());
|
|
369
|
+
try {
|
|
370
|
+
sessionStorage.removeItem('oauth_provider');
|
|
371
|
+
}
|
|
372
|
+
catch (_error) {
|
|
373
|
+
/* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
|
|
374
|
+
}
|
|
375
|
+
/** Relay a result to the opener (popup path) — origin-pinned, never `'*'`. */
|
|
376
|
+
const relayToOpener = (message) => {
|
|
377
|
+
try {
|
|
378
|
+
// targetOrigin is our OWN origin: the browser delivers the message (and the
|
|
379
|
+
// token it carries) ONLY if the opener is still on this origin. Never '*'.
|
|
380
|
+
window.opener?.postMessage(message, window.location.origin);
|
|
381
|
+
}
|
|
382
|
+
catch (_error) {
|
|
383
|
+
/* opener gone / cross-origin — the opener's close-poll will recover */
|
|
384
|
+
}
|
|
385
|
+
try {
|
|
386
|
+
window.close();
|
|
387
|
+
}
|
|
388
|
+
catch (_error) {
|
|
389
|
+
/* best-effort */
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
// Exchange code for session.
|
|
393
|
+
const exchangeCode = async () => {
|
|
394
|
+
try {
|
|
395
|
+
const response = await fetch(`${baseURL}${loginEndpoint}`, {
|
|
396
|
+
method: 'POST',
|
|
397
|
+
headers: { 'Content-Type': 'application/json' },
|
|
398
|
+
credentials: 'include', // Send cookies (oauth_state) for state validation
|
|
399
|
+
body: JSON.stringify({
|
|
400
|
+
server: provider,
|
|
401
|
+
code,
|
|
402
|
+
state: state || undefined,
|
|
403
|
+
redirect_uri: window.location.origin,
|
|
404
|
+
}),
|
|
405
|
+
});
|
|
406
|
+
if (!response.ok) {
|
|
407
|
+
// A body that is not JSON: report the generic failure.
|
|
408
|
+
const data = await response.json().catch((_error) => ({ error: oauthFailed() }));
|
|
409
|
+
const error = data.error || oauthFailed();
|
|
410
|
+
if (inPopup) {
|
|
411
|
+
relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: false, error });
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (mounted)
|
|
415
|
+
callbackConfig?.onError?.(error);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
// A body that is not JSON carries no user; the token comes from the header.
|
|
419
|
+
const data = await response.json().catch((_error) => null);
|
|
420
|
+
// Store the token from the response.
|
|
421
|
+
const authHeader = response.headers.get('authorization') || response.headers.get('set-authorization');
|
|
422
|
+
const token = authHeader ? authHeader.replace('Bearer ', '') : null;
|
|
423
|
+
// The authenticated user is `props` (molecule resource convention) or `user`
|
|
424
|
+
// (generic AuthResult). OAuth issues no refresh token, so we carry the token +
|
|
425
|
+
// user to whoever will own the session.
|
|
426
|
+
const user = data && typeof data === 'object'
|
|
427
|
+
? (data.props ??
|
|
428
|
+
data.user ??
|
|
429
|
+
null)
|
|
430
|
+
: null;
|
|
431
|
+
if (inPopup) {
|
|
432
|
+
// Relay to the opener — it (same origin) establishes the session in place.
|
|
433
|
+
// Do NOT establish it here; this window is about to close.
|
|
434
|
+
relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: true, token, user });
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
// Full-page callback: establish the session here, then fire onSuccess —
|
|
438
|
+
// unchanged behavior.
|
|
439
|
+
const ok = await establishSession(token, user);
|
|
440
|
+
if (!mounted)
|
|
441
|
+
return;
|
|
442
|
+
if (ok)
|
|
443
|
+
callbackConfig?.onSuccess?.();
|
|
444
|
+
else
|
|
445
|
+
callbackConfig?.onError?.(oauthFailed());
|
|
446
|
+
}
|
|
447
|
+
catch (err) {
|
|
448
|
+
const error = err instanceof Error ? err.message : oauthFailed();
|
|
449
|
+
if (inPopup) {
|
|
450
|
+
relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: false, error });
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (mounted)
|
|
454
|
+
callbackConfig?.onError?.(error);
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
void exchangeCode();
|
|
458
|
+
};
|
|
459
|
+
// Handle the OAuth callback for the config this component mounted with, and
|
|
460
|
+
// again for a changed config — React's effect keyed on the config identity
|
|
461
|
+
// re-runs it the same way (the cleaned URL and sessionStorage make the
|
|
462
|
+
// re-run settle nothing).
|
|
463
|
+
let detectedWith = readMaybeSignal(config);
|
|
464
|
+
detectCallback(detectedWith);
|
|
465
|
+
effect(() => {
|
|
466
|
+
const next = readMaybeSignal(config);
|
|
467
|
+
if (next === detectedWith)
|
|
468
|
+
return;
|
|
469
|
+
detectedWith = next;
|
|
470
|
+
untracked(() => detectCallback(next));
|
|
471
|
+
});
|
|
472
|
+
return {
|
|
473
|
+
get providers() {
|
|
474
|
+
return readMaybeSignal(config)?.oauthProviders ?? [];
|
|
475
|
+
},
|
|
476
|
+
getOAuthUrl,
|
|
477
|
+
redirect,
|
|
478
|
+
loginViaPopup,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
//# sourceMappingURL=use-auth-flows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-auth-flows.js","sourceRoot":"","sources":["../../src/hooks/use-auth-flows.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAUrE,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAEtC,OAAO,EAAoB,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACtE,OAAO,EAAE,UAAU,EAAwB,MAAM,gBAAgB,CAAA;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAyB7C;;;;;;;;;GASG;AACH,MAAM,UAAU,QAAQ;IACtB,MAAM,MAAM,GAAG,aAAa,EAAK,CAAA;IAEjC,MAAM,OAAO,GAAG,CAAC,WAA6B,EAA0B,EAAE,CACxE,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAA;IAE3B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IAAI,OAAO;oBAAE,cAAc,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,CAAA;YAC/C,CAAC;QACH,CAAC,CAAA;QAED,KAAK,YAAY,EAAE,CAAA;IACrB,CAAC,CAAA;IAED,4EAA4E;IAC5E,2EAA2E;IAC3E,uEAAuE;IACvE,0BAA0B;IAC1B,IAAI,YAAY,GAAG,eAAe,CAAC,MAAM,CAAC,CAAA;IAC1C,cAAc,CAAC,YAAY,CAAC,CAAA;IAC5B,MAAM,CAAC,GAAG,EAAE;QACV,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,CAAA;QACpC,IAAI,IAAI,KAAK,YAAY;YAAE,OAAM;QACjC,YAAY,GAAG,IAAI,CAAA;QACnB,SAAS,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;IACvC,CAAC,CAAC,CAAA;IAEF,OAAO;QACL,IAAI,SAAS;YACX,OAAO,eAAe,CAAC,MAAM,CAAC,EAAE,cAAc,IAAI,EAAE,CAAA;QACtD,CAAC;QACD,WAAW;QACX,QAAQ;QACR,aAAa;KACd,CAAA;AACH,CAAC"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Angular functions for authentication, mirroring `useAuth`,
|
|
3
|
+
* `useAuthClient`, `useUser` and `useIsAuthenticated` from
|
|
4
|
+
* `@molecule/app-react`.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import { type Signal } from '@angular/core';
|
|
9
|
+
import type { AuthClient, AuthResult, AuthSessionSeed, AuthState, LoginCredentials, RegisterData, RegisterExtraShape } from '@molecule/app-auth';
|
|
10
|
+
import { type MaybeSignal } from '../maybe-signal.js';
|
|
11
|
+
/**
|
|
12
|
+
* The auth client registered by `provideMolecule({ auth })` or `provideAuth`.
|
|
13
|
+
* Call it in an injection context.
|
|
14
|
+
*
|
|
15
|
+
* @returns The auth client.
|
|
16
|
+
* @throws {Error} When no auth client is registered.
|
|
17
|
+
*/
|
|
18
|
+
export declare function useAuthClient<T = unknown, TRegister extends RegisterExtraShape<TRegister> = Record<never, never>>(): AuthClient<T, TRegister>;
|
|
19
|
+
/** Options for {@link useAuth}. */
|
|
20
|
+
export interface UseAuthOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Refresh the session once on mount when the visitor is signed out and the
|
|
23
|
+
* state is decided (a silent probe for a token the storage may hold).
|
|
24
|
+
* Default `false`.
|
|
25
|
+
*/
|
|
26
|
+
autoRefresh?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* What {@link useAuth} returns: every state field as a signal and every auth
|
|
30
|
+
* action as a plain function.
|
|
31
|
+
*/
|
|
32
|
+
export interface UseAuthResult<T = unknown, TRegister extends RegisterExtraShape<TRegister> = Record<never, never>> {
|
|
33
|
+
/** `'loading'` until the client decides the session, then its status. */
|
|
34
|
+
readonly status: Signal<AuthState<T>['status']>;
|
|
35
|
+
/** The full auth state. */
|
|
36
|
+
readonly state: Signal<AuthState<T>>;
|
|
37
|
+
/** The signed-in user, or `null`. */
|
|
38
|
+
readonly user: Signal<T | null>;
|
|
39
|
+
/** Whether a session exists. */
|
|
40
|
+
readonly isAuthenticated: Signal<boolean>;
|
|
41
|
+
/** Whether the session is still being decided. */
|
|
42
|
+
readonly isLoading: Signal<boolean>;
|
|
43
|
+
/** Signs in with credentials. */
|
|
44
|
+
login: (credentials: LoginCredentials) => Promise<AuthResult<T>>;
|
|
45
|
+
/** Signs out. */
|
|
46
|
+
logout: () => Promise<void>;
|
|
47
|
+
/** Creates an account (also signs it in). */
|
|
48
|
+
register: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>;
|
|
49
|
+
/** Refreshes the session from its token. */
|
|
50
|
+
refresh: () => Promise<AuthResult<T>>;
|
|
51
|
+
/** Saves profile edits through the client and publishes the saved user. */
|
|
52
|
+
updateProfile: (data: Partial<T>) => Promise<T>;
|
|
53
|
+
/** Caches a user without signing in. */
|
|
54
|
+
setUser: (user: T | null) => void;
|
|
55
|
+
/** Adopts a caller-issued session atomically. */
|
|
56
|
+
setSession: (session: AuthSessionSeed<T>) => void;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Authentication state and actions. Call it in an injection context (a
|
|
60
|
+
* component field initializer or constructor).
|
|
61
|
+
*
|
|
62
|
+
* `status === 'loading'` is undecided; `'unavailable'` keeps the candidate
|
|
63
|
+
* session for retry; a restore failure never signs out.
|
|
64
|
+
*
|
|
65
|
+
* The options may be a signal: `autoRefresh` turning on through it probes once
|
|
66
|
+
* (when the visitor is signed out and decided), the way React re-renders
|
|
67
|
+
* `useAuth` with the new option.
|
|
68
|
+
*
|
|
69
|
+
* @param options - Hook options (`autoRefresh`), or a signal of them.
|
|
70
|
+
* @returns Auth state as signals and the auth actions.
|
|
71
|
+
*/
|
|
72
|
+
export declare function useAuth<T = unknown, TRegister extends RegisterExtraShape<TRegister> = Record<never, never>>(options?: MaybeSignal<UseAuthOptions>): UseAuthResult<T, TRegister>;
|
|
73
|
+
/**
|
|
74
|
+
* The signed-in user alone. Call it in an injection context.
|
|
75
|
+
*
|
|
76
|
+
* @returns A signal of the authenticated user or `null`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function useUser<T = unknown>(): Signal<T | null>;
|
|
79
|
+
/**
|
|
80
|
+
* Whether a session exists. Call it in an injection context.
|
|
81
|
+
*
|
|
82
|
+
* @returns A signal of the authentication flag.
|
|
83
|
+
*/
|
|
84
|
+
export declare function useIsAuthenticated(): Signal<boolean>;
|
|
85
|
+
//# sourceMappingURL=use-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-auth.d.ts","sourceRoot":"","sources":["../../src/hooks/use-auth.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAwC,KAAK,MAAM,EAAqB,MAAM,eAAe,CAAA;AAEpG,OAAO,KAAK,EACV,UAAU,EACV,UAAU,EACV,eAAe,E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