@smplcty/auth 0.6.3 → 1.0.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 (93) hide show
  1. package/README.md +198 -223
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +18 -23
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/dev-otp.d.ts.map +1 -1
  7. package/dist/dev-otp.js +4 -10
  8. package/dist/dev-otp.js.map +1 -1
  9. package/dist/errors.d.ts +19 -4
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +23 -5
  12. package/dist/errors.js.map +1 -1
  13. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  14. package/dist/find-user-by-communication-method.js +8 -1
  15. package/dist/find-user-by-communication-method.js.map +1 -1
  16. package/dist/get-user-role-names.d.ts.map +1 -1
  17. package/dist/get-user-role-names.js +2 -0
  18. package/dist/get-user-role-names.js.map +1 -1
  19. package/dist/index.d.ts +10 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +13 -7
  22. package/dist/index.js.map +1 -1
  23. package/dist/internal/hash-token.d.ts +16 -0
  24. package/dist/internal/hash-token.d.ts.map +1 -0
  25. package/dist/internal/hash-token.js +21 -0
  26. package/dist/internal/hash-token.js.map +1 -0
  27. package/dist/methods/errors.d.ts +37 -0
  28. package/dist/methods/errors.d.ts.map +1 -0
  29. package/dist/methods/errors.js +48 -0
  30. package/dist/methods/errors.js.map +1 -0
  31. package/dist/methods/oidc/index.d.ts +65 -0
  32. package/dist/methods/oidc/index.d.ts.map +1 -0
  33. package/dist/methods/oidc/index.js +76 -0
  34. package/dist/methods/oidc/index.js.map +1 -0
  35. package/dist/methods/router.d.ts +39 -0
  36. package/dist/methods/router.d.ts.map +1 -0
  37. package/dist/methods/router.js +153 -0
  38. package/dist/methods/router.js.map +1 -0
  39. package/dist/methods/twilio/index.d.ts +44 -0
  40. package/dist/methods/twilio/index.d.ts.map +1 -0
  41. package/dist/methods/twilio/index.js +77 -0
  42. package/dist/methods/twilio/index.js.map +1 -0
  43. package/dist/methods/types.d.ts +124 -0
  44. package/dist/methods/types.d.ts.map +1 -0
  45. package/dist/methods/types.js +2 -0
  46. package/dist/methods/types.js.map +1 -0
  47. package/dist/revoke-session.d.ts +20 -15
  48. package/dist/revoke-session.d.ts.map +1 -1
  49. package/dist/revoke-session.js +66 -20
  50. package/dist/revoke-session.js.map +1 -1
  51. package/dist/scope/flat-tenant.d.ts +36 -0
  52. package/dist/scope/flat-tenant.d.ts.map +1 -0
  53. package/dist/scope/flat-tenant.js +60 -0
  54. package/dist/scope/flat-tenant.js.map +1 -0
  55. package/dist/set-helpers.d.ts +44 -53
  56. package/dist/set-helpers.d.ts.map +1 -1
  57. package/dist/set-helpers.js +67 -74
  58. package/dist/set-helpers.js.map +1 -1
  59. package/dist/touch-session.d.ts +13 -0
  60. package/dist/touch-session.d.ts.map +1 -0
  61. package/dist/touch-session.js +28 -0
  62. package/dist/touch-session.js.map +1 -0
  63. package/dist/types.d.ts +59 -18
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/validate-session.d.ts +15 -14
  66. package/dist/validate-session.d.ts.map +1 -1
  67. package/dist/validate-session.js +28 -27
  68. package/dist/validate-session.js.map +1 -1
  69. package/dist/with-service-context.d.ts +15 -12
  70. package/dist/with-service-context.d.ts.map +1 -1
  71. package/dist/with-service-context.js +34 -39
  72. package/dist/with-service-context.js.map +1 -1
  73. package/dist/with-session.d.ts +22 -16
  74. package/dist/with-session.d.ts.map +1 -1
  75. package/dist/with-session.js +67 -66
  76. package/dist/with-session.js.map +1 -1
  77. package/package.json +53 -4
  78. package/schema/functions/current_user_id.yaml +18 -0
  79. package/schema/functions/resolve_session.yaml +42 -23
  80. package/schema/post/0001-backfill-audit-by.sql +15 -0
  81. package/schema/tables/auth_domains.yaml +43 -0
  82. package/schema/tables/communication_channels.yaml +5 -1
  83. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  84. package/schema/tables/roles.yaml +43 -7
  85. package/schema/tables/sessions.yaml +10 -0
  86. package/schema/tables/tenants.yaml +24 -1
  87. package/schema/tables/user_communication_methods.yaml +5 -1
  88. package/schema/tables/user_roles.yaml +1 -0
  89. package/schema/tables/users.yaml +27 -0
  90. package/dist/with-transaction.d.ts +0 -31
  91. package/dist/with-transaction.d.ts.map +0 -1
  92. package/dist/with-transaction.js +0 -49
  93. package/dist/with-transaction.js.map +0 -1
