@tech4good/angular-schematics 21.4.0 → 21.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/package.json +1 -1
  3. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +2 -1
  4. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +2 -1
  5. package/src/entity/index.js +57 -0
  6. package/src/entity/index.js.map +1 -1
  7. package/src/entity/schema.json +4 -0
  8. package/src/ng-add/files/.firebaserc.template +2 -1
  9. package/src/ng-add/files/.gitignore.template +2 -0
  10. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +34 -0
  11. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +143 -0
  12. package/src/ng-add/files/bigquery/scripts/run_query.py.template +167 -0
  13. package/src/ng-add/files/bigquery/views/events_flat.sql.template +60 -0
  14. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +34 -0
  15. package/src/ng-add/files/docs-infra/analytics-guide.md.template +170 -0
  16. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +270 -0
  17. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +16 -10
  18. package/src/ng-add/files/firebase.json.template +6 -0
  19. package/src/ng-add/files/firebase.logs.json.template +5 -0
  20. package/src/ng-add/files/firestore.indexes.json.template +112 -0
  21. package/src/ng-add/files/firestore.logs.rules.spec.ts.template +100 -0
  22. package/src/ng-add/files/firestore.logs.rules.template +8 -0
  23. package/src/ng-add/files/firestore.rules.spec.ts.template +84 -15
  24. package/src/ng-add/files/firestore.rules.template +29 -17
  25. package/src/ng-add/files/functions/.gitignore.template +3 -0
  26. package/src/ng-add/files/functions/package.json.template +12 -0
  27. package/src/ng-add/files/functions/src/index.ts.template +44 -0
  28. package/src/ng-add/files/functions/tsconfig.json.template +13 -0
  29. package/src/ng-add/files/jest.config.ts.template +1 -1
  30. package/src/ng-add/files/package.json.template +7 -4
  31. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +3 -1
  32. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +6 -8
  33. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +2 -0
  34. package/src/ng-add/files/src/app/app.component.html.template +2 -2
  35. package/src/ng-add/files/src/app/app.component.ts.template +2 -0
  36. package/src/ng-add/files/src/app/app.routes.ts.template +6 -0
  37. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +9 -4
  38. package/src/ng-add/files/src/app/core/analytics/log.service.ts.template +26 -4
  39. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +145 -2
  40. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +355 -149
  41. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +6 -1
  42. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +38 -0
  43. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +3 -2
  44. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +10 -3
  45. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +11 -5
  46. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +34 -17
  47. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +59 -0
  48. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +147 -0
  49. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +104 -17
  50. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +116 -0
  51. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +367 -70
  52. package/src/ng-add/files/src/app/core/store/app.store.ts.template +4 -1
  53. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +52 -66
  54. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +127 -0
  55. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +216 -147
  56. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +2 -4
  57. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +1 -1
  58. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +1 -0
  59. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.html.template +4 -0
  60. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.scss.template +1 -0
  61. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.ts.template +38 -0
  62. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +172 -48
  63. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +31 -0
  64. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -3
  65. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +12 -11
  66. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +5 -7
  67. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +12 -1
  68. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +93 -48
  69. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +12 -2
  70. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.html.template +18 -0
  71. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.scss.template +2 -0
  72. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +40 -0
  73. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +76 -0
  74. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +14 -8
  75. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +19 -7
  76. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +51 -0
  77. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +29 -5
  78. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +2 -1
  79. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +12 -8
  80. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +31 -10
  81. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +6 -19
  82. package/src/ng-add/files/src/app/first-time/login/login.component.html.template +58 -6
  83. package/src/ng-add/files/src/app/first-time/login/login.component.scss.template +151 -22
  84. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +18 -38
  85. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +59 -31
  86. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.html.template +12 -0
  87. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.scss.template +39 -0
  88. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +68 -0
  89. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.ts.template +20 -0
  90. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.html.template +24 -0
  91. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.scss.template +50 -0
  92. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +65 -0
  93. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.ts.template +59 -0
  94. package/src/ng-add/files/src/app/main/account-profile/guest-deletion-dialog.component.ts.template +51 -0
  95. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.html.template +50 -0
  96. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.scss.template +137 -0
  97. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +57 -0
  98. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.ts.template +59 -0
  99. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.html.template +133 -0
  100. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.scss.template +207 -0
  101. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +74 -0
  102. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.ts.template +130 -0
  103. package/src/ng-add/files/src/app/main/home/home.component.ts.template +0 -5
  104. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.html.template +15 -0
  105. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.scss.template +79 -0
  106. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +59 -0
  107. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.ts.template +44 -0
  108. package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +45 -15
  109. package/src/ng-add/files/src/app/shared/navbar/navbar.component.scss.template +103 -19
  110. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +73 -9
  111. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +46 -18
  112. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  113. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  114. package/src/ng-add/files/src/environments/environment.ts.template +1 -1
  115. package/src/ng-add/index_spec.d.ts +1 -0
  116. package/src/ng-add/index_spec.js +108 -0
  117. package/src/ng-add/index_spec.js.map +1 -0
  118. package/tsconfig.json +2 -2
