hazo_testing 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGE_LOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # hazo_testing changelog
2
2
 
3
+ ## 0.3.0 — 2026-06-12
4
+
5
+ ### Added — Permissioned user factory (FR-001)
6
+
7
+ `createTestUser` now wires a full permission/scope chain when `role`,
8
+ `permissions`, or `scopeId` opts are supplied. Bare calls (no chain opts) are
9
+ byte-for-byte backward compatible — the return shape and behavior are unchanged.
10
+
11
+ **New options:**
12
+
13
+ | Option | Type | Default | Description |
14
+ |---|---|---|---|
15
+ | `permissions` | `string[]` | — | Permission names to grant via the role. Auto-created if absent. |
16
+ | `role` | `string` | auto (`role_<id prefix>`) | Role name. Auto-created if absent; reused if it already exists. |
17
+ | `scopeId` | `string` | — | Scope id to assign the user to. Auto-created if absent. |
18
+ | `scopeName` | `string` | `scopeId` | Name for the auto-created scope row. |
19
+ | `scopeLevel` | `string` | `"firm"` | `level` column of the auto-created scope row. |
20
+
21
+ **New return fields** (only present when a chain was seeded):
22
+ `roleId`, `roleName`, `permissions`, `scopeId`.
23
+
24
+ **Tables seeded:** `hazo_roles` → `hazo_user_roles` → `hazo_permissions` →
25
+ `hazo_role_permissions` → `hazo_scopes` → `hazo_user_scopes`.
26
+
27
+ **Idempotent:** if the same `role`/`permission`/`scopeId` is passed across
28
+ multiple `createTestUser` calls in one test DB, rows are reused (`INSERT OR
29
+ IGNORE` on junction tables, `findOne`-or-create on entity tables). No
30
+ UNIQUE-constraint errors.
31
+
32
+ **Resolves:** `hazo_testing/design/feature_requests/FR-001-permissioned-user-factory.md`
33
+
34
+ ---
35
+
3
36
  ## 0.2.0 — 2026-06-11
4
37
 
5
38
  ### Added — Vitest-compatible surfaces (additive; Jest preset unchanged)
package/README.md CHANGED
@@ -105,20 +105,35 @@ These are thin shims over `createCrudService` from `hazo_connect`. They handle U
105
105
  ```ts
106
106
  import { createTestUser } from "hazo_testing";
107
107
 
108
+ // Bare user — just a hazo_users row + session cookie (backward-compatible):
108
109
  const user = await createTestUser(adapter, {
109
110
  email: "alice@example.com",
110
111
  name: "Alice", // optional — defaults to email prefix
111
- columnOverrides: { role: "admin" }, // app-specific columns
112
+ columnOverrides: { url_on_logon: "/home" }, // any nullable hazo_users column
112
113
  });
113
-
114
- // user.id — generated UUID
115
- // user.email — "alice@example.com"
114
+ // user.id — generated UUID
115
+ // user.email — "alice@example.com"
116
116
  // user.sessionCookie — ready "Cookie:" header string
117
+
118
+ // Permissioned user — seeds the full role/permission/scope chain in one call:
119
+ const admin = await createTestUser(adapter, {
120
+ email: "admin@example.com",
121
+ role: "admin", // role name; auto-created if absent
122
+ permissions: ["system.access", "file.upload"], // permission names; auto-created
123
+ scopeId: "org-1", // scope id; auto-created if absent
124
+ scopeName: "Acme Corp", // optional — defaults to scopeId
125
+ scopeLevel: "firm", // optional — defaults to "firm"
126
+ });
127
+ // admin.roleId — id of the hazo_roles row
128
+ // admin.roleName — "admin"
129
+ // admin.permissions — ["system.access", "file.upload"]
130
+ // admin.scopeId — "org-1"
117
131
  ```
118
132
 
119
133
  - Writes a real `hazo_users` row. Note: the column is `email_address` in the schema; the factory maps the `email` option automatically.
120
134
  - Mints a session cookie using HS256 JWT (same algorithm as `hazo_auth`) signed with `process.env.JWT_SECRET`.
121
- - **v0.1.0 limitation:** `createTestUser` does NOT write a `hazo_user_scopes` membership row. The `hazo_user_scopes` schema requires `root_scope_id` and `role_id` FKs pointing to existing `hazo_roles` rows — this setup is deferred. Pass the returned `id` to your own membership setup if needed.
135
+ - When `role`, `permissions`, or `scopeId` are given, seeds the full chain across `hazo_roles`, `hazo_user_roles`, `hazo_permissions`, `hazo_role_permissions`, `hazo_scopes`, and `hazo_user_scopes`. All rows are reused-or-created, so multiple calls sharing the same role/scopeId in one DB are idempotent.
136
+ - Bare calls (no chain opts) return only `{ id, email, sessionCookie }` — unchanged from v0.2.x.
122
137
 
