@teamblind/axeda-testing 0.0.0-stage → 0.1.0-alpha.1
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/CHANGELOG.md +37 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +14 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -0
- package/dist/memory-persistence.d.ts +11 -0
- package/dist/memory-persistence.js +231 -0
- package/dist/memory-tenants.d.ts +24 -0
- package/dist/memory-tenants.js +248 -0
- package/dist/memory-users.d.ts +17 -0
- package/dist/memory-users.js +111 -0
- package/dist/persistence-contract.d.ts +13 -0
- package/dist/persistence-contract.js +426 -0
- package/dist/tenant-contract.d.ts +3 -0
- package/dist/tenant-contract.js +388 -0
- package/package.json +51 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# @teamblind/axeda-testing
|
|
2
|
+
|
|
3
|
+
## 0.1.0-alpha.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- No changes of its own. It is versioned together with the other packages so that the four share one version, and it now depends on `@teamblind/axeda-core` `0.1.0-alpha.1`.
|
|
8
|
+
- Updated dependencies [ce83aff]
|
|
9
|
+
- @teamblind/axeda-core@0.1.0-alpha.1
|
|
10
|
+
|
|
11
|
+
## 0.1.0-alpha.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
- 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.
|
|
20
|
+
- 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.
|
|
21
|
+
- 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.
|
|
22
|
+
- 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.
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- 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.
|
|
27
|
+
- 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`.
|
|
28
|
+
- Updated dependencies [b519956]
|
|
29
|
+
- Updated dependencies [c55b0f4]
|
|
30
|
+
- Updated dependencies [c6a80da]
|
|
31
|
+
- Updated dependencies [a836007]
|
|
32
|
+
- Updated dependencies [7ebf1fd]
|
|
33
|
+
- Updated dependencies [fed4ed1]
|
|
34
|
+
- Updated dependencies [d9c4b80]
|
|
35
|
+
- Updated dependencies [680ab7d]
|
|
36
|
+
- Updated dependencies [b402e20]
|
|
37
|
+
- @teamblind/axeda-core@0.1.0-alpha.0
|
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
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @teamblind/axeda-testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
In-memory stores for Axeda and the contract suites that every persistence implementation must pass, for testing your own authorization logic without a database.
|
|
4
|
+
|
|
5
|
+
> **Status:** alpha (`0.1.0-alpha.1`); the API can still change before 1.0. Install with `npm install @teamblind/axeda-testing@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 { createMemoryPersistence, createMemoryUserDirectory } from '@teamblind/axeda-testing';
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Peer dependency: `vitest` `^5` (the contract suites use its `describe` and `it`).
|
|
12
|
+
|
|
13
|
+
Guides: [Quick start](https://github.com/teamblindmx/axeda/blob/main/docs/en/quickstart.md) · [Configuration](https://github.com/teamblindmx/axeda/blob/main/docs/en/configuration.md) · [Reference](https://github.com/teamblindmx/axeda/blob/main/docs/en/reference.md) · [Upgrading](https://github.com/teamblindmx/axeda/blob/main/docs/en/upgrading.md).
|
|
14
|
+
|
|
15
|
+
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).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createMemoryUserDirectory, type MemoryUserDirectory } from './memory-users.js';
|
|
2
|
+
export { createMemoryPersistence, type MemoryPersistenceOptions } from './memory-persistence.js';
|
|
3
|
+
export { CONTRACT_USERS, roleInput, runPersistenceContract, type PersistenceFactory, } from './persistence-contract.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @teamblind/axeda-testing — almacén en memoria y suites de contrato de los puertos.
|
|
2
|
+
export { createMemoryUserDirectory } from './memory-users.js';
|
|
3
|
+
export { createMemoryPersistence } from './memory-persistence.js';
|
|
4
|
+
export { CONTRACT_USERS, roleInput, runPersistenceContract, } from './persistence-contract.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type AxedaPersistence } from '@teamblind/axeda-core';
|
|
2
|
+
export interface MemoryPersistenceOptions {
|
|
3
|
+
readonly now?: () => Date;
|
|
4
|
+
readonly nextId?: () => string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Persistencia en memoria con **transacciones reales**: si el callback lanza, el estado vuelve al
|
|
8
|
+
* de antes. Las operaciones y transacciones se serializan. Es la implementación de referencia y
|
|
9
|
+
* la que usan las pruebas; no es para producción.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createMemoryPersistence(options?: MemoryPersistenceOptions): AxedaPersistence;
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { AxedaError, createAuditIdFactory, scopeKey, } from '@teamblind/axeda-core';
|
|
2
|
+
import { decodeCursor, encodeCursor, createBusinessStore, createCompanyStore, createInvitationStore, } from './memory-tenants.js';
|
|
3
|
+
const snapshot = (state) => ({
|
|
4
|
+
companies: new Map(state.companies),
|
|
5
|
+
businesses: new Map(state.businesses),
|
|
6
|
+
invitations: new Map(state.invitations),
|
|
7
|
+
roles: new Map(state.roles),
|
|
8
|
+
audit: [...state.audit],
|
|
9
|
+
assignments: new Map(state.assignments),
|
|
10
|
+
userVersions: new Map(state.userVersions),
|
|
11
|
+
policyVersion: state.policyVersion,
|
|
12
|
+
});
|
|
13
|
+
function restore(state, saved) {
|
|
14
|
+
state.companies = saved.companies;
|
|
15
|
+
state.businesses = saved.businesses;
|
|
16
|
+
state.invitations = saved.invitations;
|
|
17
|
+
state.roles = saved.roles;
|
|
18
|
+
state.audit = saved.audit;
|
|
19
|
+
state.assignments = saved.assignments;
|
|
20
|
+
state.userVersions = saved.userVersions;
|
|
21
|
+
state.policyVersion = saved.policyVersion;
|
|
22
|
+
}
|
|
23
|
+
function createRoleStore(state, run, now, nextId) {
|
|
24
|
+
return {
|
|
25
|
+
get: (id) => run(async () => state.roles.get(id) ?? null),
|
|
26
|
+
getMany: (ids) => run(async () => ids.flatMap((id) => state.roles.get(id) ?? [])),
|
|
27
|
+
getByKey: (key) => run(async () => [...state.roles.values()].find((role) => role.key === key) ?? null),
|
|
28
|
+
list: (page) => run(async () => {
|
|
29
|
+
const after = page.cursor === undefined ? null : decodeCursor(page.cursor);
|
|
30
|
+
const sorted = [...state.roles.values()].sort((a, b) => a.key.localeCompare(b.key));
|
|
31
|
+
const remaining = after === null ? sorted : sorted.filter((role) => role.key > after);
|
|
32
|
+
const items = remaining.slice(0, page.limit);
|
|
33
|
+
const last = items.at(-1);
|
|
34
|
+
const hasMore = remaining.length > items.length;
|
|
35
|
+
return { items, nextCursor: hasMore && last ? encodeCursor(last.key) : null };
|
|
36
|
+
}),
|
|
37
|
+
create: (input) => run(async () => {
|
|
38
|
+
if ([...state.roles.values()].some((role) => role.key === input.key)) {
|
|
39
|
+
throw new AxedaError('AXEDA_ROLE_KEY_TAKEN', `A role with key "${input.key}" already exists.`);
|
|
40
|
+
}
|
|
41
|
+
const at = now();
|
|
42
|
+
const role = {
|
|
43
|
+
id: nextId(),
|
|
44
|
+
key: input.key,
|
|
45
|
+
name: input.name,
|
|
46
|
+
description: input.description ?? null,
|
|
47
|
+
permissions: [...input.permissions],
|
|
48
|
+
requireMfa: input.requireMfa ?? false,
|
|
49
|
+
status: input.status ?? 'active',
|
|
50
|
+
managed: input.managed ?? false,
|
|
51
|
+
version: 1,
|
|
52
|
+
createdAt: at,
|
|
53
|
+
updatedAt: at,
|
|
54
|
+
};
|
|
55
|
+
state.roles.set(role.id, role);
|
|
56
|
+
return role;
|
|
57
|
+
}),
|
|
58
|
+
update: (id, expectedVersion, changes) => run(async () => {
|
|
59
|
+
const current = state.roles.get(id);
|
|
60
|
+
if (!current)
|
|
61
|
+
throw new AxedaError('AXEDA_ROLE_NOT_FOUND', `Role "${id}" does not exist.`);
|
|
62
|
+
if (current.version !== expectedVersion) {
|
|
63
|
+
throw new AxedaError('AXEDA_VERSION_CONFLICT', `Role "${id}" is at version ${current.version}, not ${expectedVersion}.`);
|
|
64
|
+
}
|
|
65
|
+
const updated = {
|
|
66
|
+
...current,
|
|
67
|
+
name: changes.name ?? current.name,
|
|
68
|
+
description: changes.description === undefined ? current.description : changes.description,
|
|
69
|
+
permissions: changes.permissions ? [...changes.permissions] : current.permissions,
|
|
70
|
+
requireMfa: changes.requireMfa ?? current.requireMfa,
|
|
71
|
+
status: changes.status ?? current.status,
|
|
72
|
+
version: current.version + 1,
|
|
73
|
+
updatedAt: now(),
|
|
74
|
+
};
|
|
75
|
+
state.roles.set(id, updated);
|
|
76
|
+
return updated;
|
|
77
|
+
}),
|
|
78
|
+
delete: (id) => run(async () => {
|
|
79
|
+
if (!state.roles.delete(id))
|
|
80
|
+
return false;
|
|
81
|
+
for (const [assignmentId, assignment] of state.assignments) {
|
|
82
|
+
if (assignment.roleId === id)
|
|
83
|
+
state.assignments.delete(assignmentId);
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function createAssignmentStore(state, run, now, nextId) {
|
|
90
|
+
const forUser = (userId) => [...state.assignments.values()].filter((assignment) => assignment.userId === userId);
|
|
91
|
+
return {
|
|
92
|
+
get: (id) => run(async () => state.assignments.get(id) ?? null),
|
|
93
|
+
listForScope: (scope, page) => run(async () => {
|
|
94
|
+
const after = page.cursor === undefined ? null : decodeCursor(page.cursor);
|
|
95
|
+
const sorted = [...state.assignments.values()]
|
|
96
|
+
.filter((assignment) => scopeKey(assignment.scope) === scopeKey(scope))
|
|
97
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
98
|
+
const remaining = after === null ? sorted : sorted.filter((item) => item.id > after);
|
|
99
|
+
const items = remaining.slice(0, page.limit);
|
|
100
|
+
const last = items.at(-1);
|
|
101
|
+
return {
|
|
102
|
+
items,
|
|
103
|
+
nextCursor: remaining.length > items.length && last ? encodeCursor(last.id) : null,
|
|
104
|
+
};
|
|
105
|
+
}),
|
|
106
|
+
listForUser: (userId) => run(async () => forUser(userId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())),
|
|
107
|
+
countForUser: (userId) => run(async () => forUser(userId).length),
|
|
108
|
+
create: (input) => run(async () => {
|
|
109
|
+
if (!state.roles.has(input.roleId)) {
|
|
110
|
+
throw new AxedaError('AXEDA_ROLE_NOT_FOUND', `Role "${input.roleId}" does not exist.`);
|
|
111
|
+
}
|
|
112
|
+
const duplicate = forUser(input.userId).some((existing) => existing.roleId === input.roleId && scopeKey(existing.scope) === scopeKey(input.scope));
|
|
113
|
+
if (duplicate) {
|
|
114
|
+
throw new AxedaError('AXEDA_ASSIGNMENT_EXISTS', 'The user already has that role in that scope.');
|
|
115
|
+
}
|
|
116
|
+
const assignment = {
|
|
117
|
+
id: nextId(),
|
|
118
|
+
userId: input.userId,
|
|
119
|
+
roleId: input.roleId,
|
|
120
|
+
scope: input.scope,
|
|
121
|
+
grantedBy: input.grantedBy ?? null,
|
|
122
|
+
createdAt: now(),
|
|
123
|
+
expiresAt: input.expiresAt ?? null,
|
|
124
|
+
};
|
|
125
|
+
state.assignments.set(assignment.id, assignment);
|
|
126
|
+
return assignment;
|
|
127
|
+
}),
|
|
128
|
+
revoke: (id) => run(async () => state.assignments.delete(id)),
|
|
129
|
+
deleteForUser: (userId) => run(async () => {
|
|
130
|
+
const mine = forUser(userId);
|
|
131
|
+
for (const assignment of mine)
|
|
132
|
+
state.assignments.delete(assignment.id);
|
|
133
|
+
return mine.length;
|
|
134
|
+
}),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function createAuthzStore(state, run) {
|
|
138
|
+
return {
|
|
139
|
+
getUserVersion: (userId) => run(async () => state.userVersions.get(userId) ?? 0),
|
|
140
|
+
bumpUserVersion: (userId) => run(async () => {
|
|
141
|
+
const next = (state.userVersions.get(userId) ?? 0) + 1;
|
|
142
|
+
state.userVersions.set(userId, next);
|
|
143
|
+
return next;
|
|
144
|
+
}),
|
|
145
|
+
getPolicyVersion: () => run(async () => state.policyVersion),
|
|
146
|
+
bumpPolicyVersion: () => run(async () => ++state.policyVersion),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const matchesFilter = (event, filter) => {
|
|
150
|
+
const same = (wanted, actual) => wanted === undefined || actual === wanted;
|
|
151
|
+
const sameScope = filter.scope === undefined ||
|
|
152
|
+
(event.scope !== null && scopeKey(event.scope) === scopeKey(filter.scope));
|
|
153
|
+
return (same(filter.actorId, event.actorId) &&
|
|
154
|
+
same(filter.action, event.action) &&
|
|
155
|
+
same(filter.targetType, event.targetType) &&
|
|
156
|
+
same(filter.targetId, event.targetId) &&
|
|
157
|
+
sameScope);
|
|
158
|
+
};
|
|
159
|
+
function createAuditStore(state, run, now) {
|
|
160
|
+
const nextAuditId = createAuditIdFactory();
|
|
161
|
+
return {
|
|
162
|
+
append: (input) => run(async () => {
|
|
163
|
+
const at = now();
|
|
164
|
+
const event = { ...input, id: nextAuditId(at), at };
|
|
165
|
+
state.audit.push(event);
|
|
166
|
+
return event;
|
|
167
|
+
}),
|
|
168
|
+
list: (filter, page) => run(async () => {
|
|
169
|
+
const after = page.cursor === undefined ? null : decodeCursor(page.cursor);
|
|
170
|
+
const sorted = state.audit.filter((event) => matchesFilter(event, filter));
|
|
171
|
+
sorted.sort((a, b) => b.id.localeCompare(a.id));
|
|
172
|
+
const remaining = after === null ? sorted : sorted.filter((event) => event.id < after);
|
|
173
|
+
const items = remaining.slice(0, page.limit);
|
|
174
|
+
const last = items.at(-1);
|
|
175
|
+
return {
|
|
176
|
+
items,
|
|
177
|
+
nextCursor: remaining.length > items.length && last ? encodeCursor(last.id) : null,
|
|
178
|
+
};
|
|
179
|
+
}),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Persistencia en memoria con **transacciones reales**: si el callback lanza, el estado vuelve al
|
|
184
|
+
* de antes. Las operaciones y transacciones se serializan. Es la implementación de referencia y
|
|
185
|
+
* la que usan las pruebas; no es para producción.
|
|
186
|
+
*/
|
|
187
|
+
export function createMemoryPersistence(options = {}) {
|
|
188
|
+
const now = options.now ?? (() => new Date());
|
|
189
|
+
const nextId = options.nextId ?? (() => globalThis.crypto.randomUUID());
|
|
190
|
+
const state = {
|
|
191
|
+
companies: new Map(),
|
|
192
|
+
businesses: new Map(),
|
|
193
|
+
invitations: new Map(),
|
|
194
|
+
roles: new Map(),
|
|
195
|
+
audit: [],
|
|
196
|
+
assignments: new Map(),
|
|
197
|
+
userVersions: new Map(),
|
|
198
|
+
policyVersion: 0,
|
|
199
|
+
};
|
|
200
|
+
let tail = Promise.resolve();
|
|
201
|
+
const withLock = (fn) => {
|
|
202
|
+
const result = tail.then(fn, fn);
|
|
203
|
+
tail = result.catch(() => undefined);
|
|
204
|
+
return result;
|
|
205
|
+
};
|
|
206
|
+
const inline = (fn) => fn();
|
|
207
|
+
const storesFor = (run) => ({
|
|
208
|
+
companies: createCompanyStore({ state, run, now, nextId }),
|
|
209
|
+
businesses: createBusinessStore({ state, run, now, nextId }),
|
|
210
|
+
invitations: createInvitationStore({ state, run, now, nextId }),
|
|
211
|
+
roles: createRoleStore(state, run, now, nextId),
|
|
212
|
+
assignments: createAssignmentStore(state, run, now, nextId),
|
|
213
|
+
authz: createAuthzStore(state, run),
|
|
214
|
+
audit: createAuditStore(state, run, now),
|
|
215
|
+
});
|
|
216
|
+
const root = storesFor(withLock);
|
|
217
|
+
const inTransaction = storesFor(inline);
|
|
218
|
+
return {
|
|
219
|
+
...root,
|
|
220
|
+
transaction: (callback) => withLock(async () => {
|
|
221
|
+
const saved = snapshot(state);
|
|
222
|
+
try {
|
|
223
|
+
return await callback(inTransaction);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
restore(state, saved);
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Business, type BusinessStore, type Company, type CompanyStore, type InvitationStore, type Page, type PageRequest, type RoleAssignment, type StoredInvitation } from '@teamblind/axeda-core';
|
|
2
|
+
/** El estado que comparten los almacenes en memoria. */
|
|
3
|
+
export interface TenantState {
|
|
4
|
+
companies: Map<string, Company>;
|
|
5
|
+
businesses: Map<string, Business>;
|
|
6
|
+
invitations: Map<string, StoredInvitation>;
|
|
7
|
+
assignments: Map<string, RoleAssignment>;
|
|
8
|
+
}
|
|
9
|
+
/** Ejecuta `fn` con exclusión: las operaciones y transacciones se serializan. */
|
|
10
|
+
export type Run = <T>(fn: () => Promise<T>) => Promise<T>;
|
|
11
|
+
interface Context {
|
|
12
|
+
readonly state: TenantState;
|
|
13
|
+
readonly run: Run;
|
|
14
|
+
readonly now: () => Date;
|
|
15
|
+
readonly nextId: () => string;
|
|
16
|
+
}
|
|
17
|
+
export declare const encodeCursor: (value: string) => string;
|
|
18
|
+
export declare const decodeCursor: (cursor: string) => string;
|
|
19
|
+
/** Pagina una lista ya ordenada por `key` con un cursor opaco. */
|
|
20
|
+
export declare function paginate<T>(sorted: readonly T[], key: (item: T) => string, page: PageRequest): Page<T>;
|
|
21
|
+
export declare function createCompanyStore(context: Context): CompanyStore;
|
|
22
|
+
export declare function createBusinessStore(context: Context): BusinessStore;
|
|
23
|
+
export declare function createInvitationStore(context: Context): InvitationStore;
|
|
24
|
+
export {};
|