very-express 0.8.3 → 0.9.0-alpha

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.
@@ -0,0 +1,133 @@
1
+ // External identity (broker SSO) sign-in glue.
2
+ //
3
+ // The login page renders one button per configured sign-in method, each carrying its provider id in a
4
+ // `data-provider` attribute, and the broker's own init script defines a global that turns
5
+ // `(providerId)` into a fresh ID token — for Firebase, `signInWithPopup` followed by `getIdToken()`.
6
+ //
7
+ // This file owns nothing vendor specific. It calls that global and hands the token to
8
+ // POST /api/auth/external, the only endpoint in the system that accepts a non-vex credential. The
9
+ // exchange consumes the token and answers with a vex session redirect; from that point on the client
10
+ // holds only vex tokens and nothing here runs again.
11
+ //
12
+ // Configuration arrives as `window.__vexExternalLogin`, rendered inline by the login page:
13
+ // { getToken: "<global name>", resumeRedirect: "<global name>", signInMethod: "popup"|"redirect",
14
+ // config: { ...broker public config, from env... }, problems: [...] }
15
+ //
16
+ // Two entry points, and neither the page nor this file needs to know which mode is in use:
17
+ // - a button calls getToken(providerId); in "redirect" mode the page navigates away before that
18
+ // promise ever settles
19
+ // - on page load, resumeRedirect() completes a redirect sign-in, or resolves null
20
+
21
+ document.addEventListener("DOMContentLoaded", function () {
22
+ var settings = window.__vexExternalLogin || {};
23
+ var getTokenName = settings.getToken;
24
+ var problems = settings.problems || [];
25
+
26
+ var buttons = document.querySelectorAll ? document.querySelectorAll(".externalLoginBtn") : [];
27
+
28
+ /**
29
+ * Broker SDKs report a misconfigured client with something generic — Firebase's
30
+ * `auth/internal-error` says nothing about the cause. The login page sends along what the server
31
+ * could determine, so a developer is not left reading a network trace.
32
+ */
33
+ function report(message) {
34
+ if (problems.length > 0) {
35
+ message += "\n\nServer-side configuration problems:\n- " + problems.join("\n- ");
36
+ }
37
+
38
+ // alert rather than a DOM node: the login page has no result container.
39
+ alert(message);
40
+ }
41
+
42
+ function exchange(idToken) {
43
+ return fetch("/api/auth/external", {
44
+ method: "POST",
45
+ headers: { "Content-Type": "application/json" },
46
+ body: JSON.stringify({ idToken: idToken }),
47
+ }).then(function (response) {
48
+ // read as text first: an error response may not be JSON (a proxy or the express error
49
+ // handler can return HTML), and response.json() would then reject and hide the real status
50
+ return response.text().then(function (text) {
51
+ var body;
52
+ try {
53
+ body = text ? JSON.parse(text) : {};
54
+ }
55
+ catch (e) {
56
+ body = { raw: text };
57
+ }
58
+
59
+ return { ok: response.ok, status: response.status, body: body };
60
+ });
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Complete a redirect sign-in.
66
+ *
67
+ * A no-op in popup mode, so this runs unconditionally: the redirect path cannot be distinguished
68
+ * from an ordinary page load until the broker answers, and it must be asked on every load to catch
69
+ * the return.
70
+ */
71
+ function resume() {
72
+ var resumeName = settings.resumeRedirect;
73
+ var fn = resumeName ? window[resumeName] : undefined;
74
+ if (typeof fn !== "function") return;
75
+
76
+ Promise.resolve()
77
+ .then(function () { return fn(); })
78
+ .then(function (idToken) {
79
+ if (!idToken) return; // not a return from a redirect sign-in
80
+ return exchange(idToken);
81
+ })
82
+ .then(function (outcome) {
83
+ if (!outcome) return;
84
+ if (outcome.ok && outcome.body && outcome.body.result && outcome.body.result.url) {
85
+ window.location.href = outcome.body.result.url;
86
+ return;
87
+ }
88
+ report("External sign-in failed (" + outcome.status + "): " + JSON.stringify(outcome.body));
89
+ })
90
+ .catch(function (err) {
91
+ report("External sign-in error: " + String(err));
92
+ });
93
+ }
94
+
95
+ Array.prototype.forEach.call(buttons, function (button) {
96
+ button.addEventListener("click", function () {
97
+ var getToken = getTokenName ? window[getTokenName] : undefined;
98
+ if (typeof getToken !== "function") {
99
+ report(
100
+ "External sign-in is not configured: window." + getTokenName +
101
+ " is missing. Check the broker's init script."
102
+ );
103
+ return;
104
+ }
105
+
106
+ button.disabled = true;
107
+
108
+ Promise.resolve()
109
+ .then(function () { return getToken(button.getAttribute("data-provider")); })
110
+ .then(function (idToken) {
111
+ if (!idToken) throw new Error("the configured getToken() resolved with no ID token");
112
+ return exchange(idToken);
113
+ })
114
+ .then(function (outcome) {
115
+ // mirrors the local flow: the server answers with the session redirect, and the
116
+ // /logincallback page performs the code-for-tokens exchange
117
+ if (outcome.ok && outcome.body && outcome.body.result && outcome.body.result.url) {
118
+ window.location.href = outcome.body.result.url;
119
+ return;
120
+ }
121
+
122
+ button.disabled = false;
123
+ report("External sign-in failed (" + outcome.status + "): " + JSON.stringify(outcome.body));
124
+ })
125
+ .catch(function (err) {
126
+ button.disabled = false;
127
+ report("External sign-in error: " + String(err));
128
+ });
129
+ });
130
+ });
131
+
132
+ resume();
133
+ });
@@ -65,10 +65,11 @@ Conditional emission:
65
65
 
66
66
  ```jsonc
67
67
  {
68
- "app": { "enableSwagger": true },
68
+ "app": { "enableSwagger": true, "showSoftDeleted": false },
69
69
  "auth": {
70
70
  "localAuth": true,
71
71
  "useHttpOnlyCookieToken": true,
72
+ "deleteAccount": true,
72
73
  "oauthProviders": { "google": false, "github": false }
73
74
  },
74
75
  "useRBAC": { "roles": ["visitor", "member", "admin"], "default": "admin" }
@@ -84,6 +85,12 @@ least one role (`utils.generator.isRbacEnabled`). Omitting the key, or passing
84
85
  When RBAC is on, `src/templates/jsonSchemaRBAC/` is copied over the sample schemas and
85
86
  `UserRole.role`'s enum is synced from `useRBAC.roles`.
86
87
 
88
+ Account deletion is the opposite — **opt-out**. `auth.deleteAccount` defaults to true, so
89
+ `AuthController` gains `POST /api/auth/delete-account` and the UI gains `/delete_account` unless the
90
+ project explicitly disables it (auth must also be enabled). `app.showSoftDeleted` controls whether
91
+ the repository hides soft-deleted rows; unset means hidden. See
92
+ [`docs/features/accountDeletion.md`](../features/accountDeletion.md).
93
+
87
94
  ## Auth internals
88
95
 
89
96
  JWT rolling keys and OAuth2 provider setup are documented in [`docs/appGenerated/auth.md`](../appGenerated/auth.md).
@@ -0,0 +1,150 @@
1
+ # Account deletion (tombstone)
2
+
3
+ Self-service account deletion for generated apps: `POST /api/auth/delete-account` plus a
4
+ `/delete_account` page. The account is **soft-deleted** — the row survives so business tables can
5
+ keep their required foreign keys — and its credentials and personal data are erased.
6
+
7
+ This covers the identity domain only. Business rows, uploaded objects and third-party identities
8
+ (Firebase, etc.) belong to the application. See the Renomaster spec for the full table-by-table
9
+ split.
10
+
11
+ ## Configuration
12
+
13
+ ```json
14
+ {
15
+ "auth": { "deleteAccount": true },
16
+ "app": { "showSoftDeleted": false }
17
+ }
18
+ ```
19
+
20
+ | Option | Default | Meaning |
21
+ |---|---|---|
22
+ | `auth.deleteAccount` | `true` | Emit the endpoint, the service and the page. Also requires auth to be enabled — a deletion endpoint that cannot authenticate a caller could only delete the wrong account. |
23
+ | `app.showSoftDeleted` | `false` | Lifts the adapter's soft-delete filter app-wide, making tombstones visible (and writable) again. Loud on every generation run. |
24
+
25
+ Both are read with `??`, so an explicit `false` is never swallowed. There is no `deleteAccountPlaceholder`:
26
+ the tombstone label is the constant `"Deleted user"`.
27
+
28
+ ## Declaring soft delete
29
+
30
+ Tag one boolean property with `x-vexData: "softDelete"`:
31
+
32
+ ```jsonc
33
+ "properties": {
34
+ "deleted": {
35
+ "type": "boolean",
36
+ "default": false,
37
+ "x-vexData": "softDelete",
38
+ "description": "Framework-managed; never client-writable."
39
+ }
40
+ },
41
+ "required": ["deleted"]
42
+ ```
43
+
44
+ The framework then owns that field:
45
+
46
+ - **Not client-writable.** `collectRequestManagedFields()` omits it, so it never appears in a
47
+ generated request body (`PayloadUser`), and the OpenAPI schema stops advertising it. A client
48
+ cannot soft-delete, resurrect or pre-tombstone a row through the CRUD API.
49
+ - **Hidden by default.** The adapters add `marker IS NOT TRUE` (`$ne: true` on Mongo) to every read
50
+ and write filter, so a tombstoned row is unreachable without any call-site change.
51
+ - **Owned writes.** `softDelete(id, data)` writes the marker through the normal update-phase
52
+ machinery, so `updatedAt` / `updatedBy` record who deleted the row and when. No `deletedAt` /
53
+ `deletedBy` columns are added.
54
+
55
+ Validation (generation-time, fails loud):
56
+
57
+ - at most **one** marker per document;
58
+ - it must be `"type": "boolean"`, `"default": false` and **required**.
59
+
60
+ The required/default rules are load-bearing. The hide-filter is `marker IS NOT TRUE`, so a nullable
61
+ column would drop every row written before it existed. `required` + `default: false` produce a
62
+ `boolean NOT NULL DEFAULT false` column.
63
+
64
+ ## Query semantics
65
+
66
+ `app.showSoftDeleted` is a **generation-time constant** baked into `VexFieldRegistry.gen.ts`, so no
67
+ request can flip it. There is deliberately no soft-delete key in `Filter<T>`: `Filter` is the shape
68
+ of every HTTP `filter` body, so a filter-level escape hatch would be a client-side bypass.
69
+
70
+ Internal callers use dedicated methods instead:
71
+
72
+ ```ts
73
+ softDelete(id, data?) // write the marker + redaction in one update
74
+ findOneWithDeleted(filter, join, select) // skip ONLY the soft-delete term; ownership still applies
75
+ ```
76
+
77
+ The hide term is **not** applied to relation loading, which is why the marker is a plain column and
78
+ not TypeORM's `@DeleteDateColumn` — the decorator nulls relation loads, and retained conversations
79
+ must still resolve their author to show "Deleted user".
80
+
81
+ > Enabling `app.showSoftDeleted` is a blunt instrument: it applies to every entity, including ones
82
+ > added later, and it removes the write protection that keeps a tombstone's audit fields frozen.
83
+
84
+ ## The token guard
85
+
86
+ `Authentication.middleware` verifies the JWT signature and nothing else, so a deleted user's
87
+ unexpired access token would keep working for the rest of its lifetime. The generated
88
+ `AccountStateGuard` closes that gap.
89
+
90
+ It reads the marker **value** rather than relying on the row being hidden, so the answer holds under
91
+ `app.showSoftDeleted` — a visibility-based check would call every tombstone alive. It uses
92
+ `findOneWithDeleted` so the ownership filter still applies, and treats a missing marker as live
93
+ (`!== true`), matching the adapters.
94
+
95
+ Every other auth path is already fail-closed: refresh and the OAuth exchange look the user up
96
+ through a soft-filtered read, local login compares an email that has been wiped to NULL, and the
97
+ OAuth callback cannot re-bind because the profile rows are gone.
98
+
99
+ The guard is emitted as a no-op when the identity document declares no marker, so the middleware's
100
+ import always resolves and projects without soft delete pay nothing.
101
+
102
+ The exported middleware is **synchronous** on purpose. Both call sites are express chains, and
103
+ Express 4 does not catch a rejected promise — an `async` handler would turn every failure into an
104
+ unhandled rejection. The async work lives in `handle()` and every outcome is routed to `next()`.
105
+
106
+ ## Deletion flow
107
+
108
+ `AccountDeletionService.deleteSelf()` takes the identity from `UserContext` only; no id is ever
109
+ accepted from a path or body, so one account cannot delete another. It is idempotent: a repeat call
110
+ returns `alreadyDeleted` without re-stamping the row.
111
+
112
+ Order is load-bearing:
113
+
114
+ 1. **Credentials first** — auth profiles, roles, sessions. Tombstoning first would leave the OAuth
115
+ path able to resolve the account through `provider` / `providerUserId`, i.e. a deleted user could log
116
+ back into their own tombstone.
117
+ 2. **Tombstone last** — `softDelete(userId, TOMBSTONE)`. A mid-flight failure therefore leaves a
118
+ live account that can simply be retried.
119
+
120
+ The tombstone redacts the standard personal fields: `email` → NULL, `name` → `"Deleted user"`,
121
+ `locale` / `profileErrors` → NULL, `active` → false. `email` is NULL rather than `""` because `User`
122
+ declares a unique index on it — a second deletion would collide on the empty string, and the same
123
+ address must be able to register a fresh account immediately.
124
+
125
+ The payload is derived from the project's own schema, so absent or renamed fields are never emitted
126
+ and audit / identity fields are skipped.
127
+
128
+ ## The page
129
+
130
+ `GET /delete_account`, served from `LoginUI` rather than as a static file — `express.static("public")`
131
+ would expose `public/delete_account.html` at `/delete_account.html`, not at the route the store
132
+ listing points people at.
133
+
134
+ `LoginUIConfig.deleteAccount` is **optional and defaults to true**, because an app's `server.ts` is
135
+ generated once and is not overwritten on later runs; a required field would stop such a project from
136
+ compiling.
137
+
138
+ The copy is explicit that this is a tombstone, not an erasure. The client clears its stored tokens on
139
+ success: the account is gone the moment the tombstone is written, so keeping a token the server now
140
+ rejects would only produce confusing 401s.
141
+
142
+ ## Integration notes
143
+
144
+ - **Migration.** Adding the marker adds a column. `SQL_SYNCHRONIZE=true` covers development;
145
+ production needs `ALTER TABLE "user" ADD COLUMN "deleted" boolean NOT NULL DEFAULT false`.
146
+ - **`allowOverwrite: false`.** A project that pinned `UserModel.gen.ts` / `User.gen.ts` must add the
147
+ column by hand, or clear the `.vex/meta.json` entry for those files.
148
+ - **Per-request cost.** The guard costs one narrow indexed read per authenticated request.
149
+ - **Third-party identity.** vex cannot delete a Firebase account. Do it from the app, and capture the
150
+ provider uid *before* calling the service.
@@ -237,36 +237,6 @@ Validation runs once, after every schema is loaded (`validateAuditFields()` in
237
237
  `src/preprocess/auditFields.ts`, called from the pipeline), because R1/R2 are cross-document. All problems
238
238
  are collected and reported together; `log.error` exits the generator, so a contradiction never reaches runtime.
239
239
 
240
- ## 7. Backward compatibility
241
-
242
- - Schema with no reserved keyword and no tag → nothing changes; generation output is identical.
243
- - Schema with a literal `default` → unchanged.
244
- - Existing generated apps: re-run `vex`; entities gain `nullable` audit columns if they were declared.
245
- - Existing rows keep `createdBy = NULL`. This feature cannot backfill; a downstream app that needs
246
- ownership on legacy rows must migrate data itself.
247
- - Tokens issued before the upgrade still work (the `?? _id` fallback on refresh).
248
- - The prototype branch's lowercase `x-format` values (`primary`, `uuid`, …) are **rejected** — this design
249
- keeps the current capitalized values (`Primary`, `PrimaryUUID`, `UUID`, `UnixTimestamp`) and only adds
250
- `Timestamp`.
251
-
252
- ### Breaking since v0.8.2
253
-
254
- Three changes downstream apps must absorb when they re-run `vex`:
255
-
256
- 1. **The context module was renamed.** `DataIsolationContext.gen.ts` is gone; `UserContext.gen.ts` replaces
257
- it. `cleanupStaleFiles()` removes the old file on the next run, so anything importing it by name breaks.
258
- 2. **A create without an identity now throws** where it previously wrote NULL. This affects
259
- `onCreateUserId` only, and only a path that reaches `create()` with no authenticated request context
260
- (seed scripts, background jobs, or a controller that does not mount `Authentication.middleware`).
261
- 3. **Data isolation becomes effective for the first time.** It used to be mounted only on entities declaring
262
- `dataIsolation`, which in practice meant it rarely ran at all. It now has a context on every
263
- authenticating controller. Ownership still wins over the caller's filter, so an endpoint that queries
264
- *another* user's row by id will silently act on the caller's own row instead. Audit those endpoints per
265
- app.
266
-
267
- Downstream apps no longer need the `dataIsolation` config merely to get the ALS context mounted — that
268
- coupling is gone. Use `dataIsolation` only when ownership filtering is actually wanted.
269
-
270
240
  ## 8. Mongoose
271
241
 
272
242
  Implemented in parallel with TypeORM — same registry, same strip/inject phases, same values
@@ -0,0 +1,34 @@
1
+ # Auth
2
+ - Stateless JWT token
3
+ - **Rolling Keys**
4
+ define in `.env`,
5
+ named `JWT_KEY{increment}`
6
+ ```bash
7
+ JWT_KEY1=aaaaa
8
+ JWT_KEY2=bbbbb
9
+ JWT_KEY3=ccccc
10
+ ```
11
+ - **OAuth2**
12
+ Supported Providers:
13
+ - Google
14
+ - Github
15
+
16
+ define in `.env`,
17
+ named `OAUTH_{provider}_CLIENTID` & `OAUTH_{provider}_CLIENTSECRET`
18
+ ```bash
19
+ OAUTH_GOOGLE_CLIENTID=xxxxx
20
+ OAUTH_GOOGLE_CLIENTSECRET=xxxxx
21
+ ```
22
+ - **External identity (broker SSO)** — off by default
23
+ - `POST /auth/external` takes an ID token from a broker (Firebase), verifies it against the
24
+ issuer's JWKS, and provisions the vex identity. The broker's token is consumed there and never
25
+ stored; the reply is the usual session-code redirect, so `POST /auth/token` still mints every
26
+ token.
27
+ - The generated login page renders the broker's buttons; the broker's SDK comes from the npm
28
+ package, served same-origin.
29
+ - **Prefer a broker that exposes the upstream IdP's subject — Firebase or Cognito.** Those produce
30
+ `("google", <Google sub>)`, the same key the passport flow writes. A broker that cannot (Keycloak,
31
+ Okta) only yields one broker-labelled row, so the UI shows the broker's name instead of the
32
+ provider the user actually picked.
33
+ - Config, identity layers, `signInMethod`, troubleshooting:
34
+ [`docs/features/externalIdentity.md`](../features/externalIdentity.md).
@@ -0,0 +1,163 @@
1
+ # External identity (broker SSO)
2
+
3
+ Sign in through an external identity broker — Firebase today — while **every token in the system stays
4
+ vex-issued**. Off by default.
5
+
6
+ ```
7
+ Browser ──(SDK sign-in)──> Broker ──(ID token)──> POST /api/auth/external ──> vex JWT
8
+ │
9
+ verify JWKS, map claims,
10
+ find-or-create the vex identity
11
+ ```
12
+
13
+ The broker's token is a **credential, not a session**: presented once, consumed at that endpoint, never
14
+ stored, never echoed, and accepted nowhere else. Everything downstream is the existing vex flow — the
15
+ endpoint answers with a session-code redirect, and `POST /api/auth/token` mints the access/refresh pair.
16
+
17
+ The server holds **no broker SDK and no client secret**: the ID token is a standard OIDC JWT, verified
18
+ with the `jsonwebtoken` the app already has, against keys fetched from the issuer's JWKS and imported
19
+ with `node:crypto`.
20
+
21
+ ## Configuration
22
+
23
+ ```json
24
+ "auth": {
25
+ "externalIdentity": {
26
+ "enabled": true,
27
+ "preset": "firebase",
28
+ "projectId": "your-firebase-project"
29
+ }
30
+ }
31
+ ```
32
+
33
+ A preset names a broker. Explicit keys override it, so you can start from a preset and adjust one field.
34
+ Without a preset, `issuer` and the rest must be given explicitly.
35
+
36
+ | Key | Default | Meaning |
37
+ |---|---|---|
38
+ | `enabled` | `false` | The feature gate. Auth must also be on. |
39
+ | `preset` | — | `firebase`. Unknown names fail generation loudly. |
40
+ | `projectId` | — | Preset variable: supplies the issuer and the audience. |
41
+ | `identityLayer` | `auto` | `auto` / `broker` / `upstream` — see below. |
42
+ | `signInMethod` | `popup` | `popup` / `redirect` — see below. |
43
+ | `onMissingEmail` | `reject` | `reject` refuses a login with no email; `synthesize` writes `<subject>@<provider>.invalid`. |
44
+ | `issuer`, `jwksUrl`, `discovery`, `audience`, `audienceClaim`, `algorithms`, `providerLabel`, `claims` | from the preset | For a broker with no preset. |
45
+
46
+ Generation fails loudly rather than emitting a half-working verifier: unknown preset, a missing preset
47
+ variable, a symmetric algorithm (`HS*`, an alg-confusion risk), `providerLabel: "local"` (reserved by
48
+ vex's own password path), or `identityLayer: "upstream"` on a preset that cannot reach an upstream
49
+ subject.
50
+
51
+ ### Env
52
+
53
+ ```
54
+ FIREBASE_API_KEY=
55
+ FIREBASE_AUTH_DOMAIN=
56
+ FIREBASE_PROJECT_ID=
57
+ FIREBASE_APP_ID=
58
+ ```
59
+
60
+ These are the broker's **public** browser values, served to the login page by design. `storageBucket`,
61
+ `messagingSenderId` and `measurementId` are for other Firebase products and are not used.
62
+
63
+ **`.env` is read once, at startup.** The dev watcher reloads on changes to it, but a process started by
64
+ hand needs restarting — and `dotenv` never overrides a variable that is already set in the environment,
65
+ so a value exported by your shell, IDE launch config or container silently wins. The server log names
66
+ what it could not resolve and says when a value is being shadowed.
67
+
68
+ Copy **all four** values from one app registration. Mixing an old `apiKey` with a new `appId` is a
69
+ silent failure: the request is authenticated with the key.
70
+
71
+ ## The identity that gets stored
72
+
73
+ `provider` and `providerUserId` always come from the **same layer**, so the stored pair can never name a
74
+ namespace its id does not belong to:
75
+
76
+ | Layer | `provider` | `providerUserId` |
77
+ |---|---|---|
78
+ | `broker` | the broker (`firebase`) | the broker's own subject |
79
+ | `upstream` | the upstream IdP (`google`) | the upstream subject |
80
+
81
+ `auto` picks `upstream` when the login carries one and falls back to `broker` when it does not — a
82
+ Firebase password or phone sign-in has no upstream provider.
83
+
84
+ **Each login writes exactly one row**: the identity used. A user who signs in with Google through
85
+ Firebase gets `("google", <Google sub>)` — the same key the passport flow writes, so both paths converge
86
+ on one row. A second linked provider appears after the first login with it.
87
+
88
+ The row set **is** the connected-accounts UI: there is no separate display field.
89
+
90
+ Reading the token is deliberately conservative. Only `email_verified` addresses may be used for
91
+ account linking — without that gate, any provider that does not verify addresses becomes an
92
+ account-takeover path. And the issuer is pinned in configuration, never taken from the token: a verifier
93
+ that fetched the JWKS URL named by an unvalidated `iss` claim would be an SSRF gadget.
94
+
95
+ ## The login page
96
+
97
+ The generated page renders one button per configured provider. The **preset** supplies the vendor
98
+ parts — SDK location, provider list, public env names, a browser init snippet — so nothing here names a
99
+ vendor and nothing needs editing in `server.ts`:
100
+
101
+ | Supplied by | What |
102
+ |---|---|
103
+ | the preset, emitted into `ExternalIdentityUI.gen.ts` | the SDK, the provider list, the init snippet |
104
+ | vex, in `LoginUI.gen.ts` | the buttons, the nonce'd script tags, the config carrier, and the glue that posts the ID token to `/api/auth/external` |
105
+
106
+ **The SDK comes from npm, not a CDN.** `firebase` is a dependency, and the page loads it through a
107
+ same-origin route (`/js/firebase/…`) whose file names are an allowlist. The version is npm's business,
108
+ no CDN host needs a CSP allowance, and the page works offline. The route reads `node_modules` at request
109
+ time because generation happens before `npm install` — run `npm install` after upgrading, or the login
110
+ page reports the SDK as not installed.
111
+
112
+ ### popup or redirect
113
+
114
+ `popup` is the default and is what Google recommends on browsers that block third-party storage access —
115
+ the pending sign-in state stays in the page's own first-party storage.
116
+
117
+ `redirect` navigates the whole page. Reach for it when a popup is blocked, not to dodge the storage
118
+ policy: redirect has its own form of that failure, which is why Google documents
119
+ [best practices for `signInWithRedirect` on browsers that block third-party storage
120
+ access](https://firebase.google.com/docs/auth/web/redirect-best-practices). Its remedy is to serve the
121
+ broker's sign-in helper from your own domain; vex does not generate that proxy.
122
+
123
+ ## When sign-in fails
124
+
125
+ The page expands the broker error codes that carry a meaning — `auth/unauthorized-domain` (add this
126
+ origin under Authentication → Settings → Authorized domains), `auth/operation-not-allowed` (enable the
127
+ provider under Authentication → Sign-in method), `auth/popup-blocked`, and so on — in the alert and in
128
+ the server log.
129
+
130
+ `auth/internal-error` names no cause by design. Its message points at the usual ones: a restricted API
131
+ key (Google Cloud console → APIs & Services → Credentials: the key must allow this origin under HTTP
132
+ referrers), an extension blocking `firebaseapp.com` / `apis.google.com`, or blocked third-party cookies.
133
+ For those, a request failing with `net::ERR_BLOCKED_BY_CLIENT` was never sent at all — an extension
134
+ blocked it.
135
+
136
+ A `GET /__/firebase/init.json 404` in the broker's own console output is expected: `/__/firebase/…` is a
137
+ Hosting reserved URL, and an API-only project has no Hosting site. The handler falls back to the
138
+ configuration in its own redirect URL.
139
+
140
+ ### Works in a private window, fails in the normal profile
141
+
142
+ That combination means the configuration is right and the profile is interfering — check it before
143
+ touching any Firebase setting:
144
+
145
+ 1. **An extension.** Private windows disable them. Look for `net::ERR_BLOCKED_BY_CLIENT`; then disable
146
+ all extensions and add them back one at a time.
147
+ 2. **Stale auth state for the origin.** The SDK caches sign-in and pending-redirect state in the origin's
148
+ `IndexedDB` (`firebaseLocalStorageDb`), keyed by API key. After changing the key, or after a string of
149
+ failed attempts, it can be inconsistent. Clear site data for the app origin and for
150
+ `<project>.firebaseapp.com`.
151
+ 3. **A profile-level cookie setting**, or an enterprise policy with a URL blocklist.
152
+
153
+ ## Firebase: which values are used, and where
154
+
155
+ | Console section | Used? |
156
+ |---|---|
157
+ | SDK setup → npm | no bundler here, but the SDK *package* is used — see the login page section |
158
+ | SDK setup → CDN | no |
159
+ | SDK setup → 配置 (the `firebaseConfig` object) | **yes** — `apiKey`, `authDomain`, `projectId`, `appId` |
160
+
161
+ Also enable the providers you want (Authentication → Sign-in method) and keep your app's origin in the
162
+ authorized domains list. The app's config must come from a **Web** app registration; a mobile `appId`
163
+ (`…:android:…` / `…:ios:…`) is detected and reported rather than left to a network trace.