@@ -1,108 +1,109 @@
1
- import { RoleNotAssignedError, SessionExpiredError, SessionNotFoundError, } from './errors.js';
1
+ import { withTransaction } from '@smplcty/db';
2
+ import { RoleNotHeldError, SessionExpiredError, SessionNotFoundError } from './errors.js';
2
3
  import { hashId } from './internal/hash-id.js';
4
+ import { hashToken } from './internal/hash-token.js';
3
5
  import { noopLogger } from './internal/noop-logger.js';
4
- import { setSessionContext } from './set-helpers.js';
5
- import { withTransaction } from './with-transaction.js';
6
+ import { setIdentityContext } from './set-helpers.js';
6
7
  /**
7
- * Resolves the session and the user's roles in one query. Returns null
8
- * if the session row doesn't exist or doesn't belong to a user with the
9
- * requested role.
10
- *
11
- * The query joins through `sessions → user_communication_methods → users
12
- * → user_roles → roles`, filtering by the requested role name. It also
13
- * computes:
14
- *
15
- * - `tenantIds`: distinct non-null tenant_ids on user_roles rows
16
- * - `allTenants`: true if any user_roles row has tenant_id IS NULL
17
- * - `roles`: array of all distinct role names assigned to the user
18
- *
19
- * The roles array is sourced from a separate inner join so we get every
20
- * role the user has, not just the one being requested. The `_hasRole`
21
- * column tells us whether the requested role specifically was found.
22
- */
23
- /**
24
- * Uses the resolve_session() SECURITY DEFINER function so the query
25
- * bypasses RLS on auth tables (user_communication_methods, user_roles).
26
- * This lets app_user resolve sessions without needing GUCs set first.
8
+ * Calls the pure `resolve_session` SECURITY DEFINER resolver so the read
9
+ * bypasses RLS on the auth tables (sessions, user_communication_methods,
10
+ * user_roles). The resolver validates nothing — it returns the user, the
11
+ * expiry, the roles the user holds, the default role, and the privileges.
12
+ * Validation and role selection happen here in TS.
27
13
  */
28
14
  const RESOLVE_SESSION = `
29
15
  SELECT
30
- user_id AS "userId",
31
- expires_at AS "expiresAt",
32
- tenant_ids AS "tenantIds",
33
- all_tenants AS "allTenants",
34
- roles AS "roles",
35
- has_requested_role AS "hasRequestedRole"
36
- FROM resolve_session($1, $2)
16
+ user_id AS "userId",
17
+ expires_at AS "expiresAt",
18
+ roles AS "roles",
19
+ default_role AS "defaultRole",
20
+ privileges AS "privileges"
21
+ FROM resolve_session($1)
37
22
  `;