@@ -0,0 +1,170 @@
1
+ # Analytics & Data Warehousing Guide
2
+
3
+ This document describes the telemetry logging and data warehousing architecture. It explains how user interactions are tracked, how data is synchronized to BigQuery, and how to query this data for research and analysis.
4
+
5
+ ---
6
+
7
+ ## 1. Architecture Overview
8
+
9
+ To support both real-time client-side tracking and complex research analysis (like NLP, statistical distribution, and LLM classifications), the analytics infrastructure uses a two-tier database strategy:
10
+
11
+ ```
12
+ ┌───────────────────────────────────────────────┐
13
+ │ Browser (Angular Client) │
14
+ │ Emits route-changes and interaction events │
15
+ └──────────────────────┬────────────────────────┘
16
+ │
17
+ ┌─────────────▼─────────────┐
18
+ │ Firestore: <log-project> │
19
+ │ logs/{logId} │
20
+ └─────────────┬─────────────┘
21
+ │ (Firebase BigQuery Export)
22
+ ┌─────────────▼─────────────┐
23
+ │ Google BigQuery │
24
+ │ analytics.logs_latest │ ← SQL View (latest state)
25
+ │ analytics.events_flat │ ← SQL View (event rows)
26
+ └───────────────────────────┘
27
+ ```
28
+
29
+ 1. **Firestore (`<log-project>` project)**: Serves as the high-volume ingestion layer. The client writes telemetry events to the `logs` collection. Firestore handles unreliable client networks, localStorage caching, retries, and browser beacon events.
30
+ 2. **BigQuery**: Serves as the analysis database. Telemetry documents are streamed in real-time to BigQuery using the **Firestore BigQuery Export** extension. Researchers run SQL queries and Python scripts against BigQuery to calculate metrics.
31
+ 3. **On-Demand Entity Export**: Direct application entities (like user answers or transaction records) are exported to BigQuery or Python on-demand using a Python script. This preserves privacy and makes user deletion requests trivial.
32
+
33
+ ---
34
+
35
+ ## 2. In-App Telemetry & Logging
36
+
37
+ Client-side telemetry is managed by the `TimeAnalyticsService`.
38
+
39
+ ### 2.1 Log Document Structure
40
+ Telemetry logs are written to Firestore under the collection `logs` with document IDs matching the format `${__sessionId}__${startTime}`. Each document represents a single page/route visit or registered UI state segment and contains:
41
+
42
+ ```json
43
+ {
44
+ "__userId": "user_123",
45
+ "__sessionId": "session_abc",
46
+ "__deviceId": "device_xyz",
47
+ "route": "/practice",
48
+ "state": { "problemId": "prob_456" },
49
+ "startTime": 1720000000000,
50
+ "time": [
51
+ { "type": "active", "total": 5200 },
52
+ { "type": "rest", "total": 12000 }
53
+ ],
54
+ "interactions": [
55
+ [1720000001000, "problem", "hint_click", "{\"hintIndex\":1}"],
56
+ [1720000005000, "problem", "submit_attempt", "{\"attemptText\":\"42\"}"]
57
+ ],
58
+ "_createdAt": 1720000000000,
59
+ "_updatedAt": 1720000006000
60
+ }
61
+ ```
62
+
63
+ * **`route` & `state`**: Tracks current URL route and optional registered UI state dimensions (e.g. `state.problemId`).
64
+ * **`time` array**: Tracks accumulated active and rest time on the route/state segment (measured using window focus, visibility, and mouse/keyboard activity).
65
+ * **`interactions` array**: Custom events tracked during the visit. Each interaction is a tuple: `[timestamp, category, action, JSON_stringified_properties]`.
66
+ * **`_createdAt` & `_updatedAt`**: Client-side epoch timestamps (in milliseconds) capturing when the log was opened and when it was last written (including beacon overwrites on tab close).
67
+
68
+ ### 2.2 Registering UI State Dimensions (`registerState`)
69
+ By default, logs are flushed when route or user changes. For components where users remain on a single route across multiple distinct items (such as solving math problems on `/practice`), components register state signals with `TimeAnalyticsService`:
70
+
71
+ ```typescript
72
+ // In component constructor
73
+ this.analytics.registerState(
74
+ 'problemId',
75
+ computed(() => this.currentProgress()?.__currentProblemId ?? null),
76
+ this.injector
77
+ );
78
+ ```
79
+
80
+ * **Behavior:** When the registered state signal value changes, `TimeAnalyticsService` flushes the current log segment to Firestore and starts a new segment for the new state value.
81
+ * **Cleanup:** State registrations are automatically cleaned up when the component is destroyed via `DestroyRef`.
82
+ * **Usage Rule:** Register state sparingly — only for dimensions requiring first-class time segmentation (e.g., `problemId`). General user interactions should be logged via `trackInteraction()`.
83
+
84
+ ---
85
+
86
+ ## 3. Configuring BigQuery Sync
87
+
88
+ To stream logs from Firestore to BigQuery, you must install the **Firestore BigQuery Export** extension on your logs Firebase project.
89
+
90
+ ### 3.1 Installation Steps
91
+ 1. In the Firebase Console, navigate to **Extensions**.
92
+ 2. Search for **Firestore BigQuery Export** and click **Install**.
93
+ 3. Configure the extension with the following parameters:
94
+ - **Collection path**: `logs`
95
+ - **Dataset ID**: `analytics`
96
+ - **Table ID**: `logs_raw`
97
+ - **Cloud Function location**: Select the region closest to your Firestore database (e.g., `us-central1`).
98
+ 4. Give the generated service account permissions to write to BigQuery.
99
+
100
+ The extension will create a BigQuery dataset named `analytics` containing:
101
+ * `logs_raw_changelog`: A table that appends a new row on every Firestore document create, update, or delete.
102
+ * `logs_raw_schema`: Internal schema helper table.
103
+
104
+ ---
105
+
106
+ ## 4. Understanding the BigQuery Changelog
107
+
108
+ Because BigQuery is an append-only warehouse, the extension does not edit existing rows. If a user's browser updates a log document (e.g. adding time via `sendBeacon` when they close the tab), a new row is appended to `logs_raw_changelog`.
109
+
110
+ Each row in `logs_raw_changelog` has the following system columns:
111
+ * `document_id`: The Firestore document path (`logs/sessionId__startTime`).
112
+ * `timestamp`: When the write was synced to BigQuery.
113
+ * `operation`: The Firestore write operation: `IMPORT`, `CREATE`, `UPDATE`, or `DELETE`.
114
+ * `data`: A JSON string containing the full serialized Firestore document.
115
+
116
+ To query the current state of logs without duplicates, we use a SQL view that filters for the latest update per document.
117
+
118
+ ---
119
+
120
+ ## 5. SQL Views & Queries
121
+
122
+ The SQL view files are located in `/bigquery/views/` and `/bigquery/queries/`.
123
+
124
+ ### 5.1 No Project Prefixes Needed
125
+ Our SQL scripts are designed **relativity** (omitting the GCP Project ID prefix, e.g. using `analytics.events_flat` instead of `your_project.analytics.events_flat`).
126
+ This means they run cleanly out of the box in the BigQuery Web Console (which executes them in your active project workspace) or via terminal scripts.
127
+
128
+ ### 5.2 Deduplicating Logs (`logs_latest`)
129
+ The view `logs_latest` extracts only the latest state of each document:
130
+ ```sql
131
+ SELECT * FROM `analytics.logs_latest` LIMIT 10;
132
+ ```
133
+
134
+ ### 5.3 Flattening Telemetry (`events_flat`)
135
+ The `events_flat` view flattens time segments and interactions nested arrays into standard tabular rows. Every row in `events_flat` represents a discrete event, typed as either:
136
+ - `route_visit`: Emitted when the user navigates away from a route. Includes columns `total_active_ms`, `total_rest_ms`, and `time_segments` (a raw JSON array containing the chronological sequence of active/idle intervals for pattern analysis).
137
+ - `interaction`: Emitted for custom telemetry actions. Includes columns `category`, `action`, and `properties` (parsed JSON).
138
+
139
+ ---
140
+
141
+ ## 6. Running Queries & Exports via Terminal
142
+
143
+ To avoid browser copy-paste workflows and support data analyses, we provide terminal scripts inside `bigquery/scripts/`.
144
+
145
+ ### 6.1 Running SQL Queries (`run_query.py`)
146
+ Use `run_query.py` to run any SQL file from the terminal and export the results to **JSON**, **CSV**, or a local **SQLite database**.
147
+
148
+ ```bash
149
+ # Export active time statistics by route to a local JSON file
150
+ python bigquery/scripts/run_query.py --project <your-gcp-project-id> --query bigquery/queries/active_time_by_route.sql --output output.json
151
+
152
+ # Export active time statistics by route to a local CSV file
153
+ python bigquery/scripts/run_query.py --project <your-gcp-project-id> --query bigquery/queries/active_time_by_route.sql --output output.csv
154
+
155
+ # Export active time statistics by route directly into a local SQLite table named 'active_time'
156
+ python bigquery/scripts/run_query.py --project <your-gcp-project-id> --query bigquery/queries/active_time_by_route.sql --output stats.db --table active_time
157
+ ```
158
+
159
+ ### 6.2 On-Demand Entity Export (`export_entities.py`)
160
+ Application entities contain sensitive data and are not automatically synchronized to BigQuery. Use `export_entities.py` to pull these collections directly from Firestore to local files on-demand for research.
161
+
162
+ ```bash
163
+ # Export documents directly from Firestore to a local JSON file
164
+ python bigquery/scripts/export_entities.py --credentials path/to/key.json --collection <collection-name> --output data.json
165
+
166
+ # Export documents to a local CSV file (auto-flattens nested fields)
167
+ python bigquery/scripts/export_entities.py --credentials path/to/key.json --collection <collection-name> --output data.csv
168
+ ```
169
+
170
+ *Note: If `--credentials` is omitted, the scripts automatically search the environment for `GOOGLE_APPLICATION_CREDENTIALS` or Application Default Credentials.*
@@ -0,0 +1,270 @@
1
+ # Authentication architecture
2
+
3
+ This document is the implementation reference for application authentication. It describes the production system as implemented in the Angular application, Firebase configuration, Firestore rules, and Cloud Functions.
4
+
5
+ ## Goals and boundaries
6
+
7
+ The application supports three sign-in paths:
8
+
9
+ | Path | Firebase provider | Intended use |
10
+ | --- | --- | --- |
11
+ | Google | `google.com` | One-click sign-in or upgrading a guest account with a Google identity. |
12
+ | Email magic link | Firebase Email/Password provider with email-link credentials | Passwordless sign-in and upgrading a guest account while preserving progress. |
13
+ | Guest | `anonymous` | Immediate, low-friction access; progress remains recoverable only by linking Google or an email address. |
14
+
15
+ The application does not provide password creation, password sign-in, or password reset screens. Firebase’s Email/Password provider remains enabled only because Firebase implements email-link sign-in through that provider.
16
+
17
+ Authentication establishes identity. The Firestore `users/{uid}` document establishes application state such as onboarding progress, consent, and administrator status. Both are required for access to private application routes.
18
+
19
+ ## Firebase Console configuration
20
+
21
+ Configure every Firebase project independently (development and production):
22
+
23
+ 1. Enable **Google**, **Email link (passwordless sign-in)**, and **Anonymous** under **Authentication → Sign-in method**. Keep the Email/Password provider enabled as required by Firebase for email links.
24
+ 2. Keep **Email enumeration protection** enabled.
25
+ 3. Use Firebase’s one-account-per-email behavior so Google and email-link credentials for the same email resolve to one Firebase user instead of separate accounts.
26
+ 4. Add each deployed host to **Authentication → Settings → Authorized domains**. At minimum this includes project hosts such as `<project-dev>.web.app` and `<project>.web.app`; add custom hosts as they are introduced.
27
+ 5. Leave the Firebase email template’s action URL at its project default (`https://<project>.firebaseapp.com/__/auth/action`). The app action then returns the browser to `/auth/action` on the originating application host.
28
+ 6. Deploy the `deleteAnonymousAccount` callable Cloud Function before enabling guest deletion.
29
+
30
+ The application intentionally does not call `fetchSignInMethodsForEmail`. Provider discovery would weaken enumeration protection and cannot safely resolve account-collision recovery.
31
+
32
+ ## Main application components
33
+
34
+ | Responsibility | Implementation |
35
+ | --- | --- |
36
+ | Firebase SDK operations | `src/app/core/firebase/firebase.service.ts` |
37
+ | Small Firebase abstraction used by stores and tests | `src/app/core/firebase/database.service.ts` |
38
+ | Auth and application-user state | `src/app/core/store/auth/auth.store.ts` |
39
+ | Guard-facing auth resolution | `src/app/core/auth/auth.service.ts` |
40
+ | Email-link same-browser context | `src/app/core/firebase/email-link-context.service.ts` |
41
+ | Public entry and guest start | `src/app/first-time/landing/` |
42
+ | Email action and completion views | `src/app/first-time/auth-action/`, `src/app/first-time/email-link/` |
43
+ | Account linking/deletion UI | `src/app/main/account-profile/` |
44
+ | Guest deletion backend | `functions/src/index.ts` |
45
+
46
+ `AppComponent` calls `AuthStore.loadAuth()` once during application startup. That long-lived subscription remains active for the lifetime of the app so the UI can react to sign-in, sign-out, session revocation, and authentication changes from another tab.
47
+
48
+ ```mermaid
49
+ flowchart TD
50
+ subgraph UI ["UI & Routing Layer"]
51
+ Views["Views & Components<br/>(Landing, Action, Security)"]
52
+ Guards["Route Guards<br/>(requireAuth, requireAuthAndConsent, etc.)"]
53
+ end
54
+
55
+ subgraph State ["State Management Layer"]
56
+ AuthStore["AuthStore<br/>(afUser session & profile loading)"]
57
+ UserStore["UserStore<br/>(User profile & access state)"]
58
+ AuthService["AuthService<br/>(Guard authentication resolution)"]
59
+ end
60
+
61
+ subgraph Infra ["Services & Infrastructure"]
62
+ FirebaseService["FirebaseService<br/>(Firebase Auth SDK operations)"]
63
+ ContextService["EmailLinkContextService<br/>(Cookie & LocalStorage context)"]
64
+ Firestore[("Firestore DB<br/>users/{uid} & userPrivates/{uid}")]
65
+ Functions["Cloud Functions<br/>(deleteAnonymousAccount)"]
66
+ end
67
+
68
+ Guards -->|"resolves auth"| AuthService
69
+ AuthService -->|"queries state"| AuthStore
70
+ Views -->|"triggers sign-in / linking"| AuthStore
71
+ AuthStore -->|"derives user"| UserStore
72
+ AuthStore -->|"calls SDK methods"| FirebaseService
73
+ AuthStore -->|"provisions profile"| Firestore
74
+ FirebaseService -->|"stores link context"| ContextService
75
+ Views -->|"invokes backend deletion"| Functions
76
+ ```
77
+
78
+ ## Session model and local state
79
+
80
+ `FirebaseService.afUser()` exposes Firebase Auth changes as an `AuthSession` containing:
81
+
82
+ - Firebase UID, email, display name, photo URL, anonymous state, and email-verification state;
83
+ - provider IDs (for example `google.com` or `password`);
84
+ - `emailLinkEnabled`, derived from Firebase provider metadata rather than Firestore.
85
+
86
+ `AuthStore` maintains the Firebase session in `afUser` and derives `user` by looking up the matching entity in `UserStore`. A Firebase session can therefore exist briefly before the application profile has loaded; guards use `AuthService.resolveUser()` to handle that distinction.
87
+
88
+ On an authenticated session, `provisionAndLoadUser()`:
89
+
90
+ 1. Calls `ensureUserProfile()` to create missing `users/{uid}` and `userPrivates/{uid}` records, or update available Google profile fields.
91
+ 2. Loads the application user into `UserStore`.
92
+ 3. Starts a real-time stream for that user record.
93
+
94
+ Fresh sign-in methods provision directly after Firebase reports successful sign-in. The background `loadAuth()` subscription observes the same Firebase event, but skips its own provisioning while `isLoadingLogin` is true. This is important: Firestore can observe Firebase’s auth event before its credentials provider has installed the new token. A duplicate read in that narrow window can fail with `permission-denied` / “Missing or insufficient permissions.”
95
+
96
+ The background subscription is deliberately not unsubscribed on logout. Instead, logout tears down Firestore streams and resets stores while retaining the app-wide Firebase auth observer for the next sign-in or an external auth change.
97
+
98
+ Because RxJS cannot cancel an already-running provisioning Promise, logout and account deletion first block new refresh provisioning and wait for any active refresh provisioning to settle. Only then do they tear down Firestore streams and sign out. This ordering prevents a delayed `userStore.stream()` call from recreating a listener under signed-out credentials.
99
+
100
+ ## Account creation and profile data
101
+
102
+ `ensureUserProfile()` creates a new application profile when the Firebase UID has no matching document:
103
+
104
+ - `users/{uid}` contains the application identity and onboarding state. New accounts begin at `SUBMIT_INTEREST` and are not administrators or consented.
105
+ - `userPrivates/{uid}` contains the email when Firebase provides one, plus email-link capability metadata.
106
+
107
+ Google provides display name and photo URL. Those values are copied to an existing guest profile when available.
108
+
109
+ Email magic links provide a verified email address but do not provide a display name or profile image. The application therefore preserves the existing guest profile, displays the email address on the account page, and uses the initials avatar fallback until the user sets a display name. It does not manufacture a name or avatar from an email address.
110
+
111
+ ## Google flow
112
+
113
+ `AuthStore.signInWithGoogle()` calls `FirebaseService.signInWithGoogle()`, which uses `signInWithPopup` and a `GoogleAuthProvider`. The resulting session is provisioned and recorded in `AuthStore`.
114
+
115
+ `AuthStore.linkGoogle()` uses `linkWithPopup` on the current Firebase user rather than creating a second application identity. It refreshes the Firebase ID token, reprovisions the existing UID, and updates the local session. If Firebase reports `auth/credential-already-in-use`, the account page explains that the Google identity belongs to another application profile.
116
+
117
+ ## Email magic-link flows
118
+
119
+ ```mermaid
120
+ sequenceDiagram
121
+ autonumber
122
+ actor User
123
+ participant App as Application UI
124
+ participant Context as EmailLinkContextService
125
+ participant FB as Firebase Auth SDK
126
+ participant Mail as User Email Inbox
127
+ participant Store as AuthStore / UserStore
128
+
129
+ User->>App: Request Magic Link
130
+ App->>Context: Store flow context (email, flow type, current UID)
131
+ App->>FB: sendSignInLinkToEmail(email, actionUrl)
132
+ FB->>Mail: Send email with magic link
133
+ Mail->>User: Click magic link
134
+ User->>FB: Open Firebase action URL
135
+ FB->>App: Redirect to /auth/action?mode=signIn -> /email-link
136
+ App->>Context: Retrieve stored context (same-browser verification)
137
+ App->>FB: completeEmailSignInLink() / linkWithCredential()
138
+ FB-->>App: Return authenticated credentials
139
+ App->>Store: provisionAndLoadUser()
140
+ Store-->>App: Load/create profile & establish active session
141
+ App->>User: Route to main application (/home)
142
+ ```
143
+
144
+ ### Sending
145
+
146
+ `FirebaseService.sendEmailLink()` calls `sendSignInLinkToEmail` with `handleCodeInApp: true` and an action URL based on the active browser origin:
147
+
148
+ ```
149
+ https://<current-host>/auth/action?flow=<flow>
150
+ ```
151
+
152
+ Before sending, `EmailLinkContextService` stores three values in both local storage (when available) and a 30-minute, `SameSite=Lax` cookie:
153
+
154
+ - requested email address;
155
+ - requested flow (`sign-in`, `guest-upgrade`, or `link-email`);
156
+ - current UID for flows that must retain the existing account.
157
+
158
+ The context makes the normal same-browser flow automatic and prevents a link intended to upgrade one guest account from being used to attach credentials to a different session. If storage is unavailable, the cookie provides the fallback.
159
+
160
+ The account page replaces its guest “Send Magic Link” button with “Magic link sent” after a successful send. A send failure leaves the button available for retry.
161
+
162
+ ### Callback and completion
163
+
164
+ Firebase opens its hosted action page, which redirects to the app’s `/auth/action` route. `AuthActionComponent` accepts only `mode=signIn` and forwards the request to `/email-link`. `EmailLinkComponent` completes automatically if the email is available from same-browser context; otherwise it asks the person to enter the email again.
165
+
166
+ `FirebaseService.completeEmailSignInLink()` verifies the URL with `isSignInWithEmailLink` and selects a flow:
167
+
168
+ | Flow | Completion action |
169
+ | --- | --- |
170
+ | `sign-in` | `signInWithEmailLink`, creating or restoring an email-linked Firebase session. |
171
+ | `guest-upgrade` | Requires the original same-browser UID, then calls `linkWithCredential` so guest progress stays on that UID. |
172
+ | `link-email` | Requires the original same-browser UID, then calls `linkWithCredential` to add passwordless email sign-in to an existing account. |
173
+
174
+ After completion, the Firebase token is refreshed, the short-lived email-link context is cleared, and `AuthStore` provisions/refreshes the application profile. The callback view routes to `/home`; route guards then send users to any incomplete early-access or consent step.
175
+
176
+ If the callback is opened on a different device or browser for an upgrade/linking flow, the app does not guess which account should receive the credential. It displays the `auth/link-requires-original-session` guidance instead.
177
+
178
+ ## Guest flow and account deletion
179
+
180
+ Choosing guest access calls `AuthStore.loginAnonymously()`, which creates an anonymous Firebase user, provisions the matching application profile, and then navigates through normal route guards.
181
+
182
+ Guests can preserve progress by linking Google or an email magic link. Deleting a guest account is intentionally destructive and requires confirmation.
183
+
184
+ The `deleteAnonymousAccount` callable function:
185
+
186
+ 1. Requires an authenticated request whose `sign_in_provider` is `anonymous`.
187
+ 2. Deletes guest-owned `userContexts` documents in batches. Extend `QUERY_COLLECTIONS` when the application adds other user-owned collections.
188
+ 3. Deletes the UID-keyed `users` and `userPrivates` documents.
189
+ 4. Deletes the Firebase Auth user.
190
+
191
+ After the callable succeeds, `AuthStore.deleteAnonymousAccount()` explicitly calls local Firebase `signOut`, patches local auth state to `null`, and routes to `/landing`. The explicit local sign-out matters: deleting a Firebase Auth user on the server does not necessarily clear the browser’s in-memory Firebase session before the landing guard runs. Without it, the guard could wait indefinitely for an application profile that the callable had already deleted.
192
+
193
+ ```mermaid
194
+ sequenceDiagram
195
+ autonumber
196
+ actor Guest as Guest User
197
+ participant App as Application UI / AuthStore
198
+ participant CF as Cloud Function (deleteAnonymousAccount)
199
+ participant FS as Firestore DB
200
+ participant FB as Firebase Auth
201
+
202
+ Guest->>App: Request Guest Account Deletion
203
+ App->>CF: Call deleteAnonymousAccount()
204
+ CF->>FS: Delete user-owned data (userContexts by default)
205
+ CF->>FS: Delete users and userPrivates docs
206
+ CF->>FB: Delete anonymous Firebase Auth user
207
+ CF-->>App: Callable returns success
208
+ App->>FS: resetAllStores() (Teardown Firestore listeners)
209
+ App->>FB: Local signOut() & patch auth state to null
210
+ App->>Guest: Route to /landing
211
+ ```
212
+
213
+ ## Logout and listener teardown
214
+
215
+ Before any logout or guest deletion, `AuthStore.resetAllStores()`:
216
+
217
+ 1. Tears down cached Firestore streams.
218
+ 2. Resets `UserStore` and `UserContextStore`.
219
+
220
+ Tearing down streams before the token is invalidated avoids post-logout Firestore permission errors from active listeners. It also means views can briefly observe no current application user during teardown; components that derive data from the user must treat that state as valid. For example, the early-access `waitlistData` computed signal returns `null` instead of dereferencing a missing user.
221
+
222
+ The Firebase auth observer remains subscribed after logout. It is necessary for future sign-ins, cross-tab changes, and session invalidation. Direct sign-in methods use `isLoadingLogin` to ensure that this observer mirrors the new session without racing the credential-ready provisioning operation.
223
+
224
+ ## Routing and authorization
225
+
226
+ Routes in `src/app/app.routes.ts` use four layers of guard behavior:
227
+
228
+ | Guard | Purpose |
229
+ | --- | --- |
230
+ | `redirectIfAuthenticated` | Keeps authenticated users off public landing/login routes; redirects them to home. |
231
+ | `requireAuth` | Requires a resolved application user; otherwise redirects to landing. |
232
+ | `earlyAccessGuard` | Keeps users in the interest/waitlist stage until their access state advances. |
233
+ | `requireAuthAndConsent` | Requires authentication, completion of early access, and consent before home/onboarding routes. |
234
+
235
+ `AuthService.resolveUser()` first observes Firebase Auth. If there is no Firebase session, it immediately resolves `null`; if there is a session, it returns the synchronous store user when already available or waits for the first loaded application user. This avoids guards making decisions from an incomplete Firestore load while preserving immediate redirects for logged-out users.
236
+
237
+ ## Firestore authorization relationship
238
+
239
+ Firestore rules are in `firestore.rules`. The main principle is that authentication alone is not enough for every action:
240
+
241
+ - Anonymous users, Google users, and verified-email users are permitted where `isVerifiedOrAnonymous()` applies.
242
+ - Users can create and update their own user and private records, subject to application-state restrictions; they cannot grant themselves administrator access or bypass protected onboarding transitions.
243
+ - User-owned `userContexts` documents are restricted to their owning UID, with administrator exceptions.
244
+ - Applications must add equivalent owner checks for every additional user-owned collection they introduce.
245
+
246
+ The callable guest-deletion function uses the Admin SDK and therefore performs controlled server-side deletion rather than relying on the client to clean up every collection.
247
+
248
+ ## Operational checklist
249
+
250
+ When changing authentication behavior, verify:
251
+
252
+ 1. The Firebase Console providers and authorized domains are configured in both environments.
253
+ 2. Email links return to `/auth/action` on the correct host and work in the same browser that initiated account linking.
254
+ 3. Guest login creates one profile and does not emit Firestore permission errors after a previous guest deletion.
255
+ 4. Guest deletion removes data, signs out locally, and lands on `/landing`.
256
+ 5. Google and email-link upgrades preserve the existing UID and its progress.
257
+ 6. Firestore listeners are torn down before sign-out, while the top-level auth observer remains active.
258
+ 7. Route guards redirect unauthenticated users to landing and incomplete users to the appropriate onboarding stage.
259
+ 8. `npm run lint`, `npm run build`, `npm run test`, and `npm run test:rules` pass before deployment.
260
+
261
+ ## Related implementation references
262
+
263
+ - `src/app/core/store/auth/auth.store.ts`
264
+ - `src/app/core/firebase/firebase.service.ts`
265
+ - `src/app/core/firebase/email-link-context.service.ts`
266
+ - `src/app/core/auth/auth.service.ts`
267
+ - `src/app/core/auth/guards/`
268
+ - `src/app/main/account-profile/`
269
+ - `functions/src/index.ts`
270
+ - `firestore.rules`
@@ -219,25 +219,31 @@ Each `<entity>.mock.ts` exports a seed data array (e.g. `COMMUNITY_DB = [...]`).
219
219
 
