@smplcty/auth 7.0.1 → 8.1.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/README.md CHANGED
@@ -482,11 +482,11 @@ The library ships its schema as schema-flow YAML inside the package at `@smplcty
482
482
  @smplcty/auth/schema/
483
483
  ├── tables/
484
484
  │ ├── users.yaml # + audit; seeds the app-init service user (matched by name)
485
- │ ├── tenants.yaml # + audit; slug (sub-domain), allow_otp (SSO-only switch)
485
+ │ ├── tenants.yaml # + audit; slug (sub-domain, DNS-label CHECK), allow_otp (SSO-only switch)
486
486
  │ ├── roles.yaml # + audit; seeds 'user' (default), 'settings', 'security'
487
487
  │ ├── user_roles.yaml # + audit; tenant_id NULL = wildcard / all tenants
488
488
  │ ├── communication_channels.yaml # + audit
489
- │ ├── user_communication_methods.yaml # + audit
489
+ │ ├── user_communication_methods.yaml # + audit; qualifier (optional consumer-defined label)
490
490
  │ ├── auth_domains.yaml # + audit; tenant's IdP(s), 1:N, resolved by id (display_name = button)
491
491
  │ ├── sessions.yaml # PK = token hash; last_seen_at; geo
492
492
  │ └── dev_otp_enrollments.yaml
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smplcty/auth",
3
- "version": "7.0.1",
3
+ "version": "8.1.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",
@@ -0,0 +1,28 @@
1
+ name: auth_all_tenants
2
+ language: plpgsql
3
+ volatility: stable
4
+ security: definer
5
+ # True when the current actor holds any live wildcard role — a user_roles row
6
+ # with tenant_id IS NULL, which reaches every tenant (surfaced elsewhere as the
7
+ # app.all_tenants GUC). The all-access companion to auth_tenant_ids: a wildcard
8
+ # grant can't be enumerated into a finite id set, so scope tests OR this against
9
+ # `tenant_id IN (SELECT auth_tenant_ids())`. False when there is no actor.
10
+ #
11
+ # Wrap the call in a subquery — `(SELECT auth_all_tenants())` — in a policy so
12
+ # the planner evaluates it as an InitPlan ONCE per query instead of per row.
13
+ returns: boolean
14
+ args: []
15
+ body: |
16
+ BEGIN
17
+ RETURN EXISTS (
18
+ SELECT 1
19
+ FROM user_roles ur
20
+ WHERE ur.user_id = current_user_id()
21
+ AND ur.deleted_at IS NULL
22
+ AND ur.tenant_id IS NULL
23
+ );
24
+ END;
25
+ comment: >
26
+ True if the current actor holds any live wildcard (all-tenants) role. The
27
+ all-access companion to auth_tenant_ids. SECURITY DEFINER so RLS policies can
28
+ use it without recursing on user_roles.
@@ -9,27 +9,37 @@ security: definer
9
9
  # `user_data` shape:
10
10
  # {
11
11
  # "name": "Ada Lovelace",
12
- # "communication_methods": [ { "channel": "email", "code": "ada@acme.com" } ],
12
+ # "communication_methods": [ { "channel": "email", "code": "ada@acme.com", "qualifier": "work" } ],
13
13
  # "accesses": [ { "tenant_id": 5, "role_id": 2 } ]
14
14
  # }
15
15
  # At least one communication method and one access are required. `channel` is
16
16
  # resolved by name; `tenant_id`/`role_id` are ids the caller already resolved
17
17
  # (the library pins none). A NULL/absent tenant_id is an all-tenants grant.
18
+ # `qualifier` is an optional, consumer-defined free-text label on a method
19
+ # (absent → NULL); the library stores it verbatim and never interprets it.
18
20
  #
19
21
  # Authority: the caller must hold `security` over every tenant in `accesses`;
20
22
  # an all-tenants grant requires holding `security` globally. Any failure aborts
21
23
  # the whole call — no partially-provisioned user is left behind. SECURITY
22
24
  # DEFINER does the writes RLS would otherwise block, but current_user_id() still
23
25
  # resolves to the caller, so the checks run against the calling admin.
26
+ #
27
+ # Duplicate-contact contract: if any requested (channel, code) already belongs
28
+ # to a live communication method, this raises SQLSTATE 23505 (unique_violation)
29
+ # with a message naming the channel — a stable, catchable signal a consumer can
30
+ # map to a 4xx ("that email/phone is already in use") without parsing constraint
31
+ # names. 23505 is raised ONLY for this case; every other failure carries the
32
+ # default raise_exception code (P0001).
24
33
  returns: bigint
25
34
  args:
26
35
  - name: user_data
27
36
  type: jsonb
28
37
  body: |
29
38
  DECLARE
30
- v_user_id bigint;
31
- v_access jsonb;
32
- v_methods int;
39
+ v_user_id bigint;
40
+ v_access jsonb;
41
+ v_methods int;
42
+ v_dup_channel text;
33
43
  BEGIN
34
44
  IF current_user_id() IS NULL THEN
35
45
  RAISE EXCEPTION 'auth_create_user: no authenticated actor (app.actor_id is unset)';
@@ -55,12 +65,33 @@ body: |
55
65
  END IF;
56
66
  END LOOP;
57
67
 
68
+ -- Friendly duplicate-contact check. A live ucm row already holding one of
69
+ -- the requested (channel, code) pairs would hit the partial-unique index and
70
+ -- surface as a raw 23505 the consumer can't tell from any other constraint.
71
+ -- Detect it up front and re-raise as unique_violation with a message naming
72
+ -- the channel, so a consumer maps it to a 4xx without parsing constraint
73
+ -- names. Done before the users INSERT so a doomed call burns no sequence
74
+ -- value. (The unique index remains the backstop for a concurrent race.)
75
+ SELECT cc.name INTO v_dup_channel
76
+ FROM jsonb_array_elements(user_data -> 'communication_methods') AS m
77
+ JOIN communication_channels cc
78
+ ON cc.name = m ->> 'channel' AND cc.deleted_at IS NULL
79
+ JOIN user_communication_methods ucm
80
+ ON ucm.communication_channel_id = cc.communication_channel_id
81
+ AND ucm.code = m ->> 'code'
82
+ AND ucm.deleted_at IS NULL
83
+ LIMIT 1;
84
+ IF v_dup_channel IS NOT NULL THEN
85
+ RAISE EXCEPTION 'auth_create_user: a user with this % already exists', v_dup_channel
86
+ USING ERRCODE = 'unique_violation';
87
+ END IF;
88
+
58
89
  INSERT INTO users (name, kind)
59
90
  VALUES (user_data ->> 'name', 'human')
60
91
  RETURNING user_id INTO v_user_id;
61
92
 
62
- INSERT INTO user_communication_methods (user_id, communication_channel_id, code)
63
- SELECT v_user_id, cc.communication_channel_id, m ->> 'code'
93
+ INSERT INTO user_communication_methods (user_id, communication_channel_id, code, qualifier)
94
+ SELECT v_user_id, cc.communication_channel_id, m ->> 'code', m ->> 'qualifier'
64
95
  FROM jsonb_array_elements(user_data -> 'communication_methods') AS m
65
96
  JOIN communication_channels cc
66
97
  ON cc.name = m ->> 'channel' AND cc.deleted_at IS NULL;
@@ -0,0 +1,37 @@
1
+ name: auth_tenant_ids
2
+ language: plpgsql
3
+ volatility: stable
4
+ security: definer
5
+ # The set of tenant ids the current actor holds a live, tenant-scoped role in
6
+ # (wildcard grants — user_roles.tenant_id IS NULL — are NOT in this set; test
7
+ # them with auth_all_tenants()). Returns nothing when there is no actor.
8
+ #
9
+ # This is the set-based, planner-friendly counterpart to auth_in_tenant. Used in
10
+ # an *uncorrelated* subquery an RLS policy resolves ONCE per query rather than
11
+ # once per row:
12
+ #
13
+ # USING (
14
+ # (SELECT auth_all_tenants()) -- InitPlan, evaluated once
15
+ # OR tenant_id IN (SELECT auth_tenant_ids()) -- hashed SubPlan, materialized once
16
+ # )
17
+ #
18
+ # Because the membership set is independent of the scanned row, the planner
19
+ # folds it into a hashed SubPlan and probes it per row instead of re-running a
20
+ # SECURITY DEFINER function per row (auth_in_tenant's cost on large scans). Keep
21
+ # auth_in_tenant for scalar/one-off call sites; reach for this on hot scan paths.
22
+ returns: SETOF bigint
23
+ args: []
24
+ body: |
25
+ BEGIN
26
+ RETURN QUERY
27
+ SELECT ur.tenant_id
28
+ FROM user_roles ur
29
+ WHERE ur.user_id = current_user_id()
30
+ AND ur.deleted_at IS NULL
31
+ AND ur.tenant_id IS NOT NULL;
32
+ END;
33
+ comment: >
34
+ The set of tenant ids the current actor holds a live, tenant-scoped role in
35
+ (wildcard grants excluded — see auth_all_tenants). SECURITY DEFINER so RLS
36
+ policies can use it in an uncorrelated subquery — resolved once per query, not
37
+ per row — without recursing on user_roles.
@@ -25,6 +25,13 @@ columns:
25
25
  type: boolean
26
26
  nullable: false
27
27
  default: true
28
+ checks:
29
+ # The slug IS the sub-domain (acme.app.com), so it must be a valid DNS label:
30
+ # lowercase alphanumerics and internal hyphens, no leading/trailing hyphen. An
31
+ # invalid slug is an unroutable host, so reject it at the DB rather than leave
32
+ # every consumer to re-declare this. NULL-safe: slug is optional.
33
+ - name: tenants_slug_format_check
34
+ expression: "slug IS NULL OR slug ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$'"
28
35
  indexes:
29
36
  # Partial so a tenant name can be reused after the row is soft-deleted.
30
37
  - columns: [name]
@@ -47,7 +54,14 @@ policies:
47
54
  for: SELECT
48
55
  to: app_rls
49
56
  permissive: true
50
- using: auth_in_tenant(tenants.tenant_id)
57
+ # Decorrelated scope test: the actor's reachable tenants are resolved once
58
+ # per query (InitPlan + hashed SubPlan) rather than once per row, so this
59
+ # scales on large scans. Equivalent to auth_in_tenant(tenants.tenant_id) —
60
+ # which stays for scalar call sites — but planner-friendly. See
61
+ # auth_tenant_ids / auth_all_tenants.
62
+ using: |-
63
+ (SELECT auth_all_tenants())
64
+ OR tenants.tenant_id IN (SELECT auth_tenant_ids())
51
65
  - name: tenants_insert
52
66
  for: INSERT
53
67
  to: app_rls
@@ -23,6 +23,13 @@ columns:
23
23
  - name: code
24
24
  type: text
25
25
  nullable: false
26
+ # Optional, consumer-defined free-text label distinguishing multiple methods
27
+ # of the same channel (e.g. "work" vs "home" phone). The library never
28
+ # interprets, requires, or populates it — it exists so consumers don't carry a
29
+ # ucm extend solely for this one column. NULL when unset.
30
+ - name: qualifier
31
+ type: text
32
+ nullable: true
26
33
  indexes:
27
34
  # Partial so a (channel, code) can be reused after the row is soft-deleted.
28
35
  - columns: [communication_channel_id, code]