@teamblind/axeda-core 0.0.0-stage → 0.1.0-alpha.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 (89) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +12 -2
  5. package/dist/application/assignments.d.ts +18 -0
  6. package/dist/application/assignments.js +190 -0
  7. package/dist/application/audit.d.ts +23 -0
  8. package/dist/application/audit.js +52 -0
  9. package/dist/application/authz-cache.d.ts +22 -0
  10. package/dist/application/authz-cache.js +40 -0
  11. package/dist/application/authz-reader.d.ts +30 -0
  12. package/dist/application/authz-reader.js +69 -0
  13. package/dist/application/bootstrap.d.ts +19 -0
  14. package/dist/application/bootstrap.js +78 -0
  15. package/dist/application/create-axeda.d.ts +101 -0
  16. package/dist/application/create-axeda.js +168 -0
  17. package/dist/application/invitation-token.d.ts +15 -0
  18. package/dist/application/invitation-token.js +37 -0
  19. package/dist/application/invitations.d.ts +22 -0
  20. package/dist/application/invitations.js +269 -0
  21. package/dist/application/managed-roles.d.ts +9 -0
  22. package/dist/application/managed-roles.js +97 -0
  23. package/dist/application/menu.d.ts +20 -0
  24. package/dist/application/menu.js +48 -0
  25. package/dist/application/roles.d.ts +25 -0
  26. package/dist/application/roles.js +187 -0
  27. package/dist/application/services.d.ts +84 -0
  28. package/dist/application/services.js +101 -0
  29. package/dist/application/startup-checks.d.ts +14 -0
  30. package/dist/application/startup-checks.js +38 -0
  31. package/dist/application/tenant-input.d.ts +34 -0
  32. package/dist/application/tenant-input.js +79 -0
  33. package/dist/application/tenant-lifecycle.d.ts +32 -0
  34. package/dist/application/tenant-lifecycle.js +82 -0
  35. package/dist/application/tenant-status.d.ts +17 -0
  36. package/dist/application/tenant-status.js +49 -0
  37. package/dist/application/tenants.d.ts +63 -0
  38. package/dist/application/tenants.js +261 -0
  39. package/dist/application/users.d.ts +24 -0
  40. package/dist/application/users.js +148 -0
  41. package/dist/config/menus.d.ts +41 -0
  42. package/dist/config/menus.js +148 -0
  43. package/dist/config/options.d.ts +73 -0
  44. package/dist/config/options.js +134 -0
  45. package/dist/domain/audit.d.ts +31 -0
  46. package/dist/domain/audit.js +18 -0
  47. package/dist/domain/axeda-permissions.d.ts +15 -0
  48. package/dist/domain/axeda-permissions.js +23 -0
  49. package/dist/domain/invitation.d.ts +22 -0
  50. package/dist/domain/invitation.js +19 -0
  51. package/dist/domain/permission-key.d.ts +23 -0
  52. package/dist/domain/permission-key.js +56 -0
  53. package/dist/domain/role.d.ts +58 -0
  54. package/dist/domain/role.js +1 -0
  55. package/dist/domain/scope.d.ts +42 -0
  56. package/dist/domain/scope.js +36 -0
  57. package/dist/domain/tenant.d.ts +37 -0
  58. package/dist/domain/tenant.js +6 -0
  59. package/dist/domain/user.d.ts +21 -0
  60. package/dist/domain/user.js +7 -0
  61. package/dist/errors.d.ts +13 -0
  62. package/dist/errors.js +13 -0
  63. package/dist/index.d.ts +24 -0
  64. package/dist/index.js +17 -0
  65. package/dist/policy/effective-permissions.d.ts +56 -0
  66. package/dist/policy/effective-permissions.js +95 -0
  67. package/dist/policy/grant.d.ts +35 -0
  68. package/dist/policy/grant.js +35 -0
  69. package/dist/policy/index.d.ts +5 -0
  70. package/dist/policy/index.js +5 -0
  71. package/dist/policy/revoke.d.ts +22 -0
  72. package/dist/policy/revoke.js +19 -0
  73. package/dist/policy/role-change.d.ts +24 -0
  74. package/dist/policy/role-change.js +21 -0
  75. package/dist/policy/user-admin.d.ts +28 -0
  76. package/dist/policy/user-admin.js +26 -0
  77. package/dist/ports/identity.d.ts +47 -0
  78. package/dist/ports/identity.js +1 -0
  79. package/dist/ports/index.d.ts +4 -0
  80. package/dist/ports/index.js +1 -0
  81. package/dist/ports/paging.d.ts +9 -0
  82. package/dist/ports/paging.js +1 -0
  83. package/dist/ports/persistence.d.ts +102 -0
  84. package/dist/ports/persistence.js +1 -0
  85. package/dist/ports/platform.d.ts +4 -0
  86. package/dist/ports/platform.js +1 -0
  87. package/dist/ports/tenants.d.ts +100 -0
  88. package/dist/ports/tenants.js +1 -0
  89. package/package.json +48 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # @teamblind/axeda-core
