very-express 0.9.0-alpha → 0.9.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 (31) hide show
  1. package/AGENTS.md +24 -10
  2. package/dist/index.js +747 -969
  3. package/dist/templates/_middlewares/Authentication.ts +0 -3
  4. package/dist/templates/_middlewares/UserContext.ts +1 -18
  5. package/dist/templates/_projectSettings/env +13 -12
  6. package/dist/templates/_projectSettings/package.json +2 -2
  7. package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
  8. package/dist/templates/_routes/LoginUI.ts +293 -242
  9. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +0 -6
  10. package/dist/templates/_services/VexDbConnector.ts +1 -26
  11. package/dist/templates/_services/auth/JWTService.ts +0 -15
  12. package/dist/templates/_types/auth.ts +12 -8
  13. package/dist/templates/_utils/hash.ts +0 -16
  14. package/dist/templates/root/public/js/deleteaccount.js +0 -54
  15. package/docs/appGenerated/auth.md +84 -0
  16. package/docs/architecture/authAndRouting.md +1 -1
  17. package/docs/architecture/databaseTargets.md +4 -2
  18. package/docs/features/accountDeletion.md +2 -3
  19. package/docs/features/auditFields.md +2 -2
  20. package/docs/releaseNote/v0-8-5.md +98 -0
  21. package/docs/releaseNote/v0-9-0.md +41 -47
  22. package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
  23. package/docs/vexJsonSchema.md +17 -0
  24. package/package.json +1 -1
  25. package/vex.config.json +1 -6
  26. package/dist/templates/_routes/ExternalIdentityUI.gen.ts +0 -20
  27. package/dist/templates/root/public/js/externallogin.js +0 -133
  28. package/docs/features/auth.md +0 -34
  29. package/docs/features/externalIdentity.md +0 -163
  30. /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
  31. /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
@@ -87,7 +87,6 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
87
87
  Object.assign(data, values);
88
88
  }
89
89
 
90
- /** Build ownership filter from current request context, or null. */
91
90
  private getOwnershipFilter(): Record<string, unknown> | null {
92
91
  const userId = UserContext.userId;
93
92
  if (!userId) return null;
@@ -133,7 +132,6 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
133
132
 
134
133
  private mapOperators(filter: Filter<T>): Record<string, unknown> | Array<Record<string, unknown>> {
135
134
  if (!filter || typeof filter !== "object") return {};
136
- // if (Array.isArray(filter)) return filter.map(f => this.mapOperators(f));
137
135
 
138
136
  let out: Record<string, unknown> | Array<Record<string, unknown>> = {};
139
137
 
@@ -177,10 +175,6 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
177
175
  out[key] = Like(oval.$like as string);
178
176
  continue;
179
177
  }
180
- // if (val?.$raw) {
181
- // out[key] = Raw(val.$raw as string);
182
- // continue;
183
- // }
184
178
  } else {
185
179
  out[key] = val;
186
180
  }
@@ -2,11 +2,8 @@
2
2
  import { Request, Response, NextFunction } from "express";
3
3
  import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
4
4
  import mongoose from "mongoose";
5
- // import { Document } from "mongoose";
6
- // import { sqlMigrations } from "../_models/sqlMigration.gen";
7
5
  import { VexRepository } from "../_types/vex";
8
6
  import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
9
- // import { MongooseRepositoryAdapter } from "./MongooseRepositoryAdapter.gen";
10
7
  import utils from "./../_utils";
11
8
 