220
220
  ## 6. Authentication & Access Flow
221
221
 
222
- ### 6.1 Auth State
222
+ ### 6.1 Authentication system
223
223
 
224
- Auth state lives in `src/app/core/store/auth/auth.store.ts`:
225
- - `authStore.afUser` — the Firebase Auth user (uid, email, displayName, photoURL)
226
- - `authStore.user` — a computed signal that looks up the database `User` entity by `afUser.uid`
224
+ The generated application supports Google, passwordless email links, and anonymous guest
225
+ sessions. `AuthStore.afUser` holds the normalized Firebase `AuthSession`; `AuthStore.user`
226
+ resolves the matching Firestore application profile.
227
227
 
228
- On app start, `AppComponent.ngOnInit()` calls `authStore.loadAuth()`, which:
229
- 1. Subscribes to the Firebase auth state (`db.afUser()`)
230
- 2. Performs a blocking `userStore.load()` to ensure the user is in the store before guards run
231
- 3. Then sets up a background `userStore.stream()` for real-time updates
232
- 4. Creates a new database User if one doesn't exist yet
228
+ `AppComponent.ngOnInit()` starts one app-lifetime Firebase auth observer. Fresh sign-in
229
+ methods provision the profile directly after Firebase credentials are ready. Logout and
230
+ guest deletion tear down Firestore streams and reset application stores before invalidating
231
+ the local session.
232
+
233
+ See [`docs-infra/authentication-architecture.md`](authentication-architecture.md) for the
234
+ complete provider flows, same-browser email-link context, account linking, callable guest
235
+ deletion, Firestore rules, and deployment checklist.
233
236
 