123
138
  ### `createTestScope`
124
139
 
@@ -1,7 +1,5 @@
1
1
  # Setup Checklist
2
2
 
3
- ## v0.1.0 — initial setup
4
-
5
3
  ### 1. Add the dev dependency
6
4
 
7
5
  ```bash
@@ -105,7 +103,7 @@ If you use `hazo_testing/nextjs` for in-process server tests, install the option
105
103
  npm install --save-dev next
106
104
  ```
107
105
 
108
- ### 9. (Optional, 0.2.0) Use the Vitest preset instead of Jest
106
+ ### 9. (Optional) Use the Vitest preset instead of Jest (v0.2.0+)
109
107
 
110
108
  `hazo_testing/vitest-preset` is an ESM config factory — the Vitest counterpart
111
109
  to `hazo_testing/jest-preset`. Create `vitest.config.ts`:
@@ -2,13 +2,27 @@ import type { AugmentedAdapter } from "../db/augmented_adapter.js";
2
2
  export interface CreateTestUserOptions {
3
3
  email: string;
4
4
  name?: string;
5
+ /** Role name to assign. Auto-created if it doesn't exist yet. */
5
6
  role?: string;
7
+ /** Scope id to assign the user to. Auto-created if it doesn't exist yet. */
6
8
  scopeId?: string;
9
+ /** Name for the auto-created scope row (defaults to scopeId). */
10
+ scopeName?: string;
11
+ /** Level for the auto-created scope row (defaults to "firm"). */
12
+ scopeLevel?: string;
13
+ /** Permission names to grant via the role. Auto-created if they don't exist. */
14
+ permissions?: string[];
7
15
  columnOverrides?: Record<string, unknown>;
8
16
  }
9
17
  export interface TestUser {
10
18
  id: string;
11
19
  email: string;
12
20
  sessionCookie: string;
21
+ /** Populated only when role/permissions/scopeId were given. */
22
+ roleId?: string;
23
+ roleName?: string;
24
+ /** The permission names that were seeded (parallel to opts.permissions). */
25
+ permissions?: string[];
26
+ scopeId?: string;
13
27
  }
14
28
  export declare function createTestUser(adapter: AugmentedAdapter, opts: CreateTestUserOptions): Promise<TestUser>;
@@ -8,6 +8,9 @@
8
8
  // Jest imports). We replicate the same HS256 logic.
9
9
  // - Cookie string is built as "hazo_auth_session=<token>" without calling
10
10
  // get_cookie_name (which requires a hazo_auth_config.ini with cookie_prefix).
11
+ // - Junction tables (hazo_user_roles, hazo_role_permissions, hazo_user_scopes)
12
+ // have composite PKs and no `id` column, so we bypass insertOne (which
13
+ // auto-injects an id) and use rawQuery with INSERT OR IGNORE instead.
11
14
  import { SignJWT } from "jose";