12
9
  export class VexDbConnector {
@@ -73,7 +70,6 @@ export class VexDbConnector {
73
70
  .then(() => {
74
71
  this.dataSource = ds;
75
72
  utils.log.infoSql("TypeORM DataSource initialized");
76
- // this.runSqlMigrations(ds);
77
73
  })
78
74
  .catch((err) => {
79
75
  utils.log.errorSql(`Failed to initialize TypeORM, retrying in ${retryTime}s`, err);
@@ -84,23 +80,6 @@ export class VexDbConnector {
84
80
  connectWithRetry(10);
85
81
  }
86
82
 
87
- // private async runSqlMigrations(ds: DataSource): Promise<void> {
88
- // if (!sqlMigrations.length) return;
89
- // const runner = ds.createQueryRunner();
90
- // await runner.connect();
91
- // try {
92
- // for (const sql of sqlMigrations) {
93
- // utils.log.infoSql(`Applying migration: ${sql}`);
94
- // await runner.query(sql);
95
- // }
96
- // utils.log.infoSql(`${sqlMigrations.length} migrations applied`);
97
- // } catch (err) {
98
- // utils.log.errorSql("SQL migration failed", err);
99
- // } finally {
100
- // await runner.release();
101
- // }
102
- // }
103
-
104
83
  closeSql(): void {
105
84
  if (this.dataSource?.isInitialized) {
106
85
  this.dataSource.destroy()
@@ -109,7 +88,7 @@ export class VexDbConnector {
109
88
  }
110
89
  }
111
90
 
112
- // TODO: complete mongoose support, handle join and select
91
+ // TODO: complete mongoose support
113
92
  connectMongo(): void {
114
93
  console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
115
94
  utils.log.infoMongo("Connecting to MongoDB (Driver: Mongoose)...");
@@ -124,7 +103,6 @@ export class VexDbConnector {
124
103
  connectWithRetry(10);
125
104
  }
126
105
 
127
- // TODO: complete mongoose support, handle join and select
128
106
  closeMongo(): void {
129
107
  console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
130
108
  mongoose.disconnect()
@@ -132,13 +110,10 @@ export class VexDbConnector {
132
110
  .catch((err) => utils.log.errorMongo("Error disconnecting Mongoose", err));
133
111
  }
134
112
 
135
- // getRepository<T extends Document>(target: { schema: unknown; modelName: string }): VexRepository<T>;
136
113
  getRepository<T extends ObjectLiteral>(target: EntityTarget<T>): VexRepository<T>;
137
114
  getRepository<T>(target: EntityTarget<ObjectLiteral> | any): VexRepository<T> {
138
- // TODO: complete mongoose support, handle join and select
139
115
  if (target?.schema && target?.modelName) {
140
116
  console.warn("VeryExpress unified db adapter (MongooseRepositoryAdapter) for Mongodb are under development, use with caution. Contribute to \"https://github.com/Justin26l/VeryExpress\"");
141
- // return new MongooseRepositoryAdapter<T & Document>(target);
142
117
  }
143
118
  if (!this.dataSource) throw new Error("SQL DataSource not initialized");
144
119
  return new TypeOrmRepositoryAdapter<T & ObjectLiteral>(this.dataSource.getRepository(target));
@@ -2,7 +2,6 @@
2
2
  import jwt from "jsonwebtoken";
3
3
  import ms from "ms";
4
4
  import path from "path";
5
- // import express, { CookieOptions } from "express";
6
5
 
7
6
  import JWTKeyStore from "./JWTKeyStore.gen";
8
7
 
@@ -36,13 +35,6 @@ export default class JWTService {
36
35
 
37
36
  constructor() {}
38
37
 
39
- /**
40
- * Verifies a JSON Web Token (JWT) using the provided token and key index.
41
- *
42
- * @param {string} token - The JSON Web Token to be verified.
43
- * @param {number} index - The index of the key used to verify the token.
44
- * @return {jwt.JwtPayload } The decoded token payload, an error message, or false if verification fails.
45
- */
46
38
  public verifyToken(token: string, index?: number | string): jwt.JwtPayload {
47
39
 
48
40
  if (token.startsWith("Bearer ")) {
@@ -67,9 +59,6 @@ export default class JWTService {
67
59
  }
68
60
  }
69
61
 
70
- /**
71
- * Process of login user, assign tokens and create session.
72
- */
73
62
  public async assignTokens(user: UserWithRelations, provider: string): Promise<string> {
74
63
  if(!user._id) {
75
64
  throw new VexResErr(500, null, "User Data Error, User._id missing.");
@@ -77,7 +66,6 @@ export default class JWTService {
77
66
 
78
67
  const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
79
68
 
80
- // insert new unique session for user
81
69
  await this.sessionRepo.deleteWhere({ userId: user._id });
82
70
  await this.sessionRepo.create({
83
71
  sessionCode,
@@ -86,7 +74,6 @@ export default class JWTService {
86
74
  expired: Date.now() + 5000,
87
75
  });
88
76
 
89
- // return appAuthCode to client
90
77
  const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
91
78
 
92
79
  return redirectPath;
@@ -106,8 +93,6 @@ export default class JWTService {
106
93
  };
107
94
  }
108
95
 
109
- /** utils */
110
-
111
96
  /**
112
97
  * Identity value of a user record: the field tagged `x-vexData: "userId"` in the schemas,
113
98
  * with `_id` as the fallback. This is what every audit field (createdBy / updatedBy) stores.
@@ -14,16 +14,20 @@ export interface registerResponse {
14
14
  message: string
15
15
  }
16
16
 
17
+ export interface localLoginResponse {
18
+ url: string;
19
+ }
20
+
17
21
  /**
18
- * A redirect back to the client carrying a single-use `sessionCode`, which the client exchanges at
19
- * `POST /auth/token` for the token pair.
20
- *
21
- * Neutral name on purpose: `/auth/local` and `/auth/external` both answer with this shape, and the two
22
- * are independently enabled (`localAuth` vs `auth.externalIdentity`), so the type cannot live behind
23
- * either flag.
22
+ * `POST /auth/firebase` — the answer to a Firebase sign-in.
23
+ * `isNewUser` is true only when this call created the `User` row; a user linked by a verified email address is false.
24
24
  */
25
- export interface loginRedirectResponse {
26
- url: string;
25
+ export interface firebaseLoginResponse {
26
+ accessToken: string;
27
+ accessTokenIndex: string;
28
+ refreshToken: string;
29
+ refreshTokenIndex: string;
30
+ isNewUser: boolean;
27
31
  }
28
32
 
29
33
  /** Row counts removed alongside the tombstone, so the caller can log and retry. */
@@ -1,15 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import crypto from "crypto";
3
- // import log from "~/utils/logger";
4
3
  import { UserWithRelations } from "../_types/User.gen";
5
4
 
6
- /**
7
- * Hashes a password with a salt (e.g., user email).
8
- * @param plainPassword The plain text password to hash.
9
- * @param salt The salt to use (e.g., user email).
10
- * @param algorithm The hash algorithm (default: 'sha256').
11
- * @returns The hashed password (hex encoded).
12
- */
13
5
  export function hashPassword(
14
6
  plainPassword: string,
15
7
  salt: string,
@@ -18,24 +10,16 @@ export function hashPassword(
18
10
  return crypto.createHash(algorithm).update(plainPassword + salt).digest("hex");
19
11
  }
20
12
 
21
- /**
22
- * Verifies if a plain password (with salt) matches a given hashed password.
23
- * @param user The user object containing email and userAuthProfiles.
24
- * @param plainPassword The plain text password to verify.
25
- * @returns True if the password matches, false otherwise.
26
- */
27
13
  export function verifyPassword(
28
14
  user: UserWithRelations,
29
15
  plainPassword: string,
30
16
  ): boolean {
31
17
  if(!user.email || !user.userAuthProfiles) {
32
- // log.error(`User "${user._id}" email or userAuthProfiles missing for local auth's password verification.`);
33
18
  return false;
34
19
  }
35
20
 
36
21
  const hashedPassword = user.userAuthProfiles.find((profile:any) => profile.provider === "local")?.password;
37
22
  if(!hashedPassword) {
38
- // log.error(`User "${user._id}" Local auth profile or password missing.`);
39
23
  return false;
40
24
  }
41
25
 
@@ -24,52 +24,7 @@ document.addEventListener("DOMContentLoaded", function () {
24
24
  result.textContent = JSON.stringify(data, null, 2);
25
25
  }
26
26
 
27
- /**
28
- * Deletion is self-service and the server resolves the account from the token alone, so with no
29
- * token there is nothing to delete: sending an empty `Bearer ` would only earn a bare 401 that
30
- * reads like a server fault. Point at the login page instead.
31
- *
32
- * Both credentials are required — `Authentication.middleware` treats them as one requirement — so
33
- * a half-populated store counts as "not signed in" rather than as an API call.
34
- *
35
- * Note this file is copied into a project once and never overwritten, so a project generated
36
- * before these checks existed keeps the old behaviour until it is updated by hand.
37
- */
38
- function signedIn() {
39
- return !!localStorage.getItem("accessToken") && !!localStorage.getItem("accessTokenIndex");
40
- }
41
-
42
- function notSignedIn() {
43
- render({
44
- status: 401,
45
- error: "You are not signed in. Deletion is self-service and the server takes the account " +
46
- "from your access token, so sign in first.",
47
- signIn: "/login",
48
- });
49
- }
50
-
51
- /**
52
- * A 401 from the server means the stored credential was not accepted — expired, or already
53
- * tombstoned. Deliberately does NOT clear it: the request may equally have failed for a reason
54
- * that has nothing to do with the token, and dropping the session on any failure would sign the
55
- * user out of a working account. Sign in again and retry; the login flow overwrites both tokens.
56
- */
57
- function sessionRejected(outcome) {
58
- render({
59
- status: outcome.status,
60
- error: "Your session was not accepted, so nothing was deleted. It may have expired — " +
61
- "sign in again and retry.",
62
- detail: outcome.body,
63
- signIn: "/login",
64
- });
65
- }
66
-
67
27
  button.addEventListener("click", function () {
68
- if (!signedIn()) {
69
- notSignedIn();
70
- return;
71
- }
72
-
73
28
  if (input.value !== "DELETE") {
74
29
  render({ error: 'Type DELETE in the box to confirm.' });
75
30
  return;
@@ -105,15 +60,6 @@ document.addEventListener("DOMContentLoaded", function () {
105
60
  })
106
61
  .then(function (outcome) {
107
62
  if (!outcome.ok) {
108
- // 401 means the credential was not accepted. Say what to do about it rather than
109
- // printing a raw error body the user cannot act on — see sessionRejected for why
110
- // the stored tokens are left alone.
111
- if (outcome.status === 401) {
112
- sessionRejected(outcome);
113
- button.disabled = false;
114
- return;
115
- }
116
-
117
63
  render({ status: outcome.status, error: outcome.body });
118
64
  button.disabled = false;
119
65
  return;
@@ -0,0 +1,84 @@
1
+ # Auth
2
+
3
+ Stateless JWT tokens, plus three independent sign-in paths: local (email + password), OAuth2
4
+ (passport), and Firebase.
5
+
6
+ ## Tokens
7
+
8
+ Rolling keys are defined in `.env` as `JWT_KEY{increment}`:
9
+
10
+ ```bash
11
+ JWT_KEY1=aaaaa
12
+ JWT_KEY2=bbbbb
13
+ JWT_KEY3=ccccc
14
+ ```
15
+
16
+ A client sends the access token as `Authorization: Bearer <accessToken>` with
17
+ `X-Auth-Index: <accessTokenIndex>`, and refreshes at `POST /api/auth/refresh`.
18
+
19
+ ## Sign-in paths
20
+
21
+ | Path | Endpoint | Enabled by |
22
+ |---|---|---|
23
+ | Local (email + password) | `POST /api/auth/local`, `POST /api/auth/register` | `auth.localAuth` |
24
+ | OAuth2 | `GET /api/auth/<provider>` → `GET /api/auth/<provider>/callback` | `auth.oauthProviders` |
25
+ | Firebase | `POST /api/auth/firebase` | `auth.firebase` |
26
+
27
+ Local and OAuth2 answer `302` with a single-use `sessionCode`, which the client exchanges at
28
+ `POST /api/auth/token` for the token pair. Firebase answers `200` with the token pair directly.
29
+
30
+ OAuth2 credentials come from `.env`:
31
+
32
+ ```bash
33
+ OAUTH_GOOGLE_CLIENTID=xxxxx
34
+ OAUTH_GOOGLE_CLIENTSECRET=xxxxx
35
+ ```
36
+
37
+ `/login` renders a form or a button for whichever paths are enabled.
38
+
39
+ ## The identity row
40
+
41
+ A sign-in writes one `UserAuthProfiles` row, keyed by `(provider, providerUserId)` — a composite unique
42
+ index. `provider` is the namespace, `providerUserId` the subject inside it:
43
+
44
+ | Sign-in | `provider` | `providerUserId` |
45
+ |---|---|---|
46
+ | Local | `local` | — |
47
+ | passport Google | `google` | Google `sub` (`profile.id`) |
48
+ | Firebase + Google | `google` | Google `sub` |
49
+ | Firebase email/password, phone | — | `400`, no row |
50
+
51
+ A user reaching the API through Firebase and through passport Google resolves to the same `User` row.
52
+ `provider: "local"` is reserved: `verifyPassword` looks rows up by it.
53
+
54
+ ## Firebase
55
+
56
+ ```jsonc
57
+ "auth": { "firebase": true }
58
+ ```
59
+
60
+ ```bash
61
+ FIREBASE_SERVICE_ACCOUNT_JSON= # the service account JSON
62
+ FIREBASE_WEB_API_KEY= # public browser config, served to /login
63
+ FIREBASE_WEB_AUTH_DOMAIN=
64
+ FIREBASE_WEB_PROJECT_ID=
65
+ # FIREBASE_PROVIDERS=google # which buttons /login renders; default google
66
+ ```
67
+
68
+ The server verifies the ID token with `firebase-admin` against the project named by the service
69
+ account. With no usable credential the endpoint answers `503` and the app still starts.
70
+
71
+ `/login` loads the modular SDK (`firebase-app.js` / `firebase-auth.js`, ES modules from gstatic, pinned
72
+ version), preloads it on page load, and calls `signInWithPopup(getAuth(app), provider)` followed by
73
+ `user.getIdToken()`. The page sets its own CSP (script/connect/frame hosts) and its own
74
+ `Cross-Origin-Opener-Policy: same-origin-allow-popups`.
75
+
76
+ `firebase.sign_in_provider` selects the provider and `firebase.identities[<provider>][0]` supplies the
77
+ subject. A token whose provider has no entry in that map, or whose subject is missing, is answered with
78
+ `400`.
79
+
80
+ Failure modes on the page, expanded from the SDK's codes into a message on screen and in the server
81
+ log: `auth/popup-blocked`, `auth/popup-closed-by-user` (the popup closed before the handshake finished),
82
+ `auth/unauthorized-domain`, `auth/operation-not-allowed`, `auth/internal-error`.
83
+
84
+ Design record: [`docs/plan/spec-firebase-auth.md`](../plan/spec-firebase-auth.md).
@@ -97,6 +97,6 @@ JWT rolling keys and OAuth2 provider setup are documented in [`docs/appGenerated
97
97
 
98
98
  ## Client-facing API behaviour
99
99
 
100
- Pagination, search and the response envelope: [`docs/apiUsage.md`](../apiUsage.md).
100
+ Pagination, search and the response envelope: [`docs/features/apiUsage.md`](../features/apiUsage.md).
101
101
 
102
102
  Filter DSL for `find` / `count`: [`docs/features/filterOperators.md`](../features/filterOperators.md).
@@ -9,7 +9,9 @@
9
9
  | `"mongo"` | `src/generators/db/mongooseModel.generator.ts` |
10
10
  | `"sql"` | `src/generators/db/typeormEntity.generator.ts` |
11
11
 
12
- The generated app's DB target is fixed at generation time.
12
+ The generated app's DB target is fixed at generation time. `"sql"` means PostgreSQL: the connector
13
+ pins `type: "postgres"` and the app depends on `pg` only, so column types in the entity generator
14
+ (`uuid`, `timestamptz`, `bytea`, `jsonb`) must be PostgreSQL types.
13
15
 
14
16
  ### SQL schema creation
15
17
 
@@ -91,7 +93,7 @@ Guide: [`docs/features/auditFields.md`](../features/auditFields.md).
91
93
 
92
94
  `src/generators/middlewares/joinWhitelistRegistry.generator.ts` emits a static entity → allowed-joins map consumed by `JoinWhitelistMiddleware.ts`. Populated from `x-documentConfig.restApi.joinWhitelist`; auto-filled by `jsonSchemaForeignKeys.ts` when unset. Controllers with a whitelist get `@Middlewares(JoinWhitelistMiddleware.middleware("<DocName>"))`.
93
95
 
94
- See [`docs/features/joinWhitelist.md`](../features/joinWhitelist.md) and [`docs/ForeignKey.md`](../ForeignKey.md).
96
+ See [`docs/features/joinWhitelist.md`](../features/joinWhitelist.md) and [`docs/features/ForeignKey.md`](../features/ForeignKey.md).
95
97
 
96
98
  ## RBAC
97
99
 
@@ -5,8 +5,7 @@ Self-service account deletion for generated apps: `POST /api/auth/delete-account
5
5
  keep their required foreign keys — and its credentials and personal data are erased.
6
6
 
7
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.
8
+ (Firebase, etc.) belong to the application.
10
9
 
11
10
  ## Configuration
12
11
 
@@ -112,7 +111,7 @@ returns `alreadyDeleted` without re-stamping the row.
112
111
  Order is load-bearing:
113
112
 
114
113
  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
114
+ path able to resolve the account through `provider` / `oauthId`, i.e. a deleted user could log
116
115
  back into their own tombstone.
117
116
  2. **Tombstone last** — `softDelete(userId, TOMBSTONE)`. A mid-flight failure therefore leaves a
118
117
  live account that can simply be retried.
@@ -9,7 +9,7 @@ Generated apps declare `createdBy` / `createdAt` / `updatedBy` / `updatedAt` in
9
9
  but nothing ever writes them — `grep -rn "createdBy\|updatedBy" src/` in the generator is empty.
10
10
  The columns exist in the entities and stay NULL forever.
11
11
 
12
- Consequences seen in the wild (RenoMaster):
12
+ Consequences seen in a production deployment:
13
13
 
14
14
  - A custom controller checking `findOne({ _id, createdBy: request.user._id })` never matches → `404` on `DELETE /api/job/{id}`.
15
15
  - Timeline ordering bugs, because `createdAt` is also never written.
@@ -251,7 +251,7 @@ schema — a keyword would otherwise become a literal string default.
251
251
 
252
252
  - Soft delete.
253
253
  - Backfilling existing NULL rows.
254
- - RenoMaster's own job-ownership check (its owner is the `Client` profile, not the `User`).
254
+ - An app whose ownership column points at a profile row rather than at `User`.
255
255
  - Extending `useUserSchema: false` into a fully custom account model. Today `User.json` is copied from the
256
256
  templates unconditionally and `localAuth` requires `useUserSchema: true`, so a custom identity schema is
257
257
  not reachable yet; `x-vexData: "userId"` is the forward-compatible hook for it.
@@ -0,0 +1,98 @@
1
+ # v0.8.5
2
+
3
+ ## Breaking: the identity key is renamed, and now enforced
4
+
5
+ `UserAuthProfiles.oauthId` is **`providerUserId`**, and `(provider, providerUserId)` is a **composite
6
+ unique index**. The value never changed — it is the subject within `provider`'s namespace — but the old
7
+ name claimed a protocol the field does not require, and nothing stopped two rows claiming one identity.
8
+
9
+ Re-run the generator (migration `v0.8.5` rewrites the schema, and any `uniqueIndex` entry naming the old
10
+ field), then migrate the database:
11
+
12
+ ```sql
13
+ ALTER TABLE "userauthprofiles" RENAME COLUMN "oauthId" TO "providerUserId";
14
+ ALTER TABLE "userauthprofiles" ADD CONSTRAINT "unique_provider_providerUserId"
15
+ UNIQUE ("provider", "providerUserId");
16
+ ```
17
+
18
+ Look for existing duplicates before adding the constraint:
19
+
20
+ ```sql
21
+ SELECT provider, "providerUserId", COUNT(*) FROM "userauthprofiles"
22
+ GROUP BY 1,2 HAVING COUNT(*) > 1;
23
+ ```
24
+
25
+ `SQL_SYNCHRONIZE=true` covers development. App code that reads `oauthId` must be updated.
26
+
27
+ ## New: Firebase as a sign-in option
28
+
29
+ `auth.firebase: true` generates `POST /api/auth/firebase` and a button on the generated `/login` page.
30
+ The endpoint takes a Firebase ID token and answers with the vex token pair:
31
+
32
+ ```
33
+ POST /api/auth/firebase { "idToken": "<Firebase ID token>" }
34
+ 200 { "result": { accessToken, accessTokenIndex, refreshToken, refreshTokenIndex, isNewUser } }
35
+ 503 no usable service account 401 invalid or expired token
36
+ 400 the sign-in has no upstream IdP 409 the sign-in carries no email
37
+ ```
38
+
39
+ The identity written is the **upstream** IdP's — `("google", <Google sub>)` for a Google sign-in, the
40
+ same pair `passport-google-oauth20` writes, so both doors resolve to one `User` row.
41
+
42
+ ```jsonc
43
+ "auth": { "firebase": true }
44
+ ```
45
+
46
+ That boolean is the only switch. Everything else is environment. Four required values, under the names a
47
+ deployment already has; two variables earlier drafts carried are gone because nothing reads them
48
+ (`FIREBASE_APP_ID` — Firebase Auth takes no appId — and a file-path alternative to the service account).
49
+
50
+ | Variable | Used by |
51
+ |---|---|
52
+ | `FIREBASE_SERVICE_ACCOUNT_JSON` | server — `firebase-admin` |
53
+ | `FIREBASE_WEB_API_KEY`, `FIREBASE_WEB_AUTH_DOMAIN`, `FIREBASE_WEB_PROJECT_ID` | login page — public, by design |
54
+ | `FIREBASE_PROVIDERS` | optional; which buttons `/login` renders; default `google` |
55
+
56
+ Design record, including the identity rules and the reasons behind them:
57
+ [`docs/plan/spec-firebase-auth.md`](../plan/spec-firebase-auth.md).
58
+
59
+ ## Also fixed
60
+
61
+ - **A project with `localAuth: false` and any other sign-in path generated a controller that did not
62
+ compile** — `exchangeToken` / `refreshToken` call `this.userRepo`, which was only emitted when
63
+ `localAuth` was on. The getter is now emitted whenever auth is enabled. Reachable before this release
64
+ with `oauthProviders` alone; the Firebase-only configuration is the same shape.
65
+
66
+ ## After upgrading
67
+
68
+ 1. **`npm install`** — `firebase-admin` is a dependency of the generated app (the browser SDK is loaded
69
+ from gstatic by the login page, so the `firebase` package is not needed).
70
+ 2. **Re-run `vex`.**
71
+ 3. **Run the SQL above** if your identity table is older than this release.
72
+ 4. **Set the environment** — the service account, plus the three public values from one *Web* app
73
+ registration in the same Firebase project. Paste the downloaded key file into
74
+ `FIREBASE_SERVICE_ACCOUNT_JSON` as-is: its fields are snake_case (`project_id`, `private_key`,
75
+ `client_email`) and that is what the loader expects.
76
+ 5. **Turn it on** with `"auth": { "firebase": true }`, then re-run `vex`.
77
+ 6. **Open `/login`.** The button posts to `/api/auth/firebase`; a failed sign-in names the server-side
78
+ configuration problem it can see (missing variables, an unstartable provider name).
79
+
80
+ Notes:
81
+
82
+ - The login page loads the **modular** Firebase SDK as ES modules from gstatic (pinned version), the
83
+ same way the app's own web sign-in does, and preloads it on page load. That needs `www.gstatic.com` in
84
+ `script-src`, plus `connect-src` for the token endpoints and `frame-src` for the project's auth domain
85
+ — the generated page sets all three itself, so an app-wide `helmet` CSP does not have to change.
86
+ - The glue is **inlined into the generated page**, not served from `public/js/`. `public/**` is a
87
+ copy-once template, and an earlier draft of this feature put `public/js/firebaseauth.js` there — so a
88
+ project that ran that draft keeps a compat-era file while its page moved on, and the page fails with
89
+ `Firebase sign-in is not configured: window.undefined is missing`. **Delete
90
+ `public/js/firebaseauth.js`** from any project generated from that draft; nothing references it any
91
+ more. (Same for a stale `/js/firebase/*` route, if you carried one.)
92
+ - The login page overrides `Cross-Origin-Opener-Policy` to `same-origin-allow-popups`. helmet's default
93
+ (`same-origin`) nulls `window.opener` inside a cross-origin popup, which is the channel the Firebase
94
+ handler reports on, and the SDK then reports **`auth/popup-closed-by-user`** — a message that points at
95
+ the user and the network, never at the header that actually caused it. If you proxy or re-render the
96
+ login page yourself, keep this header.
97
+ - `LoginUI.gen.ts` and `FirebaseAuthUI.gen.ts` are regenerated even when `auth.firebase` is false; the
98
+ wiring module exports `undefined` and the page renders no Firebase button.
@@ -1,49 +1,43 @@
1
1
  # v0.9.0
2
2
 
3
- ## Breaking — `UserAuthProfiles.oauthId` → `providerUserId`
4
-
5
- - `(provider, providerUserId)` is the account-linking key, and it now has a **composite unique index**;
6
- nothing enforced it before.
7
- - A schema migration renames the property; one `ALTER TABLE` renames the column.
8
-
9
- ## External identity (broker SSO) — Firebase
10
-
11
- - `POST /api/auth/external` verifies a broker ID token against the issuer's JWKS and provisions the
12
- matching vex identity. **Off by default.**
13
- - Every token stays vex-issued: the broker's token is consumed at that one endpoint and never stored.
14
- - No broker SDK on the server, no client secret, no new dependency.
15
- - The generated login page renders the broker's buttons for you — configure it in `vex.config.json`,
16
- then `npm install` (the `firebase` dependency is new).
17
- - **Use a Web app's config**, all four values from the same registration.
18
- - Configuration, identity rules, troubleshooting: [`docs/features/externalIdentity.md`](../features/externalIdentity.md).
19
-
20
- ## `sessionCode` is single-use
21
-
22
- - `POST /api/auth/token` now consumes the code, instead of leaving it replayable for its whole TTL.
23
-
24
- ## Login and delete pages
25
-
26
- - The home page shows the login link for broker-only apps, which previously had none.
27
- - `/delete_account` states the sign-in prerequisite and links to `/login`.
28
- - `public/js/deleteaccount.js` no longer sends an empty `Bearer ` — **new projects only**, that file is
29
- copied once and not overwritten.
30
- - The login page's CSP now allows the hosts a broker SDK injects at runtime.
31
-
32
- ## After upgrading
33
-
34
- 1. **`npm install`** — `firebase` is a new dependency.
35
- 2. **Re-run the generator**, so the schema migration renames the property.
36
- 3. **Rename the column and add the constraint:**
37
- ```sql
38
- ALTER TABLE "userauthprofiles" RENAME COLUMN "oauthId" TO "providerUserId";
39
- ALTER TABLE "userauthprofiles" ADD CONSTRAINT "unique_provider_providerUserId"
40
- UNIQUE ("provider", "providerUserId");
41
- ```
42
- `SQL_SYNCHRONIZE=true` covers development. If the old code let two rows claim one identity, find them
43
- first: `SELECT provider, "providerUserId", COUNT(*) FROM "userauthprofiles" GROUP BY 1,2 HAVING COUNT(*) > 1;`
44
- 4. **Update app code** that reads `oauthId`.
45
- 5. **Keep `package.json` at `0.9.0` or later** — the migration runner compares the migration's label with
46
- `.vex/meta.json`'s last generated version, so a lower version re-runs it on every generation.
47
-
48
- Guides: [`docs/features/externalIdentity.md`](../features/externalIdentity.md),
49
- [`docs/features/accountDeletion.md`](../features/accountDeletion.md).
3
+ ## Binary fields: `x-format: "Binary"`
4
+
5
+ A property can now carry a binary payload. Declare it as a string with the `Binary` format:
6
+
7
+ ```jsonc
8
+ "data": { "type": "string", "x-format": "Binary", "description": "base64-encoded bytes" }
9
+ ```
10
+
11
+ | Layer | Value |
12
+ | --- | --- |
13
+ | SQL column | `bytea` |
14
+ | Entity property | `string` |
15
+ | API request / response | base64 string |
16
+
17
+ A TypeORM transformer converts `string → Buffer` on write and `Buffer → base64 string` on read, so
18
+ clients never see a `Buffer` and every generated type stays JSON-safe:
19
+
20
+ ```ts
21
+ @Column({type: "bytea", nullable: false,
22
+ transformer: {
23
+ to: (v: string | null) => (v == null ? v : Buffer.from(v, "base64")),
24
+ from: (v: Buffer | null) => (v == null ? v : v.toString("base64"))
25
+ }})
26
+ data!: string;
27
+ ```
28
+
29
+ `type` must be `string`; any other type fails generation. In mongo mode the column is a plain
30
+ `String` holding the same base64 text. The transformer does not validate base64 — `Buffer.from`
31
+ ignores invalid characters — and `maxLength` has no effect on a binary column.
32
+
33
+ Re-run the generator, then migrate the table. `SQL_SYNCHRONIZE=true` covers development; otherwise:
34
+
35
+ ```sql
36
+ ALTER TABLE "asset" ADD COLUMN "data" bytea;
37
+ ```
38
+
39
+ ## SQL target is PostgreSQL
40
+
41
+ The generated SQL app connects with a fixed `postgres` driver and depends on `pg` only. There is no
42
+ MySQL or SQLite path, so binary columns are always `bytea`. A MySQL target would need a dialect layer
43
+ between the schema and the entity generator; `blob` is not emitted today.