38
23
  /**
39
- * The high-level "just make it work" entry point. Checks out a
40
- * connection, opens a transaction, validates the session, validates the
41
- * role, sets the four `app.*` GUC variables via parameterized
42
- * `set_config(_, _, true)`, runs the callback, and commits (or rolls
43
- * back on throw).
24
+ * The high-level "just make it work" request entry point. Opens a
25
+ * `@smplcty/db` transaction, resolves the session from its token, validates
26
+ * it, picks and validates the active role, sets the identity GUCs, runs the
27
+ * app scope hook, then runs the callback — committing on success or rolling
28
+ * back on throw.
29
+ *
30
+ * Active-role selection (in TS, not the resolver):
31
+ * 1. `roleName` if given — must be one the user holds, else {@link RoleNotHeldError}.
32
+ * 2. otherwise the user's default role, if any.
33
+ * 3. otherwise none — a privilege-only request, which is **not** an error.
44
34
  *
45
- * The session variables use **transaction scope**, so they're discarded
46
- * automatically when this function returns. Cross-request leakage is
47
- * impossible.
35
+ * Identity GUCs are transaction-local, so they vanish on COMMIT/ROLLBACK —
36
+ * no cross-request leakage. Scope GUCs are not set here: pass a `scope`
37
+ * hook (e.g. `flatTenantScope()`) for that, or rely on function-carried RLS.
48
38
  *
49
39
  * @example
50
40
  * ```ts
51
41
  * const widgets = await withSession(
52
42
  * pool,
53
- * { sessionId, roleName: 'user' },
43
+ * { token, roleName: 'user' },
54
44
  * async (client, ctx) => {
55
- * // ctx = { userId, tenantIds, allTenants, roles }
45
+ * // ctx = { userId, activeRole, roles, privileges }
56
46
  * const { rows } = await client.query('SELECT * FROM widgets');
57
47
  * return rows;
58
- * }
48
+ * },
49
+ * { scope: flatTenantScope() },
59
50
  * );
60
51
  * ```
61
52
  *
62
- * @throws {SessionNotFoundError} If no session row matches `auth.sessionId`.
63
- * @throws {SessionExpiredError} If the session has passed its `expires_at`.
64
- * @throws {RoleNotAssignedError} If the user does not have `auth.roleName`.
65
- * @throws {InvalidInputError} If `auth.sessionId` or `auth.roleName` is empty.
53
+ * @throws {SessionNotFoundError} If no session matches the token.
54
+ * @throws {SessionExpiredError} If the session has expired (or was revoked).
55
+ * @throws {RoleNotHeldError} If `roleName` is given but not held.
56
+ * @throws {InvalidInputError} If `token` is empty.
66
57
  */