12
15
  /**
13
16
  * Mint a JWT with the same algorithm/claims as hazo_auth's create_session_token.
@@ -27,6 +30,15 @@ async function mintSessionToken(user_id, email) {
27
30
  .setExpirationTime(exp)
28
31
  .sign(secret);
29
32
  }
33
+ /**
34
+ * Parameterized INSERT into a junction table that has no `id` column.
35
+ * INSERT OR IGNORE keeps calls idempotent against duplicate composite keys.
36
+ * Uses rawQuery (SqliteAdapter-specific; cast to any mirrors how execScript
37
+ * is accessed elsewhere in the package).
38
+ */
39
+ async function insertJunction(adapter, sql, params) {
40
+ await adapter.rawQuery(sql, { params });
41
+ }
30
42
  export async function createTestUser(adapter, opts) {
31
43
  const row = await adapter.insertOne("hazo_users", {
32
44
  // hazo_users uses email_address, not email
@@ -36,9 +48,57 @@ export async function createTestUser(adapter, opts) {
36
48
  });
37
49
  const token = await mintSessionToken(row.id, opts.email);
38
50
  // Build a minimal session cookie string (no prefix — mirrors a default-prefix app).
39
- // The test only asserts sessionCookie.toMatch(/=/) so this is sufficient.
40
51
  const sessionCookie = `hazo_auth_session=${token}; ` +
41
52
  `hazo_auth_user_id=${row.id}; ` +
42
53
  `hazo_auth_user_email=${encodeURIComponent(opts.email)}`;
43
- return { id: row.id, email: opts.email, sessionCookie };
54
+ const base = { id: row.id, email: opts.email, sessionCookie };
55
+ // Short-circuit: if no role/permissions/scope requested, stay backward-compatible
56
+ // and return the same shape as v0.2.x (no extra fields on the result).
57
+ const needsChain = Boolean(opts.role || opts.permissions?.length || opts.scopeId);
58
+ if (!needsChain)
59
+ return base;
60
+ // --- Role (required whenever permissions or a scope are involved,
61
+ // because hazo_user_scopes.role_id is NOT NULL). ---
62
+ const roleName = opts.role ?? `role_${row.id.slice(0, 8)}`;
63
+ let roleRow = await adapter.findOne("hazo_roles", { role_name: roleName });
64
+ if (!roleRow) {
65
+ roleRow = await adapter.insertOne("hazo_roles", { role_name: roleName });
66
+ }
67
+ const roleId = roleRow.id;
68
+ await insertJunction(adapter, "INSERT OR IGNORE INTO hazo_user_roles (user_id, role_id) VALUES (?, ?)", [row.id, roleId]);
69
+ // --- Permissions ---
70
+ const seededPermissions = [];
71
+ for (const permName of opts.permissions ?? []) {
72
+ let permRow = await adapter.findOne("hazo_permissions", { permission_name: permName });
73
+ if (!permRow) {
74
+ permRow = await adapter.insertOne("hazo_permissions", { permission_name: permName });
75
+ }
76
+ await insertJunction(adapter, "INSERT OR IGNORE INTO hazo_role_permissions (role_id, permission_id) VALUES (?, ?)", [roleId, permRow.id]);
77
+ seededPermissions.push(permName);
78
+ }
79
+ // --- Scope ---
80
+ let resolvedScopeId;
81
+ if (opts.scopeId) {
82
+ const scopeId = opts.scopeId;
83
+ let scopeRow = await adapter.findOne("hazo_scopes", { id: scopeId });
84
+ if (!scopeRow) {
85
+ // Pass explicit id so the scope is addressable by the caller-supplied value.
86
+ // CrudService only generates an id when the field is absent, so this is honoured.
87
+ scopeRow = await adapter.insertOne("hazo_scopes", {
88
+ id: scopeId,
89
+ name: opts.scopeName ?? scopeId,
90
+ level: opts.scopeLevel ?? "firm",
91
+ });
92
+ }
93
+ // root_scope_id == scope_id for a single-level (root) scope.
94
+ await insertJunction(adapter, "INSERT OR IGNORE INTO hazo_user_scopes (user_id, scope_id, root_scope_id, role_id) VALUES (?, ?, ?, ?)", [row.id, scopeId, scopeId, roleId]);
95
+ resolvedScopeId = scopeId;
96
+ }
97
+ return {
98
+ ...base,
99
+ roleId,
100
+ roleName,
101
+ ...(seededPermissions.length ? { permissions: seededPermissions } : {}),
102
+ ...(resolvedScopeId !== undefined ? { scopeId: resolvedScopeId } : {}),
103
+ };
44
104
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const HAZO_TESTING_VERSION = "0.2.0";
1
+ export declare const HAZO_TESTING_VERSION = "0.3.0";
2
2
  export { DockerNotSupported, UnmappedLlmCall } from "./errors.js";
3
3
  export { augmentAdapter } from "./db/augmented_adapter.js";
4
4
  export type { AugmentedAdapter } from "./db/augmented_adapter.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/index.ts
2
2
  // hazo_testing public server barrel.
3
- export const HAZO_TESTING_VERSION = "0.2.0";
3
+ export const HAZO_TESTING_VERSION = "0.3.0";
4
4
  export { DockerNotSupported, UnmappedLlmCall } from "./errors.js";
5
5
  export { augmentAdapter } from "./db/augmented_adapter.js";
6
6
  export { createTestDatabase, createTestDatabaseSqlite, createTestDatabaseDocker, } from "./db/test_database.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hazo_testing",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Shared test infrastructure for hazo apps: SQLite test DB, real-package wiring, auth factories, apiTestClient, fixtures, Jest + Vitest presets.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,7 +49,9 @@
49
49
  "scripts": {
50
50
  "build": "tsc -p tsconfig.build.json",
51
51
  "lint": "tsc --noEmit",
52
- "test": "NODE_OPTIONS=--experimental-vm-modules jest"
52
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
53
+ "dev:test-app": "npm run build && cd test-app && npm run dev",
54
+ "build:test-app": "npm run build && cd test-app && npm run build"
53
55
  },
54
56
  "dependencies": {
55
57
  "axe-core": "^4.12.1",
@@ -59,7 +61,7 @@
59
61
  "@playwright/test": "^1.0.0",
60
62
  "@testing-library/react": "^16.0.0",
61
63
  "hazo_auth": "^10.0.0",
62
- "hazo_connect": "^3.4.1",
64
+ "hazo_connect": "^3.5.1",
63
65
  "hazo_core": "^1.1.0",
64
66
  "hazo_jobs": "^0.12.0",
65
67
  "hazo_llm_api": "^2.1.0",