234
237
  ### 6.2 Access Pipeline (Guards)
235
238
 
236
239
  Users progress through access states defined in `AccessState`:
237
240
  ```
238
- SUBMIT_INTEREST → WAITING → DONE (+ consented)
241
+ SUBMIT_INTEREST → WAITING → CONSENT → DONE
239
242
  ```
240
243
 
244
+ When `environment.hasWaitlist` is `false`, interest submission moves directly from
245
+ `SUBMIT_INTEREST` to `CONSENT`.
246
+
241
247
  The guard hierarchy is:
242
248
 
243
249
  | Guard | Purpose |
@@ -5,6 +5,12 @@
5
5
  "rules": "firestore.rules",
6
6
  "indexes": "firestore.indexes.json"
7
7
  },
8
+ "functions": {
9
+ "source": "functions",
10
+ "predeploy": [
11
+ "npm --prefix \"$RESOURCE_DIR\" run build"
12
+ ]
13
+ },
8
14
  "hosting": {
9
15
  "public": "dist/<%= dasherize(project) %>/browser",
10
16
  "ignore": [
@@ -0,0 +1,5 @@
1
+ {
2
+ "firestore": {
3
+ "rules": "firestore.logs.rules"
4
+ }
5
+ }
@@ -0,0 +1,112 @@
1
+ {
2
+ "indexes": [
3
+ {
4
+ "collectionGroup": "userContexts",
5
+ "queryScope": "COLLECTION",
6
+ "fields": [
7
+ {
8
+ "fieldPath": "__userId",
9
+ "order": "ASCENDING"
10
+ },
11
+ {
12
+ "fieldPath": "_deleted",
13
+ "order": "ASCENDING"
14
+ },
15
+ {
16
+ "fieldPath": "_updatedAt",
17
+ "order": "ASCENDING"
18
+ },
19
+ {
20
+ "fieldPath": "__name__",
21
+ "order": "ASCENDING"
22
+ }
23
+ ],
24
+ "density": "SPARSE_ALL"
25
+ },
26
+ {
27
+ "collectionGroup": "users",
28
+ "queryScope": "COLLECTION",
29
+ "fields": [
30
+ {
31
+ "fieldPath": "_deleted",
32
+ "order": "ASCENDING"
33
+ },
34
+ {
35
+ "fieldPath": "accessState",
36
+ "order": "ASCENDING"
37
+ },
38
+ {
39
+ "fieldPath": "joinedWaitlistAt",
40
+ "order": "ASCENDING"
41
+ },
42
+ {
43
+ "fieldPath": "__name__",
44
+ "order": "ASCENDING"
45
+ }
46
+ ],
47
+ "density": "SPARSE_ALL"
48
+ },
49
+ {
50
+ "collectionGroup": "users",
51
+ "queryScope": "COLLECTION",
52
+ "fields": [
53
+ {
54
+ "fieldPath": "accessState",
55
+ "order": "ASCENDING"
56
+ },
57
+ {
58
+ "fieldPath": "_createdAt",
59
+ "order": "ASCENDING"
60
+ },
61
+ {
62
+ "fieldPath": "__name__",
63
+ "order": "ASCENDING"
64
+ }
65
+ ],
66
+ "density": "SPARSE_ALL"
67
+ },
68
+ {
69
+ "collectionGroup": "users",
70
+ "queryScope": "COLLECTION",
71
+ "fields": [
72
+ {
73
+ "fieldPath": "accessState",
74
+ "order": "ASCENDING"
75
+ },
76
+ {
77
+ "fieldPath": "_updatedAt",
78
+ "order": "DESCENDING"
79
+ },
80
+ {
81
+ "fieldPath": "__name__",
82
+ "order": "DESCENDING"
83
+ }
84
+ ],
85
+ "density": "SPARSE_ALL"
86
+ },
87
+ {
88
+ "collectionGroup": "users",
89
+ "queryScope": "COLLECTION",
90
+ "fields": [
91
+ {
92
+ "fieldPath": "__id",
93
+ "order": "ASCENDING"
94
+ },
95
+ {
96
+ "fieldPath": "_deleted",
97
+ "order": "ASCENDING"
98
+ },
99
+ {
100
+ "fieldPath": "_updatedAt",
101
+ "order": "ASCENDING"
102
+ },
103
+ {
104
+ "fieldPath": "__name__",
105
+ "order": "ASCENDING"
106
+ }
107
+ ],
108
+ "density": "SPARSE_ALL"
109
+ }
110
+ ],
111
+ "fieldOverrides": []
112
+ }