67
58
  export async function withSession(pool, auth, fn, options = {}) {
68
59
  const log = options.logger ?? noopLogger;
69
- const sessionHash = hashId(auth.sessionId);
60
+ const tokenHash = hashToken(auth.token);
61
+ const fingerprint = hashId(auth.token);
70
62
  return withTransaction(pool, async (client) => {
71
- const { rows } = await client.query(RESOLVE_SESSION, [
72
- auth.sessionId,
73
- auth.roleName,
74
- ]);
63
+ const { rows } = await client.query(RESOLVE_SESSION, [tokenHash]);
75
64
  const row = rows[0];
76
65
  if (!row) {
77
- log.warn({ sessionHash }, 'session not found');
66
+ log.warn({ session: fingerprint }, 'session not found');
78
67
  throw new SessionNotFoundError();
79
68
  }
69
+ // Revocation is just expiry: revoke sets expires_at = now(). So an
70
+ // expired-or-revoked session fails the same check.
80
71
  if (row.expiresAt.getTime() <= Date.now()) {
81
- log.warn({ sessionHash, expiresAt: row.expiresAt.toISOString() }, 'session expired');
72
+ log.warn({ session: fingerprint, expiresAt: row.expiresAt.toISOString() }, 'session expired');
82
73
  throw new SessionExpiredError(row.expiresAt);
83
74
  }
84
- if (row.hasRequestedRole !== true) {
85
- log.warn({ sessionHash, userId: row.userId, requestedRole: auth.roleName }, 'role not assigned');
86
- throw new RoleNotAssignedError(auth.roleName);
75
+ // Active-role selection happens here, not in the resolver.
76
+ let activeRole;
77
+ if (auth.roleName !== undefined) {
78
+ if (!row.roles.includes(auth.roleName)) {
79
+ log.warn({ session: fingerprint, userId: row.userId, requestedRole: auth.roleName }, 'role not held');
80
+ throw new RoleNotHeldError(auth.roleName);
81
+ }
82
+ activeRole = auth.roleName;
83
+ }
84
+ else {
85
+ activeRole = row.defaultRole ?? null;
87
86
  }
88
87
  const ctx = {
89
88
  userId: row.userId,
90
- tenantIds: row.tenantIds,
91
- allTenants: row.allTenants,
89
+ activeRole,
92
90
  roles: row.roles,
91
+ privileges: row.privileges,
93
92
  };
94
- await setSessionContext(client, {
95
- sessionId: auth.sessionId,
96
- roleName: auth.roleName,
97
- tenantIds: ctx.tenantIds,
98
- allTenants: ctx.allTenants,
93
+ await setIdentityContext(client, {
94
+ actorId: ctx.userId,
95
+ sessionId: tokenHash,
96
+ activeRole: ctx.activeRole,
97
+ privileges: ctx.privileges,
99
98
  });
99
+ // App-owned intra-tenant scope. No-op when omitted.
100
+ await options.scope?.(client, ctx);
100
101
  log.debug({
101
- sessionHash,
102
+ session: fingerprint,
102
103
  userId: ctx.userId,
103
- roleName: auth.roleName,
104
- tenantCount: ctx.tenantIds.length,
105
- allTenants: ctx.allTenants,
104
+ activeRole: ctx.activeRole,
105
+ roleCount: ctx.roles.length,
106
+ privilegeCount: ctx.privileges.length,
106
107
  }, 'session context set');
107
108
  return fn(client, ctx);
108
109
  });
@@ -1 +1 @@
1
- {"version":3,"file":"with-session.js","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAMrD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD;;;;;;;;;;;;;;;;GA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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smplcty/auth",
3
- "version": "0.6.3",
3
+ "version": "1.0.0",
4
4
  "description": "Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,6 +11,21 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js",
13
13
  "default": "./dist/index.js"
14
+ },
15
+ "./oidc": {
16
+ "types": "./dist/methods/oidc/index.d.ts",
17
+ "import": "./dist/methods/oidc/index.js",
18
+ "default": "./dist/methods/oidc/index.js"
19
+ },
20
+ "./twilio": {
21
+ "types": "./dist/methods/twilio/index.d.ts",
22
+ "import": "./dist/methods/twilio/index.js",
23
+ "default": "./dist/methods/twilio/index.js"
24
+ },
25
+ "./flat-tenant": {
26
+ "types": "./dist/scope/flat-tenant.d.ts",
27
+ "import": "./dist/scope/flat-tenant.js",
28
+ "default": "./dist/scope/flat-tenant.js"
14
29
  }
15
30
  },
16
31
  "files": [
@@ -49,27 +64,61 @@
49
64
  "build": "tsc -p tsconfig.build.json",
50
65
  "clean": "rm -rf dist",
51
66
  "lint": "eslint src tests",
67
+ "format": "prettier --check .",
68
+ "format:fix": "prettier --write .",
52
69
  "typecheck": "tsc --noEmit",
53
70
  "test": "vitest run",
54
71
  "test:watch": "vitest",
55
- "release": "GITHUB_TOKEN=$(gh auth token) release-it --ci"
72
+ "prepare": "husky",
73
+ "release": "GITHUB_TOKEN=$(gh auth token) release-it",
74
+ "release:patch": "GITHUB_TOKEN=$(gh auth token) release-it patch",
75
+ "release:minor": "GITHUB_TOKEN=$(gh auth token) release-it minor",
76
+ "release:major": "GITHUB_TOKEN=$(gh auth token) release-it major"
77
+ },
78
+ "lint-staged": {
79
+ "*.{ts,js}": [
80
+ "eslint --fix",
81
+ "prettier --write"
82
+ ],
83
+ "*.{json,md,yaml,yml}": [
84
+ "prettier --write"
85
+ ]
56
86
  },
57
87
  "peerDependencies": {
88
+ "@smplcty/oidc": ">=0.2.0",
89
+ "@smplcty/twilio": ">=0.1.0",
58
90
  "pg": ">=8.0.0"
59
91
  },
92
+ "peerDependenciesMeta": {
93
+ "@smplcty/oidc": {
94
+ "optional": true
95
+ },
96
+ "@smplcty/twilio": {
97
+ "optional": true
98
+ }
99
+ },
60
100
  "devDependencies": {
61
101
  "@eslint/js": "^10.0.1",
62
- "@smplcty/schema-flow": "^0.3.7",
102
+ "@release-it/keep-a-changelog": "^7.1.0",
103
+ "@smplcty/oidc": "^0.2.0",
104
+ "@smplcty/schema-flow": "^0.11.2",
105
+ "@smplcty/twilio": "^0.1.1",
106
+ "@testcontainers/postgresql": "^12.0.1",
63
107
  "@types/node": "^25.5.2",
64
108
  "@types/pg": "^8.20.0",
65
109
  "eslint": "^10.2.0",
110
+ "husky": "^9.1.7",
111
+ "lint-staged": "^17.0.7",
66
112
  "pg": "^8.20.0",
113
+ "prettier": "^3.8.4",
114
+ "release-it": "^20.2.0",
67
115
  "typescript": "^6.0.2",
68
116
  "typescript-eslint": "^8.58.1",
69
- "release-it": "^19.2.4",
70
117
  "vitest": "^4.1.4"
71
118
  },
72
119
  "dependencies": {
120
+ "@smplcty/db": "^4.2.0",
121
+ "@smplcty/schema-std": "^0.0.1",
73
122
  "otplib": "^13.4.0"
74
123
  }
75
124
  }
@@ -0,0 +1,18 @@
1
+ name: current_user_id
2
+ language: sql
3
+ volatility: stable
4
+ # Reads the per-request actor from the app.actor_id GUC (set by
5
+ # withSession / withServiceContext). This is the join key for app RLS and
6
+ # scope functions: policies that need "the current user" call this rather
7
+ # than re-reading the GUC themselves.
8
+ #
9
+ # Returns NULL when no actor is set (unauthenticated / outside a request
10
+ # context) — RLS policies treat a NULL current user as "see nothing".
11
+ returns: integer
12
+ args: []
13
+ body: |
14
+ SELECT NULLIF(current_setting('app.actor_id', true), '')::integer;
15
+ comment: >
16
+ Returns the current request's actor (users.user_id) from the
17
+ app.actor_id GUC, or NULL if unset. The stable, RLS-friendly accessor
18
+ app scope functions key on.
@@ -2,47 +2,66 @@ name: resolve_session
2
2
  language: plpgsql
3
3
  volatility: stable
4
4
  security: definer
5
- returns: TABLE(user_id integer, expires_at timestamptz, tenant_ids integer[], all_tenants boolean, roles varchar[], has_requested_role boolean)
5
+ # A PURE resolver. Given a session token hash, it returns the session's
6
+ # user, its expiry, the user's selectable roles (split from privileges by
7
+ # roles.is_privilege), and the user's privileges. It takes NO role
8
+ # argument and validates NOTHING — not expiry, not revocation, not role
9
+ # membership. All of that lives in withSession (TS), so this SECURITY
10
+ # DEFINER surface stays a minimal read.
11
+ #
12
+ # roles — selectable mode/persona roles (is_privilege = false)
13
+ # default_role — the role names a NULL roleName falls back to (the first
14
+ # is_default role), or NULL if the user has no default
15
+ # privileges — always-on capability flags (is_privilege = true)
16
+ #
17
+ # Soft-delete aware: a soft-deleted session, communication method, or user
18
+ # is treated as non-existent (excluded), and soft-deleted role assignments /
19
+ # roles are dropped from the aggregates.
20
+ #
21
+ # Returns zero rows when no live session matches the hash (withSession maps
22
+ # that to SessionNotFound). Returns one row with empty arrays when the
23
+ # session exists but the user holds no roles.
24
+ returns: TABLE(user_id integer, expires_at timestamptz, roles text[], default_role text, privileges text[])
6
25
  args:
7
- - name: p_session_id
8
- type: text
9
- - name: p_role_name
26
+ - name: p_token_hash
10
27
  type: text
11
28
  body: |
12
29
  BEGIN
13
30
  RETURN QUERY
14
31
  WITH found_session AS (
15
- SELECT s.session_id, s.expires_at, ucm.user_id
32
+ SELECT s.expires_at, ucm.user_id
16
33
  FROM sessions s
17
34
  JOIN user_communication_methods ucm
18
35
  ON ucm.user_communication_method_id = s.user_communication_method_id
19
- WHERE s.session_id = p_session_id
36
+ JOIN users u ON u.user_id = ucm.user_id
37
+ WHERE s.session_id = p_token_hash
38
+ AND s.deleted_at IS NULL
39
+ AND ucm.deleted_at IS NULL
40
+ AND u.deleted_at IS NULL
20
41
  ),
21
- user_role_data AS (
22
- SELECT ur.user_id, ur.tenant_id, r.name AS role_name
42
+ role_data AS (
43
+ SELECT DISTINCT r.name::text AS name, r.is_default, r.is_privilege
23
44
  FROM found_session fs
24
- JOIN user_roles ur ON ur.user_id = fs.user_id
25
- JOIN roles r ON r.role_id = ur.role_id
45
+ JOIN user_roles ur ON ur.user_id = fs.user_id AND ur.deleted_at IS NULL
46
+ JOIN roles r ON r.role_id = ur.role_id AND r.deleted_at IS NULL
26
47
  )
27
48
  SELECT
28
49
  fs.user_id,
29
50
  fs.expires_at,
30
51
  COALESCE(
31
- array_agg(DISTINCT urd.tenant_id) FILTER (WHERE urd.tenant_id IS NOT NULL),
32
- '{}'::integer[]
52
+ (SELECT array_agg(rd.name ORDER BY rd.name) FROM role_data rd WHERE NOT rd.is_privilege),
53
+ '{}'::text[]
33
54
  ),
34
- COALESCE(bool_or(urd.tenant_id IS NULL), false),
55
+ (SELECT rd.name FROM role_data rd WHERE NOT rd.is_privilege AND rd.is_default ORDER BY rd.name LIMIT 1),
35
56
  COALESCE(
36
- array_agg(DISTINCT urd.role_name) FILTER (WHERE urd.role_name IS NOT NULL),
57
+ (SELECT array_agg(rd.name ORDER BY rd.name) FROM role_data rd WHERE rd.is_privilege),
37
58
  '{}'::text[]
38
- ),
39
- bool_or(urd.role_name = p_role_name)
40
- FROM found_session fs
41
- LEFT JOIN user_role_data urd ON urd.user_id = fs.user_id
42
- GROUP BY fs.user_id, fs.expires_at;
59
+ )
60
+ FROM found_session fs;
43
61
  END;
44
62
  comment: >
45
- SECURITY DEFINER function for resolving sessions without requiring
46
- RLS GUCs to be set first. Called by withSession so app_user can
47
- look up session → user → roles through RLS-protected tables.
48
- Returns aggregate role/tenant info only — does not expose raw PII.
63
+ SECURITY DEFINER pure resolver for sessions — bypasses RLS on auth
64
+ tables so app_user can read session → user → roles without GUCs set
65
+ first. Returns aggregate role/privilege info only (no raw PII); does
66
+ no validation (expiry, revocation, and role selection live in
67
+ withSession).
@@ -0,0 +1,15 @@
1
+ -- Bootstrap audit attribution for rows seeded during the migration.
2
+ --
3
+ -- The audit mixin (from @smplcty/schema-std) makes created_by/updated_by
4
+ -- NOT NULL, stamped from app.actor_id. But rows seeded *during* a schema-flow
5
+ -- run have no request actor, so they land with NULL _by — and schema-flow
6
+ -- seeds tables in dependency order that doesn't account for the audit FK, so
7
+ -- we can't simply pre-set the actor (a table may be seeded before app-init
8
+ -- exists). Instead we let the seeds land NULL and back-fill here: post-scripts
9
+ -- run after seeds but before the NOT NULL tighten phase.
10
+ --
11
+ -- audit_backfill_by (shipped by @smplcty/schema-std) fills every NULL
12
+ -- created_by/updated_by on every audit-mixin table in this schema, attributing
13
+ -- them to the app-init service principal. app-init's own row resolves the
14
+ -- self-reference (created_by = its own user_id).
15
+ SELECT audit_backfill_by((SELECT user_id FROM users WHERE name = 'app-init' AND kind = 'service'));
@@ -0,0 +1,43 @@
1
+ table: auth_domains
2
+ # Org-bound sign-in federation config: a tenant's IdP(s). A tenant has 0..N
3
+ # of these (1:N) — mergers, mixed workforces, and multi-domain orgs legitimately
4
+ # have more than one. The method router resolves sub-domain → tenant → its
5
+ # auth_domains: exactly one ⇒ straight redirect; several ⇒ the app shows a
6
+ # chooser (one button per row, labeled display_name, valued by auth_domain_id).
7
+ #
8
+ # This is SIGN-IN federation only. Tenant CRM data connections
9
+ # (HubSpot/Salesforce sync, etc.) are a separate, app-owned concern and
10
+ # do NOT live here. Even for the same vendor, "log in with Salesforce"
11
+ # (a row here) and "connect our Salesforce data" are distinct configs.
12
+ #
13
+ # Absorbed from @smplcty/oidc by the own-domain rule: auth_domains is
14
+ # auth's data model, so auth ships it. Rows are configured at runtime
15
+ # (admin UI) and resolved by auth_domain_id — there is no stable text key.
16
+ mixins: [audit, soft_delete]
17
+ columns:
18
+ - name: auth_domain_id
19
+ type: serial
20
+ primary_key: true
21
+ - name: tenant_id
22
+ type: integer
23
+ nullable: false
24
+ references:
25
+ table: tenants
26
+ column: tenant_id
27
+ # Human label for the sign-in button when a tenant has more than one IdP
28
+ # (e.g. "Microsoft", "Google Workspace").
29
+ - name: display_name
30
+ type: text
31
+ nullable: false
32
+ # 'oidc' | 'saml' | … — selects the MethodHandler. The library only
33
+ # interprets values it ships a handler for; unknown values are an
34
+ # app concern.
35
+ - name: integration_type
36
+ type: text
37
+ nullable: false
38
+ # Provider config + provisioning policy (issuer, clientId, redirect URI,
39
+ # default roles to grant on auto-provision, …). Shape is handler-specific.
40
+ - name: integration_params
41
+ type: jsonb
42
+ nullable: false
43
+ default: "'{}'::jsonb"
@@ -1,4 +1,5 @@
1
1
  table: communication_channels
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  - name: communication_channel_id
4
5
  type: serial
@@ -6,6 +7,9 @@ columns:
6
7
  - name: name
7
8
  type: text
8
9
  nullable: false
9
- unique_constraints:
10
+ indexes:
11
+ # Partial so a name can be reused after the row is soft-deleted.
10
12
  - columns: [name]
13
+ unique: true
14
+ where: 'deleted_at IS NULL'
11
15
  name: communication_channels_name_key
@@ -1,4 +1,5 @@
1
1
  table: dev_otp_enrollments
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  # The user_communication_method this enrollment is for. There can only
4
5
  # be one dev OTP enrollment per communication method (PK + FK).
@@ -1,19 +1,43 @@
1
1
  table: roles
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: role_id
4
5
  type: serial
5
6
  primary_key: true
6
7
  - name: name
7
- type: varchar(30)
8
+ type: varchar(50)
8
9
  nullable: false
9
- unique_constraints:
10
+ # Human-friendly label for UI (role switcher, admin screens).
11
+ - name: display_name
12
+ type: text
13
+ - name: description
14
+ type: text
15
+ # The role auto-selected by withSession when no roleName is requested.
16
+ # An app should mark exactly one is_privilege=false role as default;
17
+ # the library just picks the first default it finds.
18
+ - name: is_default
19
+ type: boolean
20
+ nullable: false
21
+ default: false
22
+ # is_privilege=false → a selectable mode/persona role. These drive the
23
+ # role switcher and become app.active_role for the request.
24
+ # is_privilege=true → an always-on capability flag. These are never
25
+ # "selected"; every privilege the user holds is exported in
26
+ # app.privileges for the request.
27
+ - name: is_privilege
28
+ type: boolean
29
+ nullable: false
30
+ default: false
31
+ indexes:
32
+ # Partial so a role name can be reused after the row is soft-deleted.
10
33
  - columns: [name]
34
+ unique: true
35
+ where: 'deleted_at IS NULL'
11
36
  name: roles_name_key
12
- # The canonical role names @smplcty/auth's withSession() validates against.
13
- #
14
- # IDs 1-3 are reserved for these standard roles. Consumers adding their
15
- # own roles should use IDs >= 100 to avoid colliding with future
16
- # standard-role additions. The library never references these IDs
37
+ # The canonical role names shipped with @smplcty/auth. IDs 1-3 are
38
+ # reserved for these standard mode roles. Consumers adding their own
39
+ # roles (or privileges) should use IDs >= 100 to avoid colliding with
40
+ # future standard-role additions. The library never references these IDs
17
41
  # directly — it always looks up by name — so the IDs are just a stable
18
42
  # convention for migration-time conflict detection.
19
43
  #
@@ -22,8 +46,20 @@ unique_constraints:
22
46
  seeds:
23
47
  - role_id: 1
24
48
  name: 'user'
49
+ display_name: 'User'
50
+ description: 'Standard signed-in user.'
51
+ is_default: true
52
+ is_privilege: false
25
53
  - role_id: 2
26
54
  name: 'settings'
55
+ display_name: 'Settings'
56
+ description: 'Account and organisation settings access.'
57
+ is_default: false
58
+ is_privilege: false
27
59
  - role_id: 3
28
60
  name: 'security'
61
+ display_name: 'Security'
62
+ description: 'Security administration.'
63
+ is_default: false
64
+ is_privilege: false
29
65
  seeds_on_conflict: 'DO NOTHING'
@@ -1,4 +1,10 @@
1
1
  table: sessions
2
+ # soft_delete adds deleted_at. A session is invalid when EITHER expires_at
3
+ # has passed (revokeSession sets it to now()) OR deleted_at is set — the app
4
+ # sets deleted_at to "forget" a session/device. resolve_session and
5
+ # validateSession honor both; the library ships no delete setter (it's a
6
+ # plain column write the app owns).
7
+ mixins: [soft_delete]
2
8
  columns:
3
9
  - name: session_id
4
10
  type: text
@@ -16,6 +22,10 @@ columns:
16
22
  - name: expires_at
17
23
  type: timestamptz
18
24
  nullable: false
25
+ # Updated by touchSession on activity. Powers the "track activity"
26
+ # requirement — distinct from created_at (sign-in time).
27
+ - name: last_seen_at
28
+ type: timestamptz
19
29
  - name: ip
20
30
  type: text
21
31
  - name: city
@@ -1,4 +1,5 @@
1
1
  table: tenants
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: tenant_id
4
5
  type: serial
@@ -6,6 +7,28 @@ columns:
6
7
  - name: name
7
8
  type: text
8
9
  nullable: false
9
- unique_constraints:
10
+ # Sub-domain / URL slug, e.g. "acme" in acme.app.com. The app parses the
11
+ # request Host to this slug; the method router resolves slug → tenant →
12
+ # its auth_domains, so OIDC sign-in needs no "which org are you?" form.
13
+ # Nullable: multitenancy (and sub-domains) are optional for simple apps.
14
+ - name: slug
15
+ type: text
16
+ # Whether user-bound OTP (Twilio) sign-in is allowed for this tenant.
17
+ # Irrelevant when the tenant has no auth_domain (OTP is the only way);
18
+ # set false to enforce SSO-only on a tenant that has OIDC. Enforced in the
19
+ # router, not just the UI.
20
+ - name: allow_otp
21
+ type: boolean
22
+ nullable: false
23
+ default: true
24
+ indexes:
25
+ # Partial so a tenant name can be reused after the row is soft-deleted.
10
26
  - columns: [name]
27
+ unique: true
28
+ where: 'deleted_at IS NULL'
11
29
  name: tenants_name_key
30
+ # Sub-domain slug is unique among live tenants.
31
+ - columns: [slug]
32
+ unique: true
33
+ where: 'deleted_at IS NULL'
34
+ name: tenants_slug_key
@@ -1,4 +1,5 @@
1
1
  table: user_communication_methods
2
+ mixins: [soft_delete]
2
3
  columns:
3
4
  - name: user_communication_method_id
4
5
  type: serial
@@ -18,6 +19,9 @@ columns:
18
19
  - name: code
19
20
  type: text
20
21
  nullable: false
21
- unique_constraints:
22
+ indexes:
23
+ # Partial so a (channel, code) can be reused after the row is soft-deleted.
22
24
  - columns: [communication_channel_id, code]
25
+ unique: true
26
+ where: 'deleted_at IS NULL'
23
27
  name: user_communication_methods_channel_code_key
@@ -1,4 +1,5 @@
1
1
  table: user_roles
2
+ mixins: [audit, soft_delete]
2
3
  columns:
3
4
  - name: user_role_id
4
5
  type: serial