@tech4good/platform-auth 0.0.0-stage → 0.1.0-alpha.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/EXTRACTION-CHANGES.md +159 -0
- package/FUTURE-WORK.md +73 -0
- package/MIGRATION.md +89 -0
- package/README.md +213 -2
- package/fesm2022/tech4good-platform-auth-firebase.mjs +254 -0
- package/fesm2022/tech4good-platform-auth-firebase.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth-profiles.mjs +72 -0
- package/fesm2022/tech4good-platform-auth-profiles.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth-testing.mjs +198 -0
- package/fesm2022/tech4good-platform-auth-testing.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth.mjs +390 -0
- package/fesm2022/tech4good-platform-auth.mjs.map +1 -0
- package/package.json +45 -3
- package/types/tech4good-platform-auth-firebase.d.ts +99 -0
- package/types/tech4good-platform-auth-firebase.d.ts.map +1 -0
- package/types/tech4good-platform-auth-profiles.d.ts +55 -0
- package/types/tech4good-platform-auth-profiles.d.ts.map +1 -0
- package/types/tech4good-platform-auth-testing.d.ts +87 -0
- package/types/tech4good-platform-auth-testing.d.ts.map +1 -0
- package/types/tech4good-platform-auth.d.ts +164 -0
- package/types/tech4good-platform-auth.d.ts.map +1 -0
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, Injectable, DestroyRef } from '@angular/core';
|
|
3
|
+
import { DOCUMENT } from '@angular/common';
|
|
4
|
+
import { signalStoreFeature, withState, withMethods, patchState } from '@ngrx/signals';
|
|
5
|
+
import { rxMethod } from '@ngrx/signals/rxjs-interop';
|
|
6
|
+
import { BehaviorSubject, firstValueFrom, pipe, EMPTY, of, from } from 'rxjs';
|
|
7
|
+
import { filter, switchMap, catchError } from 'rxjs/operators';
|
|
8
|
+
import { injectLogger } from '@tech4good/platform-logging';
|
|
9
|
+
|
|
10
|
+
const AUTH_ACCESS = new InjectionToken('PlatformAuthAccess');
|
|
11
|
+
const PROFILE_PROVISIONER = new InjectionToken('PlatformProfileProvisioner');
|
|
12
|
+
const AUTH_LIFECYCLE = new InjectionToken('PlatformAuthLifecycle');
|
|
13
|
+
|
|
14
|
+
const PLATFORM_AUTH_OPTIONS = new InjectionToken('PlatformAuthOptions', {
|
|
15
|
+
providedIn: 'root', factory: () => ({}),
|
|
16
|
+
});
|
|
17
|
+
function providePlatformAuth(options = {}) {
|
|
18
|
+
return [{ provide: PLATFORM_AUTH_OPTIONS, useValue: options }];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Manages same-browser context persistence for passwordless email magic link sign-in flows.
|
|
23
|
+
*
|
|
24
|
+
* When a user requests a magic link, Firebase Auth redirects them out of the app to their email client.
|
|
25
|
+
* Upon clicking the link in the email, the user lands back on the `/auth/action` route.
|
|
26
|
+
* To securely process the callback, the application must verify the originating email address,
|
|
27
|
+
* flow type, and originating user UID (for account upgrades/linking).
|
|
28
|
+
*
|
|
29
|
+
* To remain resilient against browser storage restrictions (e.g., Safari ITP, private browsing mode),
|
|
30
|
+
* this service uses a dual-layer strategy:
|
|
31
|
+
* 1. Primary storage in `localStorage`.
|
|
32
|
+
* 2. Fallback in a short-lived (30-minute), `SameSite=Lax` cookie.
|
|
33
|
+
*/
|
|
34
|
+
class EmailLinkContextService {
|
|
35
|
+
document = inject(DOCUMENT);
|
|
36
|
+
options = inject(PLATFORM_AUTH_OPTIONS);
|
|
37
|
+
prefix = this.options.storagePrefix ?? 'app.email-link';
|
|
38
|
+
emailKey = `${this.prefix}.email`;
|
|
39
|
+
flowKey = `${this.prefix}.flow`;
|
|
40
|
+
uidKey = `${this.prefix}.uid`;
|
|
41
|
+
maxAgeSeconds = this.options.emailContextMaxAgeSeconds ?? 30 * 60;
|
|
42
|
+
/**
|
|
43
|
+
* Persists email magic link context into localStorage and fallback cookies before sending the email.
|
|
44
|
+
*
|
|
45
|
+
* @param context The email, flow type, and optional originating UID to store.
|
|
46
|
+
*/
|
|
47
|
+
remember(context) {
|
|
48
|
+
this.set(this.emailKey, context.email);
|
|
49
|
+
this.set(this.flowKey, context.flow);
|
|
50
|
+
if (context.uid)
|
|
51
|
+
this.set(this.uidKey, context.uid);
|
|
52
|
+
else
|
|
53
|
+
this.remove(this.uidKey);
|
|
54
|
+
}
|
|
55
|
+
/** Retrieves the stored target email address, or `null` if not found or expired. */
|
|
56
|
+
getEmail() {
|
|
57
|
+
return this.get(this.emailKey);
|
|
58
|
+
}
|
|
59
|
+
/** Retrieves the stored email link flow type (`sign-in`, `guest-upgrade`, or `link-email`). */
|
|
60
|
+
getFlow() {
|
|
61
|
+
const flow = this.get(this.flowKey);
|
|
62
|
+
return flow === 'sign-in' || flow === 'guest-upgrade' || flow === 'link-email' ? flow : null;
|
|
63
|
+
}
|
|
64
|
+
/** Retrieves the originating UID for account upgrading/linking flows. */
|
|
65
|
+
getUid() {
|
|
66
|
+
return this.get(this.uidKey);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Clears the persisted context if all fields match the completed context.
|
|
70
|
+
*/
|
|
71
|
+
clearIfMatches(context) {
|
|
72
|
+
if (this.getEmail() === context.email &&
|
|
73
|
+
this.getFlow() === context.flow &&
|
|
74
|
+
this.getUid() === context.uid) {
|
|
75
|
+
this.clear();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Clears all stored email link context from both localStorage and cookies. */
|
|
79
|
+
clear() {
|
|
80
|
+
this.remove(this.emailKey);
|
|
81
|
+
this.remove(this.flowKey);
|
|
82
|
+
this.remove(this.uidKey);
|
|
83
|
+
}
|
|
84
|
+
/** Safe getter for `localStorage` that handles SSR or restricted window contexts. */
|
|
85
|
+
get storage() {
|
|
86
|
+
try {
|
|
87
|
+
return this.document.defaultView?.localStorage || null;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Reads a stored value from localStorage with cookie fallback. */
|
|
94
|
+
get(key) {
|
|
95
|
+
try {
|
|
96
|
+
const storedValue = this.storage?.getItem(key);
|
|
97
|
+
if (storedValue)
|
|
98
|
+
return storedValue;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Fall back to the short-lived cookie below.
|
|
102
|
+
}
|
|
103
|
+
return this.getCookie(key);
|
|
104
|
+
}
|
|
105
|
+
/** Writes a value to both localStorage and a short-lived cookie. */
|
|
106
|
+
set(key, value) {
|
|
107
|
+
try {
|
|
108
|
+
this.storage?.setItem(key, value);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// The cookie still preserves the same-browser callback context.
|
|
112
|
+
}
|
|
113
|
+
this.setCookie(key, value);
|
|
114
|
+
}
|
|
115
|
+
/** Removes a key from both localStorage and cookies. */
|
|
116
|
+
remove(key) {
|
|
117
|
+
try {
|
|
118
|
+
this.storage?.removeItem(key);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// The cookie is cleared independently below.
|
|
122
|
+
}
|
|
123
|
+
this.document.cookie = `${encodeURIComponent(key)}=; Path=/; Max-Age=0; SameSite=Lax`;
|
|
124
|
+
}
|
|
125
|
+
/** Reads a cookie by key. */
|
|
126
|
+
getCookie(key) {
|
|
127
|
+
const encodedKey = `${encodeURIComponent(key)}=`;
|
|
128
|
+
const match = this.document.cookie
|
|
129
|
+
.split(';')
|
|
130
|
+
.map((cookie) => cookie.trim())
|
|
131
|
+
.find((cookie) => cookie.startsWith(encodedKey));
|
|
132
|
+
try {
|
|
133
|
+
return match ? decodeURIComponent(match.slice(encodedKey.length)) : null;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return null;
|
|
137
|
+
} // A malformed browser cookie is unavailable context, not a fatal auth error.
|
|
138
|
+
}
|
|
139
|
+
/** Writes a cookie with 30-minute max-age and SameSite=Lax. */
|
|
140
|
+
setCookie(key, value) {
|
|
141
|
+
const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';
|
|
142
|
+
this.document.cookie =
|
|
143
|
+
`${encodeURIComponent(key)}=${encodeURIComponent(value)}; ` +
|
|
144
|
+
`Path=/; Max-Age=${this.maxAgeSeconds}; SameSite=Lax${secure}`;
|
|
145
|
+
}
|
|
146
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: EmailLinkContextService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
147
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: EmailLinkContextService, providedIn: 'root' });
|
|
148
|
+
}
|
|
149
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: EmailLinkContextService, decorators: [{
|
|
150
|
+
type: Injectable,
|
|
151
|
+
args: [{
|
|
152
|
+
providedIn: 'root',
|
|
153
|
+
}]
|
|
154
|
+
}] });
|
|
155
|
+
|
|
156
|
+
const initialState = {
|
|
157
|
+
afUser: null, isLoadingLogin: false, authStatus: 'initializing', authError: null,
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Shared part of an application's root AuthStore. Call loadAuth() once at startup.
|
|
161
|
+
* The app adds its user selector, navigation, guest dialog and lifecycle providers.
|
|
162
|
+
*/
|
|
163
|
+
function withAuthSession() {
|
|
164
|
+
return signalStoreFeature(withState(initialState), withMethods((store, db = inject(AUTH_ACCESS), profiles = inject(PROFILE_PROVISIONER), lifecycle = inject(AUTH_LIFECYCLE)) => {
|
|
165
|
+
const logger = injectLogger('auth');
|
|
166
|
+
const refreshProvisioning = new Set();
|
|
167
|
+
const readiness = new BehaviorSubject({
|
|
168
|
+
status: 'initializing', session: null, error: null,
|
|
169
|
+
});
|
|
170
|
+
let isEndingSession = false;
|
|
171
|
+
let directLogin = false;
|
|
172
|
+
let directProfileUid;
|
|
173
|
+
let observedDuringLogin;
|
|
174
|
+
let ending = null;
|
|
175
|
+
// Only auth work uses this counter. Ordinary domain loads are allowed to finish.
|
|
176
|
+
let sessionGeneration = 0;
|
|
177
|
+
let pendingLogin = null;
|
|
178
|
+
inject(DestroyRef).onDestroy(() => { sessionGeneration++; readiness.complete(); });
|
|
179
|
+
function publish(session, status, error = null) {
|
|
180
|
+
patchState(store, { afUser: session, authStatus: status, authError: error });
|
|
181
|
+
readiness.next({ session, status, error });
|
|
182
|
+
}
|
|
183
|
+
function acceptIdentity(session) {
|
|
184
|
+
if (store.afUser()?.uid !== session?.uid) {
|
|
185
|
+
sessionGeneration++;
|
|
186
|
+
if (store.afUser())
|
|
187
|
+
lifecycle.clearSessionState();
|
|
188
|
+
}
|
|
189
|
+
publish(session, session ? 'loading-profile' : 'signed-out');
|
|
190
|
+
return sessionGeneration;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Provisions a user profile (if it doesn't exist yet), loads it into the
|
|
194
|
+
* application's UserStore, and starts a real-time stream for updates.
|
|
195
|
+
*
|
|
196
|
+
* Both direct login methods (loginAnonymously, signInWithGoogle, etc.) and
|
|
197
|
+
* the reactive loadAuth pipeline reuse this same sequence. If another UID
|
|
198
|
+
* signs in while a profile request is pending, its old completion must not
|
|
199
|
+
* reopen an auth stream or publish the previous user as ready.
|
|
200
|
+
*/
|
|
201
|
+
async function provisionAndLoadUser(session, generation) {
|
|
202
|
+
await profiles.ensureUserProfile(session);
|
|
203
|
+
if (generation !== sessionGeneration)
|
|
204
|
+
return;
|
|
205
|
+
await lifecycle.loadProfile(session);
|
|
206
|
+
if (generation !== sessionGeneration)
|
|
207
|
+
return;
|
|
208
|
+
lifecycle.streamProfile(session);
|
|
209
|
+
publish(session, 'ready');
|
|
210
|
+
}
|
|
211
|
+
function trackRefreshProvisioning(session) {
|
|
212
|
+
const generation = acceptIdentity(session);
|
|
213
|
+
const provisioning = provisionAndLoadUser(session, generation).catch(error => {
|
|
214
|
+
if (generation === sessionGeneration)
|
|
215
|
+
publish(session, 'error', error);
|
|
216
|
+
throw error;
|
|
217
|
+
});
|
|
218
|
+
refreshProvisioning.add(provisioning);
|
|
219
|
+
void provisioning.then(() => refreshProvisioning.delete(provisioning), () => refreshProvisioning.delete(provisioning));
|
|
220
|
+
return provisioning;
|
|
221
|
+
}
|
|
222
|
+
async function awaitRefreshProvisioning() {
|
|
223
|
+
if (pendingLogin)
|
|
224
|
+
await Promise.allSettled([pendingLogin]);
|
|
225
|
+
while (refreshProvisioning.size)
|
|
226
|
+
await Promise.allSettled([...refreshProvisioning]);
|
|
227
|
+
}
|
|
228
|
+
/** Keep SDK notifications from provisioning a second copy of an explicit login. */
|
|
229
|
+
async function login(operation) {
|
|
230
|
+
if (directLogin || isEndingSession)
|
|
231
|
+
throw new Error('Another auth operation is in progress.');
|
|
232
|
+
directLogin = true;
|
|
233
|
+
observedDuringLogin = undefined;
|
|
234
|
+
patchState(store, { isLoadingLogin: true });
|
|
235
|
+
const work = (async () => {
|
|
236
|
+
const session = await operation();
|
|
237
|
+
directProfileUid = session.uid;
|
|
238
|
+
await trackRefreshProvisioning(session);
|
|
239
|
+
if (store.afUser()?.uid !== session.uid) {
|
|
240
|
+
throw new Error('The authenticated account changed while its profile was loading.');
|
|
241
|
+
}
|
|
242
|
+
return session;
|
|
243
|
+
})();
|
|
244
|
+
pendingLogin = work;
|
|
245
|
+
try {
|
|
246
|
+
return await work;
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
// The SDK can establish identity, then reject token refresh. Preserve
|
|
250
|
+
// that observed identity for error/retry without provisioning early.
|
|
251
|
+
// The observer callback can change this value while the SDK promise is pending.
|
|
252
|
+
const observed = observedDuringLogin;
|
|
253
|
+
if (directProfileUid === undefined && observed !== undefined &&
|
|
254
|
+
observed?.uid !== store.afUser()?.uid) {
|
|
255
|
+
acceptIdentity(observed);
|
|
256
|
+
if (observed)
|
|
257
|
+
publish(observed, 'error', error);
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
pendingLogin = null;
|
|
263
|
+
directLogin = false;
|
|
264
|
+
directProfileUid = undefined;
|
|
265
|
+
patchState(store, { isLoadingLogin: false });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async function endSession(deleteAccount) {
|
|
269
|
+
isEndingSession = true;
|
|
270
|
+
try {
|
|
271
|
+
await awaitRefreshProvisioning();
|
|
272
|
+
// End data subscriptions before credentials change; keep domain records cached.
|
|
273
|
+
lifecycle.clearSessionState();
|
|
274
|
+
sessionGeneration++;
|
|
275
|
+
if (deleteAccount)
|
|
276
|
+
await lifecycle.deleteAnonymousAccount();
|
|
277
|
+
// Deleting an Auth user on the server does not immediately clear the
|
|
278
|
+
// browser session. Sign out before the app navigates to its landing page.
|
|
279
|
+
await db.logout();
|
|
280
|
+
publish(null, 'signed-out');
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
publish(store.afUser(), 'error', error);
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
isEndingSession = false;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function requestEndSession(deleteAccount) {
|
|
291
|
+
// Every caller must await the same teardown, including repeated clicks.
|
|
292
|
+
if (!ending)
|
|
293
|
+
ending = endSession(deleteAccount).finally(() => { ending = null; });
|
|
294
|
+
return ending;
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
loadAuth: rxMethod(pipe(
|
|
298
|
+
// 1. Listen for changes in the authenticated user. This emits on a
|
|
299
|
+
// restored session as well as when the user logs in or out.
|
|
300
|
+
switchMap(() => db.afUser().pipe(catchError(error => {
|
|
301
|
+
publish(store.afUser(), 'error', error);
|
|
302
|
+
logger.error('Authentication listener failed', error);
|
|
303
|
+
return EMPTY;
|
|
304
|
+
}))),
|
|
305
|
+
// 2. This reactive path primarily handles page refresh and restored
|
|
306
|
+
// authentication. Fresh login methods provision directly after the
|
|
307
|
+
// Firebase adapter has completed sign-in and refreshed its ID token.
|
|
308
|
+
// Ignore this listener while that direct flow is in progress: Angular
|
|
309
|
+
// Fire can publish the auth-state change before Firestore has applied
|
|
310
|
+
// the new credentials, so duplicate provisioning here can be denied.
|
|
311
|
+
//
|
|
312
|
+
// This preserves the original protection against the race where an
|
|
313
|
+
// auth notification precedes Firestore's CredentialsProvider processing
|
|
314
|
+
// the new token ("Missing or insufficient permissions" on fresh login).
|
|
315
|
+
switchMap(session => {
|
|
316
|
+
if (directLogin)
|
|
317
|
+
observedDuringLogin = session;
|
|
318
|
+
if (isEndingSession)
|
|
319
|
+
return EMPTY;
|
|
320
|
+
if (directLogin && (directProfileUid === undefined || session?.uid === directProfileUid))
|
|
321
|
+
return EMPTY;
|
|
322
|
+
// Once explicit login is provisioning, a different UID or external
|
|
323
|
+
// signout must invalidate that pending auth work too.
|
|
324
|
+
if (!session) {
|
|
325
|
+
acceptIdentity(null);
|
|
326
|
+
return of(null);
|
|
327
|
+
}
|
|
328
|
+
return from(trackRefreshProvisioning(session)).pipe(catchError(error => {
|
|
329
|
+
logger.error('User profile could not be loaded', error);
|
|
330
|
+
return EMPTY; // Keep listening; retryProfile() can also retry this identity.
|
|
331
|
+
}));
|
|
332
|
+
}))),
|
|
333
|
+
async signInWithGoogle() {
|
|
334
|
+
// Provision directly after the adapter has completed auth/token refresh.
|
|
335
|
+
await login(() => db.signInWithGoogle());
|
|
336
|
+
},
|
|
337
|
+
async loginAnonymously() {
|
|
338
|
+
// Avoid provisioning from the earlier reactive anonymous-auth notification.
|
|
339
|
+
await login(() => db.signInAnonymously());
|
|
340
|
+
},
|
|
341
|
+
async linkGoogle() {
|
|
342
|
+
// Re-provision after linking to update generated names and Google photos.
|
|
343
|
+
await login(() => db.linkGoogle());
|
|
344
|
+
},
|
|
345
|
+
async sendEmailSignInLink(email) {
|
|
346
|
+
patchState(store, { isLoadingLogin: true });
|
|
347
|
+
try {
|
|
348
|
+
await db.sendEmailSignInLink(email);
|
|
349
|
+
}
|
|
350
|
+
finally {
|
|
351
|
+
patchState(store, { isLoadingLogin: false });
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
async sendEmailLinkForCurrentAccount() { await db.sendEmailLinkForCurrentAccount(); },
|
|
355
|
+
getStoredEmailForEmailLink() { return db.getStoredEmailForEmailLink(); },
|
|
356
|
+
async completeEmailSignInLink(url, email) {
|
|
357
|
+
return login(() => db.completeEmailSignInLink(url, email));
|
|
358
|
+
},
|
|
359
|
+
async retryProfile() {
|
|
360
|
+
const session = store.afUser();
|
|
361
|
+
if (!session)
|
|
362
|
+
throw new Error('There is no authenticated identity to provision.');
|
|
363
|
+
if (isEndingSession || directLogin)
|
|
364
|
+
throw new Error('Another auth operation is in progress.');
|
|
365
|
+
await trackRefreshProvisioning(session);
|
|
366
|
+
},
|
|
367
|
+
/** Resolve only after profile loading succeeds; reject instead of hanging on failure. */
|
|
368
|
+
async whenReady() {
|
|
369
|
+
const result = await firstValueFrom(readiness.pipe(filter(value => value.status === 'ready' || value.status === 'signed-out' || value.status === 'error')));
|
|
370
|
+
if (result.status === 'error')
|
|
371
|
+
throw result.error;
|
|
372
|
+
return result.session;
|
|
373
|
+
},
|
|
374
|
+
clearSessionState() { lifecycle.clearSessionState(); },
|
|
375
|
+
async signOut() { await requestEndSession(false); },
|
|
376
|
+
async deleteGuestAccount() {
|
|
377
|
+
if (!store.afUser()?.isAnonymous)
|
|
378
|
+
throw new Error('The current account is not anonymous.');
|
|
379
|
+
await requestEndSession(true);
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
}));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Generated bundle index. Do not edit.
|
|
387
|
+
*/
|
|
388
|
+
|
|
389
|
+
export { AUTH_ACCESS, AUTH_LIFECYCLE, EmailLinkContextService, PLATFORM_AUTH_OPTIONS, PROFILE_PROVISIONER, providePlatformAuth, withAuthSession };
|
|
390
|
+
//# sourceMappingURL=tech4good-platform-auth.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-auth.mjs","sources":["../../src/auth-access.ts","../../src/config.ts","../../src/email-link-context.ts","../../src/auth-session.ts","../../src/tech4good-platform-auth.ts"],"sourcesContent":["import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\n\n/** Normalized authentication identity, independent of any backend SDK. */\nexport interface AuthSession {\n uid: string;\n email: string | null;\n displayName: string | null;\n photoURL: string | null;\n isAnonymous: boolean;\n emailVerified: boolean;\n emailLinkEnabled: boolean;\n providerIds: string[];\n}\n\n/** Auth operations used by the current lab apps. Firebase-specific objects stay in the adapter. */\nexport interface AuthAccess {\n afUser(): Observable<AuthSession | null>;\n signInWithGoogle(): Promise<AuthSession>;\n signInAnonymously(): Promise<AuthSession>;\n linkGoogle(): Promise<AuthSession>;\n sendEmailSignInLink(email: string): Promise<void>;\n sendEmailLinkForCurrentAccount(): Promise<void>;\n getStoredEmailForEmailLink(): string | null;\n completeEmailSignInLink(url: string, email: string): Promise<AuthSession>;\n logout(): Promise<void>;\n}\nexport const AUTH_ACCESS = new InjectionToken<AuthAccess>('PlatformAuthAccess');\n\n/** Every ready authenticated session must have an application profile. */\nexport interface ProfileProvisioner {\n ensureUserProfile(session: AuthSession): Promise<unknown>;\n}\nexport const PROFILE_PROVISIONER = new InjectionToken<ProfileProvisioner>('PlatformProfileProvisioner');\n\n/** App-owned integration, not a registry of all domain stores. */\nexport interface AuthLifecycle {\n loadProfile(session: AuthSession): Promise<void>;\n streamProfile(session: AuthSession): void;\n /** Stop global listeners; reset explicitly selected auth/profile stores and their history. */\n clearSessionState(): void;\n /** Delete app-owned guest records and the account. The app supplies its deletion graph. */\n deleteAnonymousAccount(): Promise<void>;\n}\nexport const AUTH_LIFECYCLE = new InjectionToken<AuthLifecycle>('PlatformAuthLifecycle');\n","import { InjectionToken, Provider } from '@angular/core';\n\nexport interface PlatformAuthOptions {\n /** Browser callback path or absolute URL; app routing remains app-owned. */\n emailActionUrl?: string;\n /** Existing applications retain app.email-link.* storage keys by default. */\n storagePrefix?: string;\n /** Cookie fallback lifetime; localStorage retains the original persistent behavior. */\n emailContextMaxAgeSeconds?: number;\n}\nexport const PLATFORM_AUTH_OPTIONS = new InjectionToken<PlatformAuthOptions>('PlatformAuthOptions', {\n providedIn: 'root', factory: () => ({}),\n});\nexport function providePlatformAuth(options: PlatformAuthOptions = {}): Provider[] {\n return [{ provide: PLATFORM_AUTH_OPTIONS, useValue: options }];\n}\n","import { DOCUMENT } from '@angular/common';\nimport { Injectable, inject } from '@angular/core';\nimport { PLATFORM_AUTH_OPTIONS } from './config';\n\n/** Supported email magic link authentication workflows. */\nexport type EmailLinkFlow = 'sign-in' | 'guest-upgrade' | 'link-email';\n\n/**\n * Encapsulates the same-browser state required to complete an email link authentication request.\n */\nexport type EmailLinkContext = {\n /** The target email address the magic link was sent to. */\n email: string;\n /** The intended authentication workflow. */\n flow: EmailLinkFlow;\n /** The current user's Firebase UID if upgrading a guest or linking email to an existing account. */\n uid: string | null;\n};\n\n/**\n * Manages same-browser context persistence for passwordless email magic link sign-in flows.\n *\n * When a user requests a magic link, Firebase Auth redirects them out of the app to their email client.\n * Upon clicking the link in the email, the user lands back on the `/auth/action` route.\n * To securely process the callback, the application must verify the originating email address,\n * flow type, and originating user UID (for account upgrades/linking).\n *\n * To remain resilient against browser storage restrictions (e.g., Safari ITP, private browsing mode),\n * this service uses a dual-layer strategy:\n * 1. Primary storage in `localStorage`.\n * 2. Fallback in a short-lived (30-minute), `SameSite=Lax` cookie.\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class EmailLinkContextService {\n private readonly document = inject(DOCUMENT);\n private readonly options = inject(PLATFORM_AUTH_OPTIONS);\n private readonly prefix = this.options.storagePrefix ?? 'app.email-link';\n private readonly emailKey = `${this.prefix}.email`;\n private readonly flowKey = `${this.prefix}.flow`;\n private readonly uidKey = `${this.prefix}.uid`;\n private readonly maxAgeSeconds = this.options.emailContextMaxAgeSeconds ?? 30 * 60;\n\n /**\n * Persists email magic link context into localStorage and fallback cookies before sending the email.\n *\n * @param context The email, flow type, and optional originating UID to store.\n */\n remember(context: EmailLinkContext): void {\n this.set(this.emailKey, context.email);\n this.set(this.flowKey, context.flow);\n if (context.uid) this.set(this.uidKey, context.uid);\n else this.remove(this.uidKey);\n }\n\n /** Retrieves the stored target email address, or `null` if not found or expired. */\n getEmail(): string | null {\n return this.get(this.emailKey);\n }\n\n /** Retrieves the stored email link flow type (`sign-in`, `guest-upgrade`, or `link-email`). */\n getFlow(): EmailLinkFlow | null {\n const flow = this.get(this.flowKey);\n return flow === 'sign-in' || flow === 'guest-upgrade' || flow === 'link-email' ? flow : null;\n }\n\n /** Retrieves the originating UID for account upgrading/linking flows. */\n getUid(): string | null {\n return this.get(this.uidKey);\n }\n\n /**\n * Clears the persisted context if all fields match the completed context.\n */\n clearIfMatches(context: EmailLinkContext): void {\n if (\n this.getEmail() === context.email &&\n this.getFlow() === context.flow &&\n this.getUid() === context.uid\n ) {\n this.clear();\n }\n }\n\n /** Clears all stored email link context from both localStorage and cookies. */\n clear(): void {\n this.remove(this.emailKey);\n this.remove(this.flowKey);\n this.remove(this.uidKey);\n }\n\n /** Safe getter for `localStorage` that handles SSR or restricted window contexts. */\n private get storage(): Storage | null {\n try {\n return this.document.defaultView?.localStorage || null;\n } catch {\n return null;\n }\n }\n\n /** Reads a stored value from localStorage with cookie fallback. */\n private get(key: string): string | null {\n try {\n const storedValue = this.storage?.getItem(key);\n if (storedValue) return storedValue;\n } catch {\n // Fall back to the short-lived cookie below.\n }\n return this.getCookie(key);\n }\n\n /** Writes a value to both localStorage and a short-lived cookie. */\n private set(key: string, value: string): void {\n try {\n this.storage?.setItem(key, value);\n } catch {\n // The cookie still preserves the same-browser callback context.\n }\n this.setCookie(key, value);\n }\n\n /** Removes a key from both localStorage and cookies. */\n private remove(key: string): void {\n try {\n this.storage?.removeItem(key);\n } catch {\n // The cookie is cleared independently below.\n }\n this.document.cookie = `${encodeURIComponent(key)}=; Path=/; Max-Age=0; SameSite=Lax`;\n }\n\n /** Reads a cookie by key. */\n private getCookie(key: string): string | null {\n const encodedKey = `${encodeURIComponent(key)}=`;\n const match = this.document.cookie\n .split(';')\n .map((cookie) => cookie.trim())\n .find((cookie) => cookie.startsWith(encodedKey));\n try { return match ? decodeURIComponent(match.slice(encodedKey.length)) : null; }\n catch { return null; } // A malformed browser cookie is unavailable context, not a fatal auth error.\n }\n\n /** Writes a cookie with 30-minute max-age and SameSite=Lax. */\n private setCookie(key: string, value: string): void {\n const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';\n this.document.cookie =\n `${encodeURIComponent(key)}=${encodeURIComponent(value)}; ` +\n `Path=/; Max-Age=${this.maxAgeSeconds}; SameSite=Lax${secure}`;\n }\n}\n","import { DestroyRef, inject } from '@angular/core';\nimport { patchState, signalStoreFeature, withMethods, withState } from '@ngrx/signals';\nimport { rxMethod } from '@ngrx/signals/rxjs-interop';\nimport { BehaviorSubject, EMPTY, firstValueFrom, from, of, pipe } from 'rxjs';\nimport { catchError, filter, switchMap } from 'rxjs/operators';\nimport { injectLogger } from '@tech4good/platform-logging';\nimport { AUTH_ACCESS, AUTH_LIFECYCLE, AuthSession, PROFILE_PROVISIONER } from './auth-access';\n\nexport type AuthStatus = 'initializing' | 'signed-out' | 'loading-profile' | 'ready' | 'error';\nexport interface AuthState {\n afUser: AuthSession | null;\n isLoadingLogin: boolean;\n authStatus: AuthStatus;\n authError: unknown | null;\n}\nconst initialState: AuthState = {\n afUser: null, isLoadingLogin: false, authStatus: 'initializing', authError: null,\n};\n\n/**\n * Shared part of an application's root AuthStore. Call loadAuth() once at startup.\n * The app adds its user selector, navigation, guest dialog and lifecycle providers.\n */\nexport function withAuthSession() {\n return signalStoreFeature(\n withState(initialState),\n withMethods((store, db = inject(AUTH_ACCESS), profiles = inject(PROFILE_PROVISIONER), lifecycle = inject(AUTH_LIFECYCLE)) => {\n const logger = injectLogger('auth');\n const refreshProvisioning = new Set<Promise<void>>();\n const readiness = new BehaviorSubject<{ status: AuthStatus; session: AuthSession | null; error: unknown }>({\n status: 'initializing', session: null, error: null,\n });\n let isEndingSession = false;\n let directLogin = false;\n let directProfileUid: string | undefined;\n let observedDuringLogin: AuthSession | null | undefined;\n let ending: Promise<void> | null = null;\n // Only auth work uses this counter. Ordinary domain loads are allowed to finish.\n let sessionGeneration = 0;\n let pendingLogin: Promise<AuthSession> | null = null;\n inject(DestroyRef).onDestroy(() => { sessionGeneration++; readiness.complete(); });\n\n function publish(session: AuthSession | null, status: AuthStatus, error: unknown = null): void {\n patchState(store, { afUser: session, authStatus: status, authError: error });\n readiness.next({ session, status, error });\n }\n\n function acceptIdentity(session: AuthSession | null): number {\n if (store.afUser()?.uid !== session?.uid) {\n sessionGeneration++;\n if (store.afUser()) lifecycle.clearSessionState();\n }\n publish(session, session ? 'loading-profile' : 'signed-out');\n return sessionGeneration;\n }\n\n /**\n * Provisions a user profile (if it doesn't exist yet), loads it into the\n * application's UserStore, and starts a real-time stream for updates.\n *\n * Both direct login methods (loginAnonymously, signInWithGoogle, etc.) and\n * the reactive loadAuth pipeline reuse this same sequence. If another UID\n * signs in while a profile request is pending, its old completion must not\n * reopen an auth stream or publish the previous user as ready.\n */\n async function provisionAndLoadUser(session: AuthSession, generation: number): Promise<void> {\n await profiles.ensureUserProfile(session);\n if (generation !== sessionGeneration) return;\n await lifecycle.loadProfile(session);\n if (generation !== sessionGeneration) return;\n lifecycle.streamProfile(session);\n publish(session, 'ready');\n }\n\n function trackRefreshProvisioning(session: AuthSession): Promise<void> {\n const generation = acceptIdentity(session);\n const provisioning = provisionAndLoadUser(session, generation).catch(error => {\n if (generation === sessionGeneration) publish(session, 'error', error);\n throw error;\n });\n refreshProvisioning.add(provisioning);\n void provisioning.then(\n () => refreshProvisioning.delete(provisioning),\n () => refreshProvisioning.delete(provisioning),\n );\n return provisioning;\n }\n\n async function awaitRefreshProvisioning(): Promise<void> {\n if (pendingLogin) await Promise.allSettled([pendingLogin]);\n while (refreshProvisioning.size) await Promise.allSettled([...refreshProvisioning]);\n }\n\n /** Keep SDK notifications from provisioning a second copy of an explicit login. */\n async function login(operation: () => Promise<AuthSession>): Promise<AuthSession> {\n if (directLogin || isEndingSession) throw new Error('Another auth operation is in progress.');\n directLogin = true;\n observedDuringLogin = undefined;\n patchState(store, { isLoadingLogin: true });\n const work = (async () => {\n const session = await operation();\n directProfileUid = session.uid;\n await trackRefreshProvisioning(session);\n if (store.afUser()?.uid !== session.uid) {\n throw new Error('The authenticated account changed while its profile was loading.');\n }\n return session;\n })();\n pendingLogin = work;\n try { return await work; }\n catch (error) {\n // The SDK can establish identity, then reject token refresh. Preserve\n // that observed identity for error/retry without provisioning early.\n // The observer callback can change this value while the SDK promise is pending.\n const observed = observedDuringLogin as AuthSession | null | undefined;\n if (directProfileUid === undefined && observed !== undefined &&\n observed?.uid !== store.afUser()?.uid) {\n acceptIdentity(observed);\n if (observed) publish(observed, 'error', error);\n }\n throw error;\n } finally {\n pendingLogin = null;\n directLogin = false;\n directProfileUid = undefined;\n patchState(store, { isLoadingLogin: false });\n }\n }\n\n async function endSession(deleteAccount: boolean): Promise<void> {\n isEndingSession = true;\n try {\n await awaitRefreshProvisioning();\n // End data subscriptions before credentials change; keep domain records cached.\n lifecycle.clearSessionState();\n sessionGeneration++;\n if (deleteAccount) await lifecycle.deleteAnonymousAccount();\n // Deleting an Auth user on the server does not immediately clear the\n // browser session. Sign out before the app navigates to its landing page.\n await db.logout();\n publish(null, 'signed-out');\n } catch (error) {\n publish(store.afUser(), 'error', error);\n throw error;\n } finally { isEndingSession = false; }\n }\n\n function requestEndSession(deleteAccount: boolean): Promise<void> {\n // Every caller must await the same teardown, including repeated clicks.\n if (!ending) ending = endSession(deleteAccount).finally(() => { ending = null; });\n return ending;\n }\n\n return {\n loadAuth: rxMethod<void>(pipe(\n // 1. Listen for changes in the authenticated user. This emits on a\n // restored session as well as when the user logs in or out.\n switchMap(() => db.afUser().pipe(catchError(error => {\n publish(store.afUser(), 'error', error);\n logger.error('Authentication listener failed', error);\n return EMPTY;\n }))),\n // 2. This reactive path primarily handles page refresh and restored\n // authentication. Fresh login methods provision directly after the\n // Firebase adapter has completed sign-in and refreshed its ID token.\n // Ignore this listener while that direct flow is in progress: Angular\n // Fire can publish the auth-state change before Firestore has applied\n // the new credentials, so duplicate provisioning here can be denied.\n //\n // This preserves the original protection against the race where an\n // auth notification precedes Firestore's CredentialsProvider processing\n // the new token (\"Missing or insufficient permissions\" on fresh login).\n switchMap(session => {\n if (directLogin) observedDuringLogin = session;\n if (isEndingSession) return EMPTY;\n if (directLogin && (directProfileUid === undefined || session?.uid === directProfileUid)) return EMPTY;\n // Once explicit login is provisioning, a different UID or external\n // signout must invalidate that pending auth work too.\n if (!session) { acceptIdentity(null); return of(null); }\n return from(trackRefreshProvisioning(session)).pipe(catchError(error => {\n logger.error('User profile could not be loaded', error);\n return EMPTY; // Keep listening; retryProfile() can also retry this identity.\n }));\n }),\n )),\n async signInWithGoogle(): Promise<void> {\n // Provision directly after the adapter has completed auth/token refresh.\n await login(() => db.signInWithGoogle());\n },\n async loginAnonymously(): Promise<void> {\n // Avoid provisioning from the earlier reactive anonymous-auth notification.\n await login(() => db.signInAnonymously());\n },\n async linkGoogle(): Promise<void> {\n // Re-provision after linking to update generated names and Google photos.\n await login(() => db.linkGoogle());\n },\n async sendEmailSignInLink(email: string): Promise<void> {\n patchState(store, { isLoadingLogin: true });\n try { await db.sendEmailSignInLink(email); }\n finally { patchState(store, { isLoadingLogin: false }); }\n },\n async sendEmailLinkForCurrentAccount(): Promise<void> { await db.sendEmailLinkForCurrentAccount(); },\n getStoredEmailForEmailLink(): string | null { return db.getStoredEmailForEmailLink(); },\n async completeEmailSignInLink(url: string, email: string): Promise<AuthSession> {\n return login(() => db.completeEmailSignInLink(url, email));\n },\n async retryProfile(): Promise<void> {\n const session = store.afUser();\n if (!session) throw new Error('There is no authenticated identity to provision.');\n if (isEndingSession || directLogin) throw new Error('Another auth operation is in progress.');\n await trackRefreshProvisioning(session);\n },\n /** Resolve only after profile loading succeeds; reject instead of hanging on failure. */\n async whenReady(): Promise<AuthSession | null> {\n const result = await firstValueFrom(readiness.pipe(filter(value =>\n value.status === 'ready' || value.status === 'signed-out' || value.status === 'error')));\n if (result.status === 'error') throw result.error;\n return result.session;\n },\n clearSessionState(): void { lifecycle.clearSessionState(); },\n async signOut(): Promise<void> { await requestEndSession(false); },\n async deleteGuestAccount(): Promise<void> {\n if (!store.afUser()?.isAnonymous) throw new Error('The current account is not anonymous.');\n await requestEndSession(true);\n },\n };\n }),\n );\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;;MA2Ba,WAAW,GAAG,IAAI,cAAc,CAAa,oBAAoB;MAMjE,mBAAmB,GAAG,IAAI,cAAc,CAAqB,4BAA4B;MAWzF,cAAc,GAAG,IAAI,cAAc,CAAgB,uBAAuB;;MClC1E,qBAAqB,GAAG,IAAI,cAAc,CAAsB,qBAAqB,EAAE;IAClG,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AACxC,CAAA;AACK,SAAU,mBAAmB,CAAC,OAAA,GAA+B,EAAE,EAAA;IACnE,OAAO,CAAC,EAAE,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAChE;;ACIA;;;;;;;;;;;;AAYG;MAIU,uBAAuB,CAAA;AACjB,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC3B,IAAA,OAAO,GAAG,MAAM,CAAC,qBAAqB,CAAC;IACvC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,IAAI,gBAAgB;AACvD,IAAA,QAAQ,GAAG,CAAA,EAAG,IAAI,CAAC,MAAM,QAAQ;AACjC,IAAA,OAAO,GAAG,CAAA,EAAG,IAAI,CAAC,MAAM,OAAO;AAC/B,IAAA,MAAM,GAAG,CAAA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A,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,WAAW;AAAE,oBAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;AAC1F,gBAAA,MAAM,iBAAiB,CAAC,IAAI,CAAC;YAC/B,CAAC;SACF;IACH,CAAC,CAAC,CACH;AACH;;ACrOA;;AAEG;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tech4good/platform-auth",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Shared authentication, profile assurance and session coordination for Tech4Good Angular applications.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"@angular/common": "^21.0.0",
|
|
9
|
+
"@angular/core": "^21.0.0",
|
|
10
|
+
"@ngrx/signals": "^21.0.0",
|
|
11
|
+
"@tech4good/platform-data": "0.1.0-alpha.0",
|
|
12
|
+
"@tech4good/platform-logging": "0.1.0-alpha.0",
|
|
13
|
+
"firebase": "^12.0.0",
|
|
14
|
+
"rxjs": "^7.8.0"
|
|
15
|
+
},
|
|
16
|
+
"peerDependenciesMeta": {
|
|
17
|
+
"firebase": {
|
|
18
|
+
"optional": true
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"tslib": "^2.3.0"
|
|
23
|
+
},
|
|
24
|
+
"module": "fesm2022/tech4good-platform-auth.mjs",
|
|
25
|
+
"typings": "types/tech4good-platform-auth.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
"./package.json": {
|
|
28
|
+
"default": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./types/tech4good-platform-auth.d.ts",
|
|
32
|
+
"default": "./fesm2022/tech4good-platform-auth.mjs"
|
|
33
|
+
},
|
|
34
|
+
"./firebase": {
|
|
35
|
+
"types": "./types/tech4good-platform-auth-firebase.d.ts",
|
|
36
|
+
"default": "./fesm2022/tech4good-platform-auth-firebase.mjs"
|
|
37
|
+
},
|
|
38
|
+
"./profiles": {
|
|
39
|
+
"types": "./types/tech4good-platform-auth-profiles.d.ts",
|
|
40
|
+
"default": "./fesm2022/tech4good-platform-auth-profiles.mjs"
|
|
41
|
+
},
|
|
42
|
+
"./testing": {
|
|
43
|
+
"types": "./types/tech4good-platform-auth-testing.d.ts",
|
|
44
|
+
"default": "./fesm2022/tech4good-platform-auth-testing.mjs"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"type": "module"
|
|
6
48
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, Provider } from '@angular/core';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { Auth, User } from 'firebase/auth';
|
|
5
|
+
import { AuthAccess, AuthSession } from '@tech4good/platform-auth';
|
|
6
|
+
import { ProfilePersistence, ProfileRecord, ProfileChanges } from '@tech4good/platform-auth/profiles';
|
|
7
|
+
|
|
8
|
+
/** The application initializes Firebase Auth and chooses its persistence/emulator. */
|
|
9
|
+
declare const PLATFORM_FIREBASE_AUTH: InjectionToken<Auth>;
|
|
10
|
+
type FirebaseAuthUser = Pick<User, 'uid' | 'email' | 'displayName' | 'photoURL' | 'isAnonymous' | 'emailVerified' | 'providerData'>;
|
|
11
|
+
/**
|
|
12
|
+
* Maps a Firebase Auth `User` instance (or subset) into the application's normalized `AuthSession` model.
|
|
13
|
+
*
|
|
14
|
+
* Checks both top-level Firebase `User` properties and `providerData` entries to resolve
|
|
15
|
+
* available display names, profile avatars, verified email addresses, and enabled sign-in providers.
|
|
16
|
+
*
|
|
17
|
+
* @param currentUser The raw Firebase Auth user object.
|
|
18
|
+
* @returns A normalized `AuthSession` instance for state stores and guards.
|
|
19
|
+
*/
|
|
20
|
+
declare function firebaseUserToAuthSession(currentUser: FirebaseAuthUser): AuthSession;
|
|
21
|
+
/** Firebase authentication operations extracted from the original FirebaseService. */
|
|
22
|
+
declare class FirebaseAuthService implements AuthAccess {
|
|
23
|
+
private afAuth;
|
|
24
|
+
private document;
|
|
25
|
+
private options;
|
|
26
|
+
private emailLinkContext;
|
|
27
|
+
private user$;
|
|
28
|
+
/**
|
|
29
|
+
* Returns an observable stream emitting the current `AuthSession` whenever Firebase authentication state changes.
|
|
30
|
+
* Emits `null` when signed out.
|
|
31
|
+
*/
|
|
32
|
+
afUser(): Observable<AuthSession | null>;
|
|
33
|
+
/**
|
|
34
|
+
* Signs in a user via Google OAuth popup and returns the mapped `AuthSession`.
|
|
35
|
+
*
|
|
36
|
+
* Forces token initialization before Firestore provisioning to avoid a fresh-login credentials race.
|
|
37
|
+
*/
|
|
38
|
+
signInWithGoogle(): Promise<AuthSession>;
|
|
39
|
+
/**
|
|
40
|
+
* Creates an anonymous Firebase Auth session.
|
|
41
|
+
*
|
|
42
|
+
* Forces ID token initialization immediately after creation to prevent race conditions
|
|
43
|
+
* with Firestore security rules on fresh sign-ins (especially after deleting a previous guest account).
|
|
44
|
+
*/
|
|
45
|
+
signInAnonymously(): Promise<AuthSession>;
|
|
46
|
+
/**
|
|
47
|
+
* Links a Google identity to the currently signed-in Firebase user without changing their UID.
|
|
48
|
+
* Preserves existing guest/application data under the current UID.
|
|
49
|
+
*/
|
|
50
|
+
linkGoogle(): Promise<AuthSession>;
|
|
51
|
+
/**
|
|
52
|
+
* Dispatches a passwordless email magic link for sign-in or guest upgrading.
|
|
53
|
+
*
|
|
54
|
+
* Saves flow context into `EmailLinkContextService` before sending the email.
|
|
55
|
+
*
|
|
56
|
+
* @param email The destination email address.
|
|
57
|
+
*/
|
|
58
|
+
sendEmailSignInLink(email: string): Promise<void>;
|
|
59
|
+
/**
|
|
60
|
+
* Dispatches a passwordless email magic link to attach email-link sign-in to an existing account.
|
|
61
|
+
*/
|
|
62
|
+
sendEmailLinkForCurrentAccount(): Promise<void>;
|
|
63
|
+
/** Retrieves any stored email magic link email address from `EmailLinkContextService`. */
|
|
64
|
+
getStoredEmailForEmailLink(): string | null;
|
|
65
|
+
/**
|
|
66
|
+
* Verifies the magic link URL and completes authentication or account linking.
|
|
67
|
+
*
|
|
68
|
+
* - Handles `sign-in`, `guest-upgrade`, and `link-email` workflows.
|
|
69
|
+
* - Enforces same-browser UID validation for upgrade and link flows.
|
|
70
|
+
* - Refreshes the Firebase token and clears stored magic link context upon completion.
|
|
71
|
+
*
|
|
72
|
+
* @param url The full callback URL (containing action code parameters).
|
|
73
|
+
* @param email The target email address.
|
|
74
|
+
* @returns The updated `AuthSession`.
|
|
75
|
+
*/
|
|
76
|
+
completeEmailSignInLink(url: string, email: string): Promise<AuthSession>;
|
|
77
|
+
/** Signs out the current Firebase user. */
|
|
78
|
+
logout(): Promise<void>;
|
|
79
|
+
private actionCodeSettings;
|
|
80
|
+
private sendEmailLink;
|
|
81
|
+
private getEmailLinkFlow;
|
|
82
|
+
private clearEmailLinkContext;
|
|
83
|
+
private authError;
|
|
84
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<FirebaseAuthService, never>;
|
|
85
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<FirebaseAuthService>;
|
|
86
|
+
}
|
|
87
|
+
declare function provideFirebaseAuth(): Provider[];
|
|
88
|
+
|
|
89
|
+
/** Keep a concurrent login/tab from overwriting an already-created profile with defaults. */
|
|
90
|
+
declare class FirestoreProfilePersistence implements ProfilePersistence {
|
|
91
|
+
private readonly firestore;
|
|
92
|
+
ensure(collection: string, privateCollection: string | null, uid: string, decide: (profile: ProfileRecord | null, privateProfile: ProfileRecord | null) => ProfileChanges): Promise<ProfileRecord>;
|
|
93
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<FirestoreProfilePersistence, never>;
|
|
94
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<FirestoreProfilePersistence>;
|
|
95
|
+
}
|
|
96
|
+
declare function provideFirestoreProfiles(): Provider[];
|
|
97
|
+
|
|
98
|
+
export { FirebaseAuthService, FirestoreProfilePersistence, PLATFORM_FIREBASE_AUTH, firebaseUserToAuthSession, provideFirebaseAuth, provideFirestoreProfiles };
|
|
99
|
+
//# sourceMappingURL=tech4good-platform-auth-firebase.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-auth-firebase.d.ts","sources":["../../firebase/auth.ts","../../firebase/profiles.ts"],"mappings":";;;;;;;AAWA;AACA,cAAa,sBAAsB,EAAA,cAAA,CAAA,IAAA;AAEnC,KAAK,gBAAgB,GAAG,IAAI,CAC1B,IAAI;AAUN;;;;;;;;AAQG;AACH,iBAAgB,yBAAyB,cAAc,gBAAgB,GAAG,WAAW;AAmBrF;AACA,cACa,mBAAoB,YAAW,UAAU;;;;;;AAUpD;;;AAGG;AACH,cAAU,UAAU,CAAC,WAAW;AAOhC;;;;AAIG;AACG,wBAAoB,OAAO,CAAC,WAAW;AAM7C;;;;;AAKG;AACG,yBAAqB,OAAO,CAAC,WAAW;AAS9C;;;AAGG;AACG,kBAAc,OAAO,CAAC,WAAW;AAQvC;;;;;;AAMG;wCACuC,OAAO;AAMjD;;AAEG;AACG,sCAAkC,OAAO;;;AAW/C;;;;;;;;;;AAUG;AACG,yDAAqD,OAAO,CAAC,WAAW;;cAqClE,OAAA;AAIZ;;AAmBA;AASA;AAIA;yCA1KW,mBAAmB;6CAAnB,mBAAmB;AA6K/B;AAED,iBAAgB,mBAAmB,IAAI,QAAQ;;ACjO/C;AACA,cACa,2BAA4B,YAAW,kBAAkB;AACpE;AACM,gGACc,aAAa,yBAAyB,aAAa,YAAY,cAAc,GAC9F,OAAO,CAAC,aAAa;yCAJb,2BAA2B;6CAA3B,2BAA2B;AA2BvC;AACD,iBAAgB,wBAAwB,IAAI,QAAQ;;","names":[]}
|