@ordinatio/access 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +365 -2
- package/dist/chunk-BJLK3LNX.js +1768 -0
- package/dist/index.d.ts +716 -0
- package/dist/index.js +438 -0
- package/dist/request-types-CC1oDWv_.d.ts +587 -0
- package/dist/testing.d.ts +455 -0
- package/dist/testing.js +3284 -0
- package/package.json +46 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ordinatio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,366 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ordinatio/access
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Who may see which records, as plain data. An app describes its roles, its teams and each team's rules; this package answers "what may this subject see in this area?" with a small scope object the app turns into a query filter.
|
|
4
|
+
|
|
5
|
+
It holds no database code and knows nothing about what the records are.
|
|
6
|
+
|
|
7
|
+
## The pieces
|
|
8
|
+
|
|
9
|
+
- **Subject**: a member, an API key, or an agent acting for a member or for a team. Always with an `organizationId`.
|
|
10
|
+
- **Role table** (the app supplies it): per role and area, a level (`none`, `read`, `write`) and whether the role sees everything in that area.
|
|
11
|
+
- **Rules**: stored per team and area. A record is visible when it matches any rule. A team with no rules for an area sees everything in it.
|
|
12
|
+
- `teamTag`: records tagged with one of the listed teams.
|
|
13
|
+
- `owner`: records owned by members of the listed teams, or of the team itself plus the teams it was granted.
|
|
14
|
+
- `tag`: records carrying one of the listed tags.
|
|
15
|
+
- `container`: records inside one of the listed containers of a named type.
|
|
16
|
+
- **Scope**: `{ mode: 'unrestricted' }`, `{ mode: 'none' }`, or `{ mode: 'restricted', anyOf: Clause[] }`.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { resolveScope, matchesScope, can } from '@ordinatio/access';
|
|
20
|
+
|
|
21
|
+
if (!can(roles, member.role, 'files', 'write')) deny();
|
|
22
|
+
const scope = await resolveScope({ kind: 'member', organizationId, userId }, 'files', {
|
|
23
|
+
store, roles, isEnabled, logger,
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Turning a scope into a filter
|
|
28
|
+
|
|
29
|
+
Your query builder must agree with `matchesScope`. Two cases are easy to get wrong:
|
|
30
|
+
|
|
31
|
+
1. **`restricted` with an empty `anyOf`, or a clause with an empty id list, matches nothing.** It is never "no filter". Build `WHERE false`, not an empty condition.
|
|
32
|
+
2. **Unowned means an empty owner list.** For `ownerIn` with `includeNull: true`, a record with no owner matches. When building facts for `matchesScope`, pass `ownerIds: []` for such a record, not `[null]`.
|
|
33
|
+
|
|
34
|
+
A scope never replaces your own organization filter. In a shared database every query still filters by `organizationId`, including when the scope is `unrestricted`.
|
|
35
|
+
|
|
36
|
+
`none` and `restricted` both deny; treat a denied record the same as a missing one so a caller cannot tell them apart.
|
|
37
|
+
|
|
38
|
+
For a worked example on plain SQL, see `reference/postgres/scope-sql.ts` in this package's source: `scopeCondition(scope, bind)` returns one condition to AND with your organization filter. Every id goes in as a bound value, and anything it does not understand becomes `FALSE`. `record-store.ts` beside it uses that condition for the impact counts and shows a team-tag store in two statements. Those two stores pass the impact kit and the team-tag kit against a real database.
|
|
39
|
+
|
|
40
|
+
## Failing closed
|
|
41
|
+
|
|
42
|
+
- Unknown member, unknown key, a role with no level on the area, a key or agent tied to a team of another organization: `none`.
|
|
43
|
+
- A member whose team cannot be confirmed in the organization, and no default team: their own records only.
|
|
44
|
+
- A rule of a kind this version does not know matches nothing, and is reported through `logger.warn`. The team stays restricted.
|
|
45
|
+
- Every team id is confirmed through `listGroups` and compared with the organization before use. A grant that points at a team of another organization is ignored.
|
|
46
|
+
- If the store or the switch throws, or answers in the wrong shape, `resolveScope` rejects with an `ACCESS_1xx` error. It never returns a guessed scope. Deny the request.
|
|
47
|
+
- If `logger.warn` itself fails, the result does not change and the event goes to `console.error`. Dropped team ids (`ACCESS_121`) are the only sign of a row pointing across organizations, so watch that channel too.
|
|
48
|
+
- A member whose stored team cannot be confirmed is treated as having no team and gets the default team's rules, which means everything in the area if the default team has no rules.
|
|
49
|
+
- With the switch off for an area, members and keys of the organization see everything in it. That is the meaning of "off". The switch does not open an area to a key whose area list does not hold it: that key reads nothing there.
|
|
50
|
+
|
|
51
|
+
`canAssignTo` only answers whether the scope allows handing work to that user id. It does not check that the user exists or belongs to the organization; do that first.
|
|
52
|
+
|
|
53
|
+
Keys and agents acting for a team have no role, so the role table is not consulted for them: they get the team's rules, and everything in an area the team has no rules for.
|
|
54
|
+
|
|
55
|
+
A key with no team is unrestricted without any further lookup, so which organization a key belongs to rests entirely on your `getKeyTeam`.
|
|
56
|
+
|
|
57
|
+
A key can also carry an area list. Outside that list it reads nothing, whatever its team and whatever the switch says. See "Keys and agents" below.
|
|
58
|
+
|
|
59
|
+
Error contexts carry `causeMessage`, the raw text of the store's error. Log it; do not send it to callers.
|
|
60
|
+
|
|
61
|
+
One thing the package cannot check: the user ids returned by `listMemberIdsInGroups`. Your store must filter them by organization. The proof kit tests that.
|
|
62
|
+
|
|
63
|
+
## Proving your store: `@ordinatio/access/testing`
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { runAccessMatrix, assertAccessMatrix } from '@ordinatio/access/testing';
|
|
67
|
+
|
|
68
|
+
const results = await runAccessMatrix({
|
|
69
|
+
makeStore: async (fixture) => { await load(fixture); return myStore; },
|
|
70
|
+
cleanup: (fixture) => wipe(fixture),
|
|
71
|
+
makeIsEnabled: (fixture) => myIsEnabled, // your real switch
|
|
72
|
+
decide: (facts, scope, check) => myQueryFinds(facts, scope), // your real filter
|
|
73
|
+
});
|
|
74
|
+
assertAccessMatrix(results);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The kit gives you plain fixture data, you load it into your own storage, and it runs 21 scenarios: team visibility, grants, a grant that ends, the bypass role, the switch, the default team, each rule kind, keys, and rows that point across organizations. Pass `decide` and `makeIsEnabled`; without them the kit checks your store but not your query builder or your switch.
|
|
78
|
+
|
|
79
|
+
`createSharedMemoryStore` and `createPerOrganizationStore` are reference stores for one shared database and for a database per organization.
|
|
80
|
+
|
|
81
|
+
## Changing access (the admin side)
|
|
82
|
+
|
|
83
|
+
The operations below change teams, members, grants and rules. Each one runs in a single transaction, checks that the acting member's role has `manageAccess`, and records what changed.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { createGroup, setRules, revertRules, setMemberRole } from '@ordinatio/access';
|
|
87
|
+
|
|
88
|
+
const deps = { admin, roles, logger, now: () => new Date(), canChangeRole: (actor, target, newRole) => true };
|
|
89
|
+
const actor = { organizationId, userId };
|
|
90
|
+
|
|
91
|
+
await createGroup(actor, { name: 'North' }, deps);
|
|
92
|
+
const { version } = await setRules(actor, { groupId, area: 'files', rules: [{ kind: 'tag', tagIds: ['t1'] }], expectedVersion: 0 }, deps);
|
|
93
|
+
// Back one step. The earlier list here is empty, which means wide open, so it has to be said.
|
|
94
|
+
await revertRules(actor, { groupId, area: 'files', expectedVersion: version, allowWideOpen: true }, deps);
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
| Operation | Refused when |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `createGroup`, `renameGroup` | the name is empty, over 100 characters, or taken |
|
|
100
|
+
| `deleteGroup` | it is the default team, or it still has members, keys, or another team's rule naming it. It removes the team's grants, rules and limits; team tags stay on the work, and an open request that named the team closes as outdated when someone approves it |
|
|
101
|
+
| `moveMember` | the member or the team is not in this organization, or no team is named |
|
|
102
|
+
| `placeEveryone` | the name is empty or over 100 characters, or the organization has no default team and the name is taken |
|
|
103
|
+
| `setMemberRole` | the acting role does not cover both the old and the new role, the app says no, or it would leave nobody who manages access |
|
|
104
|
+
| `grantVisibility`, `revokeVisibility` | a team is not in this organization, the grant already exists and still counts, or the end is not a time ahead |
|
|
105
|
+
| `removeEndedGrants` | never, for a member who manages access |
|
|
106
|
+
| `setRules` | the rules are malformed, name a team of another organization, or the stored version is not `expectedVersion` |
|
|
107
|
+
| `revertRules` | there is no earlier version, or the earlier version no longer passes the same checks as a fresh save |
|
|
108
|
+
|
|
109
|
+
Things to know:
|
|
110
|
+
|
|
111
|
+
- **Who may act.** Only a member whose role has `manageAccess`. That check comes before anything is looked up, so a refusal says nothing about what exists. A member who manages access may change any team's rules, their own team included: that is what the permission means. Give it only to roles you trust with it.
|
|
112
|
+
- **Everyone is on a team.** In the step that turns teams on, call `placeEveryone(actor, { defaultTeamName }, deps)`. It puts every member who has no team on the default team, and makes that team first if there is none (a valid name is always required, and used only then). A team made this way has no rules yet, so its members see the whole of each area until you save rules for it. After that `moveMember` moves people between teams; it has no move to "no team". Give a new member a team when they join. `everyoneHasTeam(organizationId, { admin })` is a health check. A member who still has no team is read as a member of the default team.
|
|
113
|
+
- **Roles.** Nobody gives or takes away more than their own role holds, as far as the role table shows. `canChangeRole` is required because roles often differ in ways the table cannot show (who may approve, who owns the account). Pass `() => true` only if yours do not.
|
|
114
|
+
- **No lock-out.** The last member who manages access cannot be demoted. Your own code that removes or deactivates a member, or cancels an invitation, must call `assertManagerRemains(tx, ...)` inside the same `admin.transaction`. `hasManager(organizationId, deps)` is a health check worth running on a schedule.
|
|
115
|
+
- **Versions.** Every saved rule list is a new version. Saving the same rules again adds nothing. `revertRules` writes a new version holding the rules of the one before; doing it twice returns to where you started.
|
|
116
|
+
- **Grants that end.** Pass `expiresAt` (a full ISO time with its zone, such as `2030-01-31T17:00:00Z`, at most 366 days ahead) to `grantVisibility` and the grant stops counting at that instant. Nothing has to run for that: the resolver skips an ended grant every time it reads one, using `deps.now` (the system clock if you leave it out). A grant whose stored end cannot be read counts as ended and is logged as `ACCESS_123`. Stores return the end as ISO text with its zone, not a `Date` object; `grantVisibility` reads a timed grant back and fails with `ACCESS_251` if the end did not survive. `listGrants` must return the field on every row, `null` for no end and at most three fractional digits: a row without the field is skipped and logged, so a store that forgets the column shows less, never more. On the admin side a grant with an unreadable end is not treated as ended: it cannot be given again and is not cleared, so take it back with `revokeVisibility`. An ended grant can be given again; one that still counts must be taken back first. `removeEndedGrants` deletes ended rows, which is tidying only.
|
|
117
|
+
- **Wide open is never an accident.** An empty rule list lets the team see the whole area. `setRules` needs `wideOpen: true` for it, and `revertRules` needs `allowWideOpen: true` when the earlier version is empty.
|
|
118
|
+
- **History.** `recordChange` is called inside the transaction with who, what, before, after and when. Store it in the same database as the access tables, so it can neither be lost nor outlive a rolled-back change. Feed an activity screen from it after commit.
|
|
119
|
+
- **Errors.** `ACCESS_200` to `ACCESS_242` are refusals; `ACCESS_250` and `ACCESS_251` mean the store (or something else you passed in, such as `now`) failed. `context.causeMessage` may quote stored data: log it, never return it to a browser.
|
|
120
|
+
|
|
121
|
+
### What the admin store must guarantee
|
|
122
|
+
|
|
123
|
+
`AccessAdminStore.transaction(organizationId, fn)`:
|
|
124
|
+
|
|
125
|
+
1. Everything `fn` writes commits together or not at all, history included.
|
|
126
|
+
2. Two transactions for one organization never overlap, across every running copy of your app. In Postgres, take `pg_advisory_xact_lock` on the organization at the start. A lock held in memory is not enough.
|
|
127
|
+
3. A value thrown inside `fn` reaches the caller unchanged.
|
|
128
|
+
4. Role and team belong to the member of that organization. If your roles live on a user row shared by several organizations, one organization's manager can change another's member: move them to the membership first.
|
|
129
|
+
5. Anyone who cannot sign in is absent: `getMember` returns null for them and no count includes them. (The read side's `listMemberIdsInGroups` still lists them, so what they own stays with their team.)
|
|
130
|
+
6. `insertDefaultGroup` fails if the organization already has a default team, and `placeMembersWithoutGroup` moves only members who can sign in and have no team.
|
|
131
|
+
7. A team id is never given out again. A deleted team's id stays on the work it was tagged with and in open requests that named it, so a new team with that id would inherit both.
|
|
132
|
+
8. `deleteLimitsOfGroup` removes every limit stored for that team in the organization and returns what it removed; a store that keeps no limits returns an empty list.
|
|
133
|
+
9. `putRuleSet` fails if the version exists, and `deleteGroup` fails if the team still has members who can sign in; members who cannot are left with no team. Other code paths that write these tables without the lock are then caught instead of silently winning.
|
|
134
|
+
10. For a team and area never written through this port, `getRuleSet` returns version 0 with the rules your read side applies today.
|
|
135
|
+
|
|
136
|
+
### A reference store on PostgreSQL
|
|
137
|
+
|
|
138
|
+
`reference/postgres` in this package's source holds a complete store on plain SQL: the tables (`schema.sql`), the read side, the admin side with one lock per organization, and a harness whose test runs both proof kits against a real database, in both shapes (one shared database, or one schema per organization). It is not shipped in the npm package; copy from it. To run it: `ACCESS_TEST_DATABASE_URL=postgresql://... pnpm test`.
|
|
139
|
+
|
|
140
|
+
### Proving your admin store
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { runAccessAdminMatrix, assertAccessAdminMatrix } from '@ordinatio/access/testing';
|
|
144
|
+
|
|
145
|
+
const results = await runAccessAdminMatrix({ makeHarness: (fixture) => loadIntoMyDatabase(fixture), cleanup });
|
|
146
|
+
assertAccessAdminMatrix(results);
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`makeHarness` returns your read store, two separately built admin stores, `listChanges(organizationId)` and `snapshot(organizationId)`. The kit runs 57 scenarios:
|
|
150
|
+
|
|
151
|
+
- every operation and every refusal (`ACCESS_200` to `ACCESS_242`)
|
|
152
|
+
- every operation tried by a non-manager, and every operation with a target aimed at another organization
|
|
153
|
+
- one person who belongs to two organizations, and a member who cannot sign in
|
|
154
|
+
- placing everyone without a team, with and without a default team to start from
|
|
155
|
+
- a failed change leaving nothing behind, for every kind of write
|
|
156
|
+
- two changes to one organization waiting their turn, and a change made through one running copy being seen by the other at once
|
|
157
|
+
- each area of a team keeping its own rules and versions
|
|
158
|
+
- history entries stored whole: actor, target, before, after and time
|
|
159
|
+
- writes made for one organization never landing in another
|
|
160
|
+
- a grant with an end: stored and read back as the same instant, counting until then and not after, given again once ended, and cleared without touching the rest
|
|
161
|
+
|
|
162
|
+
Changes are checked through the read side, so a store whose writes do not reach its reads fails. Where a scenario expects nothing to change, a failure says which rows differ. A scenario that does not finish within `timeoutMs` (30 seconds unless you say otherwise) fails instead of hanging; give the test that runs the kit a time limit of its own to match (a full run on a real database takes seconds, not milliseconds).
|
|
163
|
+
|
|
164
|
+
Load a fixture member marked `canSignIn: false` the way your app stores someone who can no longer sign in (deactivated, removed, invitation not accepted).
|
|
165
|
+
|
|
166
|
+
What the kit cannot see: whether your lock holds across separate processes. It runs in one process, so build the harness's two admin stores on two separate connection pools; then only a lock held in the database passes.
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
## Keys and agents
|
|
170
|
+
|
|
171
|
+
A key or an agent goes through the same `resolveScope` as a member. There is one set of rules.
|
|
172
|
+
|
|
173
|
+
| Subject | What it reads |
|
|
174
|
+
|---|---|
|
|
175
|
+
| Key tied to a team | What that team's rules allow. No role is consulted, so no role can widen it. |
|
|
176
|
+
| Key tied to no team | The whole organization. This is how a key behaves before anybody ties it. |
|
|
177
|
+
| Agent acting for a member | Exactly what that member reads. |
|
|
178
|
+
| Agent acting for a team | What that team's rules allow, like a key tied to it. |
|
|
179
|
+
|
|
180
|
+
A manager ties keys and limits them:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
await tieKey(actor, { keyId, groupId: 'team-1' }, deps); // the key now reads as team-1
|
|
184
|
+
await tieKey(actor, { keyId, groupId: null }, deps); // whole organization again
|
|
185
|
+
await limitKeyAreas(actor, { keyId, areas: ['files'] }, deps); // nothing outside 'files'
|
|
186
|
+
await limitKeyAreas(actor, { keyId, areas: [] }, deps); // the key reads nothing
|
|
187
|
+
await limitKeyAreas(actor, { keyId, areas: null }, deps); // no area limit
|
|
188
|
+
await listKeys(actor, deps); // every key, with team and areas
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
- **Untying widens.** `groupId: null` gives the key the whole organization. It needs the same right as tying, and the history records it with the team the key had. Whoever manages access can widen a key, as they can widen a team with a grant or a rule; a role that should not do that should not manage access.
|
|
192
|
+
- **Area names are not checked against anything.** A name no area has simply never matches.
|
|
193
|
+
- **Team tags ignore the area list.** `teamTagsFor` gives a key its team's tag in every area; the list limits reading only.
|
|
194
|
+
- **An agent has no area list.** An agent acting for a team reads every area that team's rules allow.
|
|
195
|
+
- **The area list narrows only.** It is checked before the team and before the switch.
|
|
196
|
+
- **An empty list is not "no limit".** `[]` closes the key; `null` lifts the limit. Your store must keep the two apart, and the kit checks that it does.
|
|
197
|
+
- **A team with a key tied to it cannot be deleted.** Untie or move the key first.
|
|
198
|
+
- **The store.** The admin transaction needs `getKey`, `listKeys`, `setKeyTeam` and `setKeyAreas`, each bound to the transaction's organization. `getKeyTeam` on the read side returns the team and `areas` (null for no limit). A row without `areas` is refused, so a forgotten column cannot open a key.
|
|
199
|
+
- **What the package does not do.** It does not issue, check or revoke keys, and it does not know which request came from which key. Your app establishes the subject; this package says what that subject may read.
|
|
200
|
+
|
|
201
|
+
## Hidden fields and action limits
|
|
202
|
+
|
|
203
|
+
A scope says which records a subject sees. Limits say what it must not be shown, or allowed to do, on the records it does see. They are stored per team and area:
|
|
204
|
+
|
|
205
|
+
- **Hidden field groups**: names such as `prices`. Your app decides which fields each name covers.
|
|
206
|
+
- **Denied actions**: names such as `export` or `bulkChange`.
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
import { resolveLimits, redact, mayDo } from '@ordinatio/access';
|
|
210
|
+
|
|
211
|
+
const { scope, limits } = await resolveLimits(subject, 'files', { store, roles, isEnabled, logger, limits: limitStore });
|
|
212
|
+
if (!mayDo(limits, 'export')) deny();
|
|
213
|
+
const safe = rows.map((row) => redact(row, { prices: ['price', 'cost'] }, limits));
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
`resolveLimits` returns the same scope `resolveScope` does, so one call serves both. `limitStore` is a second, small port: `getTeamLimits(organizationId, groupId, area)` returns `{ hiddenFields, deniedActions }`, or `null` when none were set.
|
|
217
|
+
|
|
218
|
+
How limits are decided:
|
|
219
|
+
|
|
220
|
+
| The subject | Limits |
|
|
221
|
+
|---|---|
|
|
222
|
+
| The switch is off for the area, or the role sees everything in it | none |
|
|
223
|
+
| A key tied to no team | none |
|
|
224
|
+
| A member, key or agent with a confirmed team | that team's limits for the area |
|
|
225
|
+
| Sees nothing in the area, or has no team that can be confirmed | closed: every field group hidden, every action refused |
|
|
226
|
+
|
|
227
|
+
- Limits do not depend on rules. A team with no rules sees every record and still has its limits.
|
|
228
|
+
- `redact` removes top-level fields only. To hide a value nested inside a list or an object, name the outer field in the group.
|
|
229
|
+
- A hidden group your app no longer has in its map hides every grouped field. What that name meant is unknown, so nothing grouped is sent.
|
|
230
|
+
- `redact` takes one plain record. A list, `null`, or a field-group map it cannot read (not an object, or a group that is not a list of field names) is refused with `ACCESS_111`; nothing is returned. Redact a list one row at a time.
|
|
231
|
+
- The copy holds the record's own enumerable fields only. Fields on a class prototype and symbol keys are not copied. A `toJSON` function of the record's own is copied like any field, so do not give records one.
|
|
232
|
+
- The field-group map must be a plain object. With an empty map there is nothing to hide, also for closed limits: list every sensitive field in a group.
|
|
233
|
+
- Names are compared exactly: `Export` is not `export`.
|
|
234
|
+
- Call `redact` on the server, last, on every path that sends a record out: lists, single reads, exports, search results and anything nested in another answer. A field left in one path is a leak.
|
|
235
|
+
- Closed limits carry empty lists and `closed: true`. Always go through `redact` and `mayDo`, or check `closed` first; do not read the lists alone.
|
|
236
|
+
- `mayDo` refuses when the limits are closed, unreadable, or the action has no name.
|
|
237
|
+
- If the limit store throws, `resolveLimits` rejects with `ACCESS_110`. If it answers in the wrong shape, with `ACCESS_109`. Only `null` means "no limits".
|
|
238
|
+
|
|
239
|
+
### Setting limits
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import { setTeamLimits, readTeamLimits } from '@ordinatio/access';
|
|
243
|
+
|
|
244
|
+
await setTeamLimits(actor, { groupId, area: 'files', hiddenFields: ['prices'], deniedActions: ['export'] }, deps);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
- Only a member whose role manages access may set or read limits, and only for a team of their own organization.
|
|
248
|
+
- The two lists replace what was there. Two empty lists lift every limit.
|
|
249
|
+
- Each change is written to the history as `limits.set`, with the lists from before. Setting what is already there writes nothing.
|
|
250
|
+
- At most 100 names per list as given, repeats included, each at most 100 characters. A stored row beyond that can still be read and replaced.
|
|
251
|
+
- Your admin transaction gains two methods, `getLimits(groupId, area)` and `setLimits(groupId, area, limits)`. They take part in the transaction and are bound to its organization.
|
|
252
|
+
- `deleteGroup` removes the team's limits in the same transaction and keeps them in the history entry, through the store method `deleteLimitsOfGroup`.
|
|
253
|
+
|
|
254
|
+
Prove your stores with the limit kit. It checks that a change reaches the read side, stays inside one organization, team and area, is not kept when the transaction fails, and goes with its team when the team is deleted:
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
import { runLimitMatrix, assertLimitMatrix } from '@ordinatio/access/testing';
|
|
258
|
+
|
|
259
|
+
assertLimitMatrix(await runLimitMatrix({ makeHarness, cleanup }));
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
`makeHarness(fixture, limits)` returns your admin harness with the two transaction methods, plus `limits` (your read-side limit store) and `listLimits(organizationId)`. `withMemoryLimits` is the in-memory reference; `reference/postgres/limit-store.ts` is the same on SQL.
|
|
263
|
+
|
|
264
|
+
## Asking for access
|
|
265
|
+
|
|
266
|
+
A member can ask that their team may see another team's work for some days. Asking changes nothing: only an approval makes a grant, and that grant always ends.
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import { requestAccess, decideRequest, withdrawRequest, listRequests } from '@ordinatio/access';
|
|
270
|
+
|
|
271
|
+
const { id } = await requestAccess(member, { visibleGroupId, reason: 'covering next week', days: 7 }, deps);
|
|
272
|
+
await decideRequest(manager, { requestId: id, approve: true }, deps); // or approve: false, or days: 3
|
|
273
|
+
await withdrawRequest(member, { requestId: id }, deps); // the requester, while it is open
|
|
274
|
+
const open = await listRequests(manager, { status: 'open' }, deps);
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
- **Who may do what.** Any member with a team may ask, always for their own team; the team is taken from the member, never from the caller. Only a member who manages access decides. Only the requester withdraws. A manager lists the whole organization; anyone else lists their own.
|
|
278
|
+
- **Limits.** 1 to 90 days, a reason of at most 500 characters, 5 open requests per member, one open request per member and team. A team that already holds a grant to the other one that still counts cannot ask again (`ACCESS_281`).
|
|
279
|
+
- **Approval.** The grant and the closed request are written in one transaction, with the grant ending after the asked days counted from the approval. A manager may give fewer or more days. If a grant between the two teams is still counting, the approval is refused (`ACCESS_205`) and the request stays open. A closed request is never decided again (`ACCESS_284`).
|
|
280
|
+
- **Out of date.** An approval answers the question that was asked. If the asker has since moved to another team or is no longer a member, or one of the two teams is gone, approving makes no grant: the request closes as `outdated` and `decideRequest` returns that status, so tell the three results apart: `approved`, `denied`, `outdated`. A member who moved asks again from where they are now. Denying and withdrawing work as before.
|
|
281
|
+
- **Volume.** Only open requests are limited. Closed ones stay as a record and `listRequests` returns them all, so limit how often a member may call `requestAccess` the way you limit any other write.
|
|
282
|
+
- **The store.** Requests need four more methods on the same transaction as the admin side (`AccessRequestTx`: `insertRequest`, `getRequest`, `listRequests`, `closeRequest`), so pass `deps.admin` as an `AccessAdminStore<RequestAdminTx>`. `closeRequest` must change a request only while it is open and say whether it did. Apps that do not use requests implement nothing.
|
|
283
|
+
- **Proving your store.** `runRequestMatrix({ makeHarness })` from `@ordinatio/access/testing` runs 9 scenarios; `makeHarness(fixture, requests)` returns the admin harness plus `listRequests(organizationId)`. `withMemoryRequests` is the in-memory reference.
|
|
284
|
+
|
|
285
|
+
## Team tags
|
|
286
|
+
|
|
287
|
+
A team tag is the team's id on a record. The usual rule for a team is "sees records carrying its tag" (`{ kind: 'teamTag', teamIds: [...] }`), so tagging is what makes work show up for the right people. The package does not add that rule for you: a team with no rules sees everything, so give a new team its rule when you create it.
|
|
288
|
+
|
|
289
|
+
**Tagging new work.** Wherever your app creates a record, or a member handles one (assigns it, replies, adds a note), ask which tag it must carry and add it:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
const add = await teamTagsFor(subject, 'files', deps); // the subject's team, or [] if none can be established
|
|
293
|
+
record.teamTagIds = mergeTeamTags(record.teamTagIds, add); // adds only
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
`teamTagsFor` works for members, keys and agents. It looks at neither the area's switch nor the role's level for the area: records are tagged from day one, so turning restriction on later hides nothing by accident. `mergeTeamTags` never removes a tag. When a member moves to another team, their earlier work keeps the tag it had.
|
|
297
|
+
|
|
298
|
+
Save the added tag as one step in the database (an insert that ignores a row already there, or an append-if-absent), not by writing the whole list back: two people handling the same record at once would otherwise lose one of the tags.
|
|
299
|
+
|
|
300
|
+
**The lock.** Team tags decide who sees a record, so changing them by hand is for members whose role manages access. Before saving a hand edit, call `checkTeamTagEdit(actor, { area, before, after }, deps)`. An unchanged list passes for anyone. Otherwise it refuses with `ACCESS_260` unless the actor manages access, and with `ACCESS_261` if an added tag is not a team of the same organization. A list holding anything but non-empty strings is refused outright. It returns `{ added, removed, after }`; save the returned `after` and nothing else. Three things stay with your app: read `before` from your own tables, never from the request; call the check on every path that can change team tags; and make sure the record belongs to the actor's organization. Plain tags are yours to handle as you like.
|
|
301
|
+
|
|
302
|
+
**Backfill.** To tag what a team's members already own, implement two calls over your own tables:
|
|
303
|
+
|
|
304
|
+
```ts
|
|
305
|
+
const tags: TeamTagStore = {
|
|
306
|
+
countUntagged(organizationId, area, teamId, ownerIds) { /* how many of their records lack the tag */ },
|
|
307
|
+
tagUntagged(organizationId, area, teamId, ownerIds, limit) { /* tag up to `limit` of them, return how many */ },
|
|
308
|
+
};
|
|
309
|
+
await previewBackfill(actor, { groupId, area }, { ...adminDeps, store, tags }); // { members, records }
|
|
310
|
+
await runBackfill(actor, { groupId, area }, { ...adminDeps, store, tags }); // { tagged, done }
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Both need a role that manages access. A run works in batches and tags nothing twice, so a run that stopped (`done: false`) or failed is finished by running it again. The history gets a `teamTag.backfill.start` line before anything is tagged and a `teamTag.backfill` line with the result after. If the result line cannot be written the run fails with `ACCESS_264`, which says how much was tagged. A long run stops when the member who started it stops managing access. `listMemberIdsInGroups` must include members who can no longer sign in, so what they left is tagged with the rest. A run is `done` only when the count of untagged records has come back as zero (a team with no members is done at once).
|
|
314
|
+
|
|
315
|
+
A backfill covers the members who are on the team. A member with no team gets the default team's tag on new work, but no backfill reaches what they already own: give them a team first, then run it.
|
|
316
|
+
|
|
317
|
+
`tagUntagged` must add the tag in one step per record, as above, count a record once however many of its owners are on the team, and cope with a long owner list.
|
|
318
|
+
|
|
319
|
+
### Proving your tag store
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
const results = await runTeamTagMatrix({ makeHarness: (records) => myTagHarness(records), cleanup });
|
|
323
|
+
assertTeamTagMatrix(results);
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
`makeHarness` loads the given records into your tables and returns `{ tags, read }`. Ten scenarios check that the count matches what a run tags, that one matching owner is enough and ids are compared exactly, that tagging only adds, that a second run does nothing, that a batch respects its limit, that a long member list works, that no members means no records, and that other organizations, other areas and other teams are left alone. The kit runs in one process, so it cannot see two writers at once; the one-step rule above is yours to keep.
|
|
327
|
+
|
|
328
|
+
## Seeing before saving
|
|
329
|
+
|
|
330
|
+
Three calls for an admin screen. Each needs a member who manages access, writes nothing, and only looks inside the acting organization.
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
import { viewAs, explainAccess, previewRuleChange } from '@ordinatio/access';
|
|
334
|
+
|
|
335
|
+
// What does this member, key or team see in this area, and why?
|
|
336
|
+
const seen = await viewAs(actor, { subject, area: 'files' }, deps);
|
|
337
|
+
// { scope, reason: 'rules' | 'noRules' | 'seesAll' | 'switchOff' | 'noTeam' | ..., groupId }
|
|
338
|
+
|
|
339
|
+
// Is this one record visible to them, and which rule decides?
|
|
340
|
+
const why = await explainAccess(actor, { subject, area: 'files', facts }, deps);
|
|
341
|
+
// why.match: { visible: true, by: 'clause', index, clause } or { visible: false, by: 'noClauseMatches' } ...
|
|
342
|
+
|
|
343
|
+
// What would these rules change for the team, before saving them?
|
|
344
|
+
const preview = await previewRuleChange(actor, { groupId, area: 'files', rules }, { ...deps, impact });
|
|
345
|
+
// { before, after, gained, lost, kept }
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
`deps` here is the admin `deps` plus the read `store` and `isEnabled`.
|
|
349
|
+
|
|
350
|
+
- **View as** signs nobody in. It runs the same resolver your lists use and returns its answer with the reason. To look as a team, pass an agent acting for that team.
|
|
351
|
+
- **Explain** says more than the subject should learn: it names rules, teams and members. Show it to admins only, never to the member who was refused.
|
|
352
|
+
- **Preview** checks the shape of the proposed rules and the teams they name as saving does, and saves nothing. An empty list can be previewed; saving it still needs `wideOpen: true`. It shows what the rules alone decide, as if the area's switch were on, for the team as a whole. A member also sees their own records under an owner rule; the preview does not add that. A member whose role sees the whole area is not affected by rules at all.
|
|
353
|
+
|
|
354
|
+
`resolveScopeDetailed` and `explainMatch` are the two plain functions underneath, for code that has already decided who may ask.
|
|
355
|
+
|
|
356
|
+
### Checking your record counts
|
|
357
|
+
|
|
358
|
+
The preview counts through an `ImpactStore` you write: `countMatching` (records of an area inside a scope) and `countMatchingBoth` (inside two scopes at once). Build it on the same query filter your lists use, then check it:
|
|
359
|
+
|
|
360
|
+
```ts
|
|
361
|
+
import { runImpactMatrix, assertImpactMatrix } from '@ordinatio/access/testing';
|
|
362
|
+
|
|
363
|
+
assertImpactMatrix(await runImpactMatrix({ makeStore: (records) => myImpactStoreHolding(records), cleanup }));
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
The kit hands your store a small set of records and asks for counts under many shapes of scope, each alone in two areas and two organizations and in pairs in one, and compares each count with the package's own decision. Because the store shares your list filter, a green run is strong evidence that the filter turns a scope into a query correctly: empty lists, unknown kinds of clause, several ids, several owners, and ids that differ only in case or length are all in it. `createMemoryImpactStore` is the reference.
|