2
+
3
+ ## 0.1.0-alpha.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b519956: Add the authorization use cases. `@teamblind/axeda-core` gains role management, assignments with the no-escalation rule (also on revoke and on role edits), an append-only audit log, `bootstrap` for the first administrator, roles declared in code that sync at start, `scopesFor` and `scopeFilter`, and a version-validated permission cache. `requireMfa` is now enforced when deciding. `@teamblind/axeda-better-auth` stores the audit log and exposes `createBetterAuthUserDirectory`; `@teamblind/axeda-testing` adds an in-memory user directory and covers the new ports in the contract suite.
8
+
9
+ The Better Auth plugin now exposes the use cases as `/axeda/*` endpoints (every one requires a session and declares its permission), connects the session to the actor, cleans up on user deletion, refuses to start with `session.cookieCache`, and ships a typed client at `@teamblind/axeda-better-auth/client`. `npm run demo` runs the whole story against a real server.
10
+
11
+ - c55b0f4: Persist Axeda on top of the Better Auth database adapter. `@teamblind/axeda-better-auth` adds the plugin schema (roles, assignments, policy state and the user's `authzVersion`) and `createBetterAuthPersistence`, which implements the persistence ports for any database Better Auth supports, with atomic counters, optimistic role updates and real transactions. The persistence contract suite now also covers concurrent duplicate creation, and `@teamblind/axeda-core` adds the `AXEDA_USER_NOT_FOUND` and `AXEDA_DATA_CORRUPT` error codes.
12
+ - c6a80da: Add companies, businesses, invitations and public identity. Companies and businesses are real entities with versions, soft deletion with a grace period (and immediate deletion for privacy requests) and a status that silences their people at once; business scopes are now resolved from the database, never from the request. Invitations are single-use, only the owner of the verified email can accept them, and the inviter's current power is re-checked on acceptance. The plugin exposes `/axeda/company/*`, `/axeda/business/*`, `/axeda/invitation/*` and an opt-in `/axeda/public/identity`; the HTTP status of every error code is now decided exhaustively.
13
+ - a836007: Add the authorization core: permission keys with wildcards, scope inheritance (global → company → business), effective permissions, the no-escalation grant rule, persistence ports, option validation and `createAxeda` with a startup transaction check. `@teamblind/axeda-testing` adds an in-memory persistence with real transactions and a persistence contract suite.
14
+ - 7ebf1fd: Add Express middleware, a secure Better Auth preset and the first documentation. `@teamblind/axeda-express` provides `requireAuth()`, `requirePermission()` and `resolveScope()`: it denies by default, resolves the company of a business from the database, answers the same whether a scope exists or not, requires a trusted origin for cookie-bearing writes and never fails open. `@teamblind/axeda-better-auth` adds `secureAuthOptions()` (refuses weak secrets, wildcard or plain-http origins), `sessionPrincipal()` and `principalFromUser()`, and the plugin now refuses to start with Better Auth's CSRF check, origin check or IP tracking disabled. `@teamblind/axeda-core` adds `resolveTarget()` so applications never trust a company id sent by the client. Documentation in English and Spanish, and an example API in `apps/example`.
15
+ - b402e20: Add user administration and menus. Platform administrators can list users, create accounts without any credential, ban and unban (with an optional end date) and sign people out everywhere; a user with more administrative power than the actor cannot be touched, a ban applies to every path including API keys, and a banned account cannot open sessions. Menus are declared in code, validated at startup (every entry needs its permission, no cycles, safe paths) and `GET /axeda/menu` returns only what the person may use in the requested scope, in their language.
16
+
17
+ ### Patch Changes
18
+
19
+ - fed4ed1: Make the packages publishable: compiled ES modules with type declarations under `dist/`, an `exports` map, `files` limited to what is needed, a README, the licence and the notice in each tarball, and the dependencies each package really uses (`@teamblind/axeda-core` for the others, `zod`, and `vitest` and `@types/express` as peers where needed). The CI now builds the packages, checks what would be published and installs the packed files in an empty project to run and type-check them, and it runs the suite against Better Auth 1.7.10 and 1.7.14.
20
+ - d9c4b80: `@teamblind/axeda-express` gains an optional `onDenied` hook that reports every refused request, with the exact reason the client is not told, so an application can log it; it never changes the response and a failing hook is ignored. All packages now declare a `default` export condition next to `types`, so they can be loaded from CommonJS with `require()` on Node 22.12 or later (and with `import()` everywhere); before, `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED`.
21
+ - 680ab7d: Fix three findings of the security review. A banned principal (for example one arriving through an API key) could still read roles, companies, businesses and other people's assignments; every use case now builds the actor's permission data in one place, which includes the ban. Listing the assignments of a scope answered differently for a company or business that exists and one that does not, which let any signed-in person probe for identifiers; both now answer the same unless the caller holds the permission globally. Every `/axeda/*` response, errors included, now carries `Cache-Control: no-store`.
22
+ - e7e5e56: Fix four problems found while reviewing the first alpha. With sessions kept in `secondaryStorage` (for example Redis), Better Auth keeps a stale copy of the user next to each session, so a revoked assignment, a ban or a 2FA change never reached it; the plugin endpoints and `sessionPrincipal` now re-read the user from the database when `secondaryStorage` is set, and a user who no longer exists is nobody (`principalFromSession` is now async). Dropping a role's `requireMfa` now requires covering all of its permissions, as reactivating it already did. `start()` retries after a transient failure such as an unreachable database instead of staying broken until the process restarts; configuration failures are still remembered. The startup transaction probe no longer reports a false "no transactions" when another instance syncs its roles at the same moment.
23
+ - 4b6cf64: Fix one management problem. Who manages the roles now can remove permissions, deactivate or delete an user only if their own permissions cover what is lost, just like remove an assignment. ´delete´ and ´setStatus´ demand cover all the rol permissions. Before, deactivate didn´t demand anything, just reactivate did. ´Update´ now demand cover the permissions what is lost. The rule is in a new function, ´permissionsToCover´ , because ESLint indicated that ´update´ surpassed complexity limit.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] TeamBlind
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Axeda
2
+ Copyright 2026 TeamBlind
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ See the LICENSE file for the full license text.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @teamblind/axeda-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The authorization policy and use cases of Axeda: effective permissions with downward inheritance, anti-escalation rules, companies, businesses, invitations, users, menus and audit. It depends on neither Better Auth nor any HTTP framework; it talks to storage through ports.
4
+
5
+ > **Status:** alpha (`0.1.0-alpha.0`); the API can still change before 1.0. Install with `npm install @teamblind/axeda-core@alpha`. Documentation: [English](https://github.com/teamblindmx/axeda/tree/main/docs/en) · [Español](https://github.com/teamblindmx/axeda/tree/main/docs/es).
6
+
7
+ ```ts
8
+ import { createAxeda } from '@teamblind/axeda-core';
9
+ ```
10
+
11
+ Most applications use it through [`@teamblind/axeda-better-auth`](https://github.com/teamblindmx/axeda/tree/main/packages/better-auth) and only import types or `createAxeda` directly for tests.
12
+
13
+ Part of [Axeda](https://github.com/teamblindmx/axeda), hierarchical authorization (global → company → business) on top of [Better Auth](https://www.better-auth.com). Licensed under [Apache-2.0](LICENSE).
@@ -0,0 +1,18 @@
1
+ import type { Actor, RoleAssignment } from '../domain/role.js';
2
+ import { type AssignmentScope } from '../domain/scope.js';
3
+ import type { Page, PageRequest } from '../ports/persistence.js';
4
+ import { type Services } from './services.js';
5
+ export interface AssignInput {
6
+ readonly userId: string;
7
+ readonly roleId: string;
8
+ readonly scope: AssignmentScope;
9
+ readonly expiresAt?: Date | null | undefined;
10
+ }
11
+ export interface AssignmentService {
12
+ /** Asignaciones de un usuario que `actor` puede ver (las propias, o las de alcances que administra). */
13
+ listForUser(actor: Actor, userId: string): Promise<readonly RoleAssignment[]>;
14
+ listForScope(actor: Actor, scope: AssignmentScope, page: PageRequest): Promise<Page<RoleAssignment>>;
15
+ assign(actor: Actor, input: AssignInput): Promise<RoleAssignment>;
16
+ revoke(actor: Actor, assignmentId: string): Promise<void>;
17
+ }
18
+ export declare function createAssignmentService(services: Services): AssignmentService;
@@ -0,0 +1,190 @@
1
+ import { z } from 'zod';
2
+ import { AXEDA_PERMISSIONS } from '../domain/axeda-permissions.js';
3
+ import { GLOBAL_TARGET, scopeContains, } from '../domain/scope.js';
4
+ import { AxedaError } from '../errors.js';
5
+ import { scopesGranting } from '../policy/effective-permissions.js';
6
+ import { authorizeGrant } from '../policy/grant.js';
7
+ import { authorizeRevoke } from '../policy/revoke.js';
8
+ import { auditDenials, markDenied, writeAudit } from './audit.js';
9
+ import { loadSnapshot } from './authz-reader.js';
10
+ import { actorPermissions, actorPolicyData, invalidInput, lockUsers, resolveForActor as resolveForActorShared, resolveTarget, } from './services.js';
11
+ const id = z.string().min(1).max(255);
12
+ const assignSchema = z.strictObject({
13
+ userId: id,
14
+ roleId: id,
15
+ scope: z.union([
16
+ z.strictObject({ type: z.literal('global') }),
17
+ z.strictObject({ type: z.enum(['company', 'business']), id }),
18
+ ]),
19
+ expiresAt: z.date().nullish(),
20
+ });
21
+ export function createAssignmentService(services) {
22
+ const { persistence, options } = services;
23
+ const forbid = (reason, permissions = []) => markDenied(new AxedaError('AXEDA_FORBIDDEN', 'You are not allowed to manage this assignment.', {
24
+ details: { reason, permissions },
25
+ }));
26
+ const draft = (actor, action, targetId, scope) => ({
27
+ actorId: actor.userId,
28
+ action,
29
+ targetType: 'assignment',
30
+ targetId,
31
+ scope,
32
+ meta: actor,
33
+ });
34
+ async function requireRole(stores, roleId) {
35
+ const role = await stores.roles.get(roleId);
36
+ if (role === null)
37
+ throw new AxedaError('AXEDA_ROLE_NOT_FOUND', `Role "${roleId}" does not exist.`);
38
+ return role;
39
+ }
40
+ async function requireUser(userId) {
41
+ const user = await services.users.find(userId);
42
+ if (user === null)
43
+ throw new AxedaError('AXEDA_USER_NOT_FOUND', `User "${userId}" does not exist.`);
44
+ return user;
45
+ }
46
+ const resolveForActor = (stores, actor, scope, onDenied = () => forbid('missing_assignment_permission'), requireUsable = true) => resolveForActorShared(services, stores, actor, scope, {
47
+ permission: AXEDA_PERMISSIONS.assignmentManage,
48
+ onDenied,
49
+ requireUsable,
50
+ });
51
+ async function assertCanManage(stores, actor, target) {
52
+ const held = await actorPermissions(stores, services, actor, target);
53
+ if (!held.allows(AXEDA_PERMISSIONS.assignmentManage)) {
54
+ throw forbid('missing_assignment_permission');
55
+ }
56
+ }
57
+ /**
58
+ * ¿Puede `actor` administrar las asignaciones de `scope`? Un alcance que no existe no se
59
+ * distingue de uno ajeno: nadie tiene un permiso propio de una compañía o un negocio que no
60
+ * existen, así que solo quien lo tiene en GLOBAL aprende que falta (los demás ven lo mismo
61
+ * que ante un alcance que existe y no es suyo).
62
+ */
63
+ async function manageAccess(actor, scope) {
64
+ const target = await resolveTarget(services, scope, { requireUsable: false }).catch(() => null);
65
+ const where = target ?? GLOBAL_TARGET;
66
+ const held = await actorPermissions(persistence, services, actor, where);
67
+ if (!held.allows(AXEDA_PERMISSIONS.assignmentManage))
68
+ return 'forbidden';
69
+ return target === null ? 'missing' : 'allowed';
70
+ }
71
+ async function assertCanAssign(stores, actor, role, scope, target) {
72
+ const granter = await actorPermissions(stores, services, actor, target);
73
+ const decision = authorizeGrant({ granter, role, scopeType: scope.type });
74
+ if (!decision.allowed)
75
+ throw forbid(decision.reason, decision.permissions);
76
+ }
77
+ return {
78
+ async listForUser(actor, userId) {
79
+ await services.ready();
80
+ const all = await persistence.assignments.listForUser(userId);
81
+ if (userId === actor.userId)
82
+ return all;
83
+ const snapshot = await loadSnapshot(persistence, actor.userId);
84
+ const managed = scopesGranting(actorPolicyData(services, actor, snapshot), AXEDA_PERMISSIONS.assignmentManage);
85
+ // Una asignación de negocio se ve a través de un alcance de compañía si es de esa compañía.
86
+ const businessIds = all.flatMap((a) => (a.scope.type === 'business' ? [a.scope.id] : []));
87
+ const businesses = businessIds.length === 0 ? [] : await persistence.businesses.getMany(businessIds);
88
+ const companyOf = new Map(businesses.map((business) => [business.id, business.companyId]));
89
+ return all.filter((assignment) => managed.some((container) => scopeContains(container, assignment.scope, assignment.scope.type === 'business' ? companyOf.get(assignment.scope.id) : undefined)));
90
+ },
91
+ async listForScope(actor, scope, page) {
92
+ await services.ready();
93
+ const access = await manageAccess(actor, scope);
94
+ if (access === 'forbidden') {
95
+ throw new AxedaError('AXEDA_FORBIDDEN', 'You are not allowed to list this scope.');
96
+ }
97
+ if (access === 'missing') {
98
+ throw invalidInput(`The ${scope.type} does not exist.`);
99
+ }
100
+ return persistence.assignments.listForScope(scope, page);
101
+ },
102
+ async assign(actor, input) {
103
+ await services.ready();
104
+ const parsed = assignSchema.safeParse(input);
105
+ if (!parsed.success) {
106
+ throw invalidInput(parsed.error.issues.map((issue) => issue.message).join('; '));
107
+ }
108
+ const { userId, roleId, scope } = parsed.data;
109
+ const expiresAt = parsed.data.expiresAt ?? null;
110
+ if (expiresAt !== null && expiresAt <= services.clock.now()) {
111
+ throw invalidInput('expiresAt must be in the future.');
112
+ }
113
+ const base = draft(actor, 'assignment.create', null, scope);
114
+ return auditDenials(persistence, base, async () => {
115
+ // ANTES de la transacción: comprobar el permiso y consultar al usuario y al alcance. Dentro
116
+ // de una transacción no se puede usar nada que no sean sus almacenes: en una base de una
117
+ // sola conexión (SQLite) la transacción la tiene tomada y la consulta esperaría por siempre.
118
+ // Va primero el permiso, antes de revelar si el usuario, la función o el negocio existen.
119
+ const target = await resolveForActor(persistence, actor, scope);
120
+ await assertCanManage(persistence, actor, target);
121
+ const user = await requireUser(userId);
122
+ return persistence.transaction(async (stores) => {
123
+ // Bloqueo + invalidación de caché de quien concede y de quien recibe (ver `lockUsers`).
124
+ await lockUsers(stores, [actor.userId, userId]);
125
+ const role = await requireRole(stores, roleId);
126
+ if (role.requireMfa && !user.twoFactorEnabled) {
127
+ throw new AxedaError('AXEDA_MFA_REQUIRED', `Role "${role.key}" requires two-factor authentication, which the user has not enabled.`);
128
+ }
129
+ await assertCanAssign(stores, actor, role, scope, target);
130
+ if ((await stores.assignments.countForUser(userId)) >= options.limits.maxAssignmentsPerUser) {
131
+ throw new AxedaError('AXEDA_LIMIT_EXCEEDED', `A user cannot have more than ${options.limits.maxAssignmentsPerUser} assignments.`);
132
+ }
133
+ const created = await stores.assignments.create({
134
+ userId,
135
+ roleId,
136
+ scope,
137
+ grantedBy: actor.userId,
138
+ expiresAt,
139
+ });
140
+ await writeAudit(stores, {
141
+ ...draft(actor, 'assignment.create', created.id, scope),
142
+ metadata: {
143
+ userId,
144
+ roleId,
145
+ roleKey: role.key,
146
+ expiresAt: expiresAt?.toISOString() ?? null,
147
+ },
148
+ }, 'success');
149
+ return created;
150
+ });
151
+ });
152
+ },
153
+ async revoke(actor, assignmentId) {
154
+ await services.ready();
155
+ const base = draft(actor, 'assignment.revoke', assignmentId, null);
156
+ const notFound = () => new AxedaError('AXEDA_ASSIGNMENT_NOT_FOUND', `Assignment "${assignmentId}" does not exist.`);
157
+ // Sin permiso sobre el alcance, la asignación "no existe" para quien pregunta (404).
158
+ const hidden = () => markDenied(new AxedaError('AXEDA_ASSIGNMENT_NOT_FOUND', notFound().message, {
159
+ details: { reason: 'missing_assignment_permission' },
160
+ }));
161
+ await auditDenials(persistence, base, async () => {
162
+ // Antes de la transacción (ver `assign`): leer la asignación y resolver su alcance.
163
+ const first = await persistence.assignments.get(assignmentId);
164
+ if (first === null)
165
+ throw notFound();
166
+ const target = await resolveForActor(persistence, actor, first.scope, hidden, false);
167
+ await persistence.transaction(async (stores) => {
168
+ await lockUsers(stores, [actor.userId, first.userId]);
169
+ // Se vuelve a leer: mientras se esperaba el bloqueo pudo revocarse.
170
+ const assignment = await stores.assignments.get(assignmentId);
171
+ if (assignment === null)
172
+ throw notFound();
173
+ const role = await requireRole(stores, assignment.roleId);
174
+ const granter = await actorPermissions(stores, services, actor, target);
175
+ const decision = authorizeRevoke({ granter, role });
176
+ if (!decision.allowed) {
177
+ throw decision.reason === 'missing_assignment_permission'
178
+ ? hidden()
179
+ : forbid(decision.reason, decision.permissions);
180
+ }
181
+ await stores.assignments.revoke(assignmentId);
182
+ await writeAudit(stores, {
183
+ ...draft(actor, 'assignment.revoke', assignmentId, assignment.scope),
184
+ metadata: { userId: assignment.userId, roleId: role.id, roleKey: role.key },
185
+ }, 'success');
186
+ });
187
+ });
188
+ },
189
+ };
190
+ }
@@ -0,0 +1,23 @@
1
+ import { type AuditAction, type AuditTargetType } from '../domain/audit.js';
2
+ import type { RequestMeta } from '../domain/role.js';
3
+ import type { AssignmentScope } from '../domain/scope.js';
4
+ import type { AxedaPersistence, AxedaStores } from '../ports/persistence.js';
5
+ export interface AuditDraft {
6
+ readonly actorId: string | null;
7
+ readonly action: AuditAction;
8
+ readonly targetType: AuditTargetType;
9
+ readonly targetId: string | null;
10
+ readonly scope?: AssignmentScope | null;
11
+ readonly meta?: RequestMeta | undefined;
12
+ readonly metadata?: Readonly<Record<string, unknown>>;
13
+ }
14
+ /** Escribe un evento. Dentro de una transacción, queda atado a ella: o ambos, o ninguno. */
15
+ export declare function writeAudit(stores: Pick<AxedaStores, 'audit'>, draft: AuditDraft, outcome: 'success' | 'denied'): Promise<void>;
16
+ export declare function markDenied<T extends Error>(error: T): T;
17
+ /**
18
+ * Ejecuta `operation` y, si lanza una denegación marcada, la audita **aparte**: la transacción
19
+ * que hubiera escrito el registro ya se deshizo, y el intento no puede perderse.
20
+ */
21
+ export declare function auditDenials<T>(persistence: AxedaPersistence, draft: AuditDraft, operation: () => Promise<T>): Promise<T>;
22
+ /** `auditDenials` sobre una transacción: si se deniega, no queda nada del intento. */
23
+ export declare function runAudited<T>(persistence: AxedaPersistence, draft: AuditDraft, work: (stores: AxedaStores) => Promise<T>): Promise<T>;
@@ -0,0 +1,52 @@
1
+ import { MAX_AUDIT_METADATA_BYTES, } from '../domain/audit.js';
2
+ import { isAxedaError } from '../errors.js';
3
+ const MAX_IP_LENGTH = 64;
4
+ const MAX_USER_AGENT_LENGTH = 255;
5
+ /** Acota el tamaño de `metadata` (S12): si se pasa, se guarda una marca en lugar del contenido. */
6
+ function boundedMetadata(metadata) {
7
+ const text = JSON.stringify(metadata);
8
+ if (text.length <= MAX_AUDIT_METADATA_BYTES)
9
+ return { ...metadata };
10
+ return { truncated: true, originalBytes: text.length };
11
+ }
12
+ const clip = (value, max) => value === undefined || value.length === 0 ? null : value.slice(0, max);
13
+ /** Escribe un evento. Dentro de una transacción, queda atado a ella: o ambos, o ninguno. */
14
+ export async function writeAudit(stores, draft, outcome) {
15
+ await stores.audit.append({
16
+ actorId: draft.actorId,
17
+ action: draft.action,
18
+ targetType: draft.targetType,
19
+ targetId: draft.targetId,
20
+ scope: draft.scope ?? null,
21
+ outcome,
22
+ ip: clip(draft.meta?.ip, MAX_IP_LENGTH),
23
+ userAgent: clip(draft.meta?.userAgent, MAX_USER_AGENT_LENGTH),
24
+ metadata: boundedMetadata(draft.metadata ?? {}),
25
+ });
26
+ }
27
+ /** Errores de denegación que deben quedar en la auditoría aunque la transacción se deshaga. */
28
+ const deniedErrors = new WeakSet();
29
+ export function markDenied(error) {
30
+ deniedErrors.add(error);
31
+ return error;
32
+ }
33
+ /**
34
+ * Ejecuta `operation` y, si lanza una denegación marcada, la audita **aparte**: la transacción
35
+ * que hubiera escrito el registro ya se deshizo, y el intento no puede perderse.
36
+ */
37
+ export async function auditDenials(persistence, draft, operation) {
38
+ try {
39
+ return await operation();
40
+ }
41
+ catch (error) {
42
+ if (error instanceof Error && deniedErrors.has(error)) {
43
+ const reason = isAxedaError(error) ? error.details['reason'] : undefined;
44
+ await writeAudit(persistence, { ...draft, metadata: { ...draft.metadata, ...(reason === undefined ? {} : { reason }) } }, 'denied');
45
+ }
46
+ throw error;
47
+ }
48
+ }
49
+ /** `auditDenials` sobre una transacción: si se deniega, no queda nada del intento. */
50
+ export function runAudited(persistence, draft, work) {
51
+ return auditDenials(persistence, draft, () => persistence.transaction(work));
52
+ }
@@ -0,0 +1,22 @@
1
+ import type { Role, RoleAssignment } from '../domain/role.js';
2
+ /** Lo que se necesita para decidir los permisos de un usuario en cualquier alcance. */
3
+ export interface AuthzSnapshot {
4
+ readonly assignments: readonly RoleAssignment[];
5
+ readonly roles: ReadonlyMap<string, Role>;
6
+ /** Compañías y negocios de sus asignaciones que no pueden conceder poder (`scopeKey`). */
7
+ readonly unusable: ReadonlySet<string>;
8
+ }
9
+ /**
10
+ * Caché en memoria de permisos, **validada por versión**.
11
+ *
12
+ * Una entrada solo se usa si sus dos contadores coinciden con los actuales; si no, es como si
13
+ * no existiera. Por eso no necesita caducar ni invalidarse de forma activa: la seguridad no
14
+ * depende de ella, solo el rendimiento. Es de tamaño acotado (LRU) para no crecer sin límite.
15
+ */
16
+ export declare class AuthzCache {
17
+ #private;
18
+ constructor(maxEntries: number);
19
+ get(userId: string, authzVersion: number, policyVersion: number): AuthzSnapshot | undefined;
20
+ set(userId: string, authzVersion: number, policyVersion: number, snapshot: AuthzSnapshot): void;
21
+ get size(): number;
22
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Caché en memoria de permisos, **validada por versión**.
3
+ *
4
+ * Una entrada solo se usa si sus dos contadores coinciden con los actuales; si no, es como si
5
+ * no existiera. Por eso no necesita caducar ni invalidarse de forma activa: la seguridad no
6
+ * depende de ella, solo el rendimiento. Es de tamaño acotado (LRU) para no crecer sin límite.
7
+ */
8
+ export class AuthzCache {
9
+ #entries = new Map();
10
+ #maxEntries;
11
+ constructor(maxEntries) {
12
+ this.#maxEntries = maxEntries;
13
+ }
14
+ get(userId, authzVersion, policyVersion) {
15
+ const entry = this.#entries.get(userId);
16
+ if (entry === undefined)
17
+ return undefined;
18
+ if (entry.authzVersion !== authzVersion || entry.policyVersion !== policyVersion) {
19
+ this.#entries.delete(userId);
20
+ return undefined;
21
+ }
22
+ // Se marca como usada recientemente.
23
+ this.#entries.delete(userId);
24
+ this.#entries.set(userId, entry);
25
+ return entry.snapshot;
26
+ }
27
+ set(userId, authzVersion, policyVersion, snapshot) {
28
+ this.#entries.delete(userId);
29
+ this.#entries.set(userId, { authzVersion, policyVersion, snapshot });
30
+ while (this.#entries.size > this.#maxEntries) {
31
+ const oldest = this.#entries.keys().next();
32
+ if (oldest.done === true)
33
+ break;
34
+ this.#entries.delete(oldest.value);
35
+ }
36
+ }
37
+ get size() {
38
+ return this.#entries.size;
39
+ }
40
+ }
@@ -0,0 +1,30 @@
1
+ import type { Principal } from '../domain/role.js';
2
+ import type { TargetScope } from '../domain/scope.js';
3
+ import type { AxedaStores } from '../ports/persistence.js';
4
+ import type { AuthzCache, AuthzSnapshot } from './authz-cache.js';
5
+ export declare function assertPrincipal(principal: Principal): void;
6
+ /**
7
+ * Lee las asignaciones de un usuario, las funciones que usan y qué compañías y negocios de sus
8
+ * asignaciones no pueden conceder poder, directamente de los almacenes.
9
+ */
10
+ export declare function loadSnapshot(stores: AxedaStores, userId: string): Promise<AuthzSnapshot>;
11
+ export interface Read {
12
+ readonly snapshot: AuthzSnapshot;
13
+ /** La versión de política con la que se leyó; etiqueta cualquier dato derivado. */
14
+ readonly policyVersion: number;
15
+ }
16
+ /**
17
+ * Lector de permisos para las **consultas** (`can`, `scopesFor`…): usa la caché validada por
18
+ * versión. Las operaciones de administración NO lo usan: leen siempre con `loadSnapshot`
19
+ * dentro de su transacción, porque decidir una concesión con datos cacheados sería una carrera.
20
+ *
21
+ * El estado de las compañías y negocios también se cachea, con la versión de política como
22
+ * etiqueta: cambiar el estado de una compañía o negocio sube esa versión en la misma transacción.
23
+ */
24
+ export declare class AuthzReader {
25
+ #private;
26
+ constructor(stores: AxedaStores, cache: AuthzCache);
27
+ read(principal: Principal): Promise<Read>;
28
+ /** Qué parte del destino (compañía, negocio) no puede conceder poder, con caché por versión. */
29
+ unusableForTarget(policyVersion: number, target: TargetScope): Promise<ReadonlySet<string>>;
30
+ }