@ddd-ts-kit/openfga 0.84.1 → 0.86.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 (40) hide show
  1. package/README.fr.md +44 -35
  2. package/README.md +43 -35
  3. package/dist/authorizer/open-fga-authorizer-options.d.ts +3 -3
  4. package/dist/authorizer/open-fga-authorizer-options.d.ts.map +1 -1
  5. package/dist/authorizer/open-fga-authorizer.d.ts +3 -1
  6. package/dist/authorizer/open-fga-authorizer.d.ts.map +1 -1
  7. package/dist/authorizer/open-fga-authorizer.js +10 -6
  8. package/dist/authorizer/open-fga-authorizer.js.map +1 -1
  9. package/dist/client/open-fga-client.d.ts.map +1 -1
  10. package/dist/index.d.ts +2 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/model/authorization-model-of.d.ts +3 -2
  15. package/dist/model/authorization-model-of.d.ts.map +1 -1
  16. package/dist/model/authorization-model-of.js +17 -7
  17. package/dist/model/authorization-model-of.js.map +1 -1
  18. package/dist/model/ensure-authorization-model.d.ts.map +1 -1
  19. package/dist/model/ensure-authorization-model.js.map +1 -1
  20. package/dist/model/model-drift.d.ts.map +1 -1
  21. package/dist/model/model-drift.js.map +1 -1
  22. package/dist/model/open-fga-model-error.d.ts +5 -0
  23. package/dist/model/open-fga-model-error.d.ts.map +1 -0
  24. package/dist/model/open-fga-model-error.js +8 -0
  25. package/dist/model/open-fga-model-error.js.map +1 -0
  26. package/dist/model/relation-name-of.d.ts +8 -0
  27. package/dist/model/relation-name-of.d.ts.map +1 -0
  28. package/dist/model/relation-name-of.js +18 -0
  29. package/dist/model/relation-name-of.js.map +1 -0
  30. package/dist/model/userset-of.d.ts +4 -4
  31. package/dist/model/userset-of.d.ts.map +1 -1
  32. package/dist/model/userset-of.js +25 -20
  33. package/dist/model/userset-of.js.map +1 -1
  34. package/dist/sdk.d.ts.map +1 -1
  35. package/dist/sdk.js.map +1 -1
  36. package/dist/store/open-fga-relation-tuple-store.d.ts +10 -6
  37. package/dist/store/open-fga-relation-tuple-store.d.ts.map +1 -1
  38. package/dist/store/open-fga-relation-tuple-store.js +33 -22
  39. package/dist/store/open-fga-relation-tuple-store.js.map +1 -1
  40. package/package.json +4 -4
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:903eebf3bd591305 -->
2
+ <!-- translation-of: README.md sha256:7389dc2d40830bbe -->
3
3
 
4
4
  # @ddd-ts-kit/openfga
5
5
 
@@ -29,26 +29,33 @@ et un magasin de tuples dans votre propre base de données.
29
29
  ## Le modèle, à partir du schéma
30
30
 
31
31
  Le schéma est celui qu'évalue `RelationBasedAuthorizer` dans le processus : des types, les
32
- relations qu'un tuple peut porter, et les permissions qui en dérivent. `authorizationModelOf` le
32
+ relations qu'un tuple peut porter, et les relations qui en dérivent, dont celles nommées d'après
33
+ une permission. `authorizationModelOf` le
33
34
  transforme en corps de `WriteAuthorizationModel` (schéma 1.1). Voici un schéma simplifié, inspiré
34
35
  de celui de l'application d'exemple :
35
36
 
36
37
  <!-- checked sample -->
37
38
  ```ts
38
- import { defineSchema, from, union } from '@ddd-ts-kit/auth/rebac';
39
+ import { definePermissions } from '@ddd-ts-kit/auth';
40
+ import { defineSchema, via } from '@ddd-ts-kit/auth/rebac';
39
41
  import { authorizationModelOf } from '@ddd-ts-kit/openfga';
40
42
 
43
+ export const schedulingPermissions = definePermissions('scheduling', {
44
+ 'appointment.cancel': { description: 'Cancel an appointment' },
45
+ });
46
+
41
47
  // Qui est quoi pour quel élément : un cabinet a des responsables, un agenda son titulaire et ses assistants.
42
48
  export const relationshipSchema = defineSchema({
43
49
  user: {},
44
- practice: { relations: { manager: ['user'] }, permissions: { manage: union('manager') } },
50
+ practice: { relations: { manager: ['user'] }, derived: { manage: 'manager' } },
45
51
  calendar: {
46
52
  relations: { holder: ['user'], assistant: ['user'], practice: ['practice'] },
47
- permissions: { run: union('holder', 'assistant', from('practice', 'manage')) },
53
+ derived: { run: { anyOf: ['holder', 'assistant', via('practice', 'manage')] } },
48
54
  },
49
55
  appointment: {
50
56
  relations: { patient: ['user'], calendar: ['calendar'] },
51
- permissions: { change: union('patient', from('calendar', 'run')) },
57
+ // Annuler un rendez-vous, c'est détenir `change` sur lui : la relation dérivée nommée d'après la permission l'accorde.
58
+ derived: { change: { anyOf: ['patient', via('calendar', 'run')] }, [schedulingPermissions['appointment.cancel'].id]: 'change' },
52
59
  },
53
60
  });
54
61
 
@@ -82,15 +89,22 @@ type appointment
82
89
  define patient: [user]
83
90
  define calendar: [calendar]
84
91
  define change: patient or run from calendar
92
+ define scheduling_appointment_cancel: change
85
93
  ```
86
94
 
95
+ Une relation dérivée nommée d'après l'identifiant d'une permission ne peut pas garder son nom :
96
+ OpenFGA refuse `:` dans un nom de relation. `relationNameOf` écrit `scheduling:appointment.cancel`
97
+ en `scheduling_appointment_cancel`, dans le modèle comme dans chaque `Check` et `ListObjects` ;
98
+ aucun identifiant de permission ne contient `_`, deux ne deviennent donc jamais un même nom.
99
+
87
100
  | Schéma de `@ddd-ts-kit/auth/rebac` | OpenFGA |
88
101
  |---|---|
89
102
  | une relation et les sujets qu'elle énumère : `editor: ['user', 'group#member']` | une relation directement attribuable (`this`) avec `directly_related_user_types` |
90
- | un nom dans une réécriture : `union('owner', 'editor')` | un *userset* calculé (computed userset) |
91
- | `union(...)`, `intersection(...)` | `union`, `intersection` |
92
- | `exclusion(base, subtract)` | `difference` |
93
- | `from('parent', 'edit')` | un *tuple to userset* |
103
+ | un nom parmi les voies : `edit: 'owner'`, `anyOf: ['owner', 'editor']` | un *userset* calculé (computed userset) |
104
+ | `anyOf`, `allOf` | `union`, `intersection` |
105
+ | `butNot` | `difference` |
106
+ | `via('parent', 'edit')` | un *tuple to userset*, `edit from parent` |
107
+ | une relation dérivée nommée `docs:document.edit` | la relation `docs_document_edit` |
94
108
 
95
109
  `ensureAuthorizationModel(client, schema)` écrit le modèle généré quand le dernier modèle du
96
110
  magasin en diffère, et renvoie l'identifiant en vigueur et les différences (OpenFGA garde chaque
@@ -145,42 +159,35 @@ calendar#run differs: the schema says union(holder, assistant, from(practice, ma
145
159
 
146
160
  ## Le magasin et l'*authorizer*
147
161
 
148
- Dans la racine de composition, un seul client lié à un seul magasin sert les deux adaptateurs. La
149
- correspondance (`mapping`) dit, par type de ressource, quelle relation du modèle représente
150
- chaque permission du kit, comme pour `RelationBasedAuthorizer` :
162
+ Dans la racine de composition, un seul client lié à un seul magasin sert les deux adaptateurs.
163
+ Tous deux lisent le schéma : le magasin pour donner à un sujet le *userset* que dit sa relation
164
+ (`group:eng` s'écrit `group:eng#member`), l'*authorizer* pour demander une permission comme la
165
+ relation dérivée nommée d'après elle, comme le fait `RelationBasedAuthorizer` :
151
166
 
152
167
  <!-- checked sample -->
153
168
  ```ts
154
- import { definePermissions } from '@ddd-ts-kit/auth';
155
- import type { PermissionMapping, Schema } from '@ddd-ts-kit/auth/rebac';
169
+ import type { Schema } from '@ddd-ts-kit/auth/rebac';
156
170
  import { OpenFgaAuthorizer, OpenFgaRelationTupleStore } from '@ddd-ts-kit/openfga';
157
171
  import { openFgaClient } from '@ddd-ts-kit/openfga/sdk';
158
172
 
159
- declare const relationshipSchema: Schema;
173
+ declare const relationshipSchema: Schema; // celui du bloc précédent, avec scheduling:appointment.cancel dérivée sur un rendez-vous
160
174
  declare const config: { readonly openfga: { readonly url: string; readonly storeId: string } };
161
175
 
162
- export const schedulingPermissions = definePermissions('scheduling', {
163
- 'appointment.cancel': { description: 'Cancel an appointment' },
164
- });
165
-
166
- // Annuler un rendez-vous, c'est détenir la relation `change` sur lui.
167
- const mapping: PermissionMapping = {
168
- appointment: { [schedulingPermissions['appointment.cancel'].id]: 'change' },
169
- };
170
-
171
176
  const client = openFgaClient({ apiUrl: config.openfga.url, storeId: config.openfga.storeId });
172
177
 
173
178
  // Les deux mêmes ports que l'authorizer dans le processus et qu'un magasin de tuples dans votre base.
174
179
  export const tuples = new OpenFgaRelationTupleStore(client, relationshipSchema);
175
- export const authorizer = new OpenFgaAuthorizer({ client, mapping, listObjectsLimit: 1000 });
180
+ export const authorizer = new OpenFgaAuthorizer({ client, schema: relationshipSchema, listObjectsLimit: 1000 });
176
181
  ```
177
182
 
178
183
  - `OpenFgaRelationTupleStore` passe `relationTupleStoreContract`, comme le magasin PostgreSQL :
179
184
  écrire deux fois un tuple et supprimer un tuple absent ne changent rien (les options de conflit
180
185
  d'OpenFGA 1.10 et des versions suivantes), les écritures et les suppressions vont par 100, les
181
- lectures suivent chaque page. Une lecture par sujet fait une lecture par relation du schéma qui
182
- accepte la sorte du sujet, puisqu'OpenFGA lit par utilisateur au sein d'un seul type d'objet.
183
- - `OpenFgaAuthorizer` passe `authorizerContract`, avec la correspondance et les codes de refus de
186
+ lectures suivent chaque page. Un tuple du kit nomme son sujet seul ; le magasin écrit le
187
+ *userset* que lui donne le schéma (`group:eng#member`) et le relit seul. Une lecture par sujet
188
+ fait une lecture par relation du schéma qui accepte le type du sujet, puisqu'OpenFGA lit par
189
+ utilisateur au sein d'un seul type d'objet.
190
+ - `OpenFgaAuthorizer` passe `authorizerContract`, avec le schéma et les codes de refus de
184
191
  `RelationBasedAuthorizer` (`ANONYMOUS`, `RESOURCE_REQUIRED`, `UNMAPPED_PERMISSION`,
185
192
  `NO_RELATION`) : `Check` décide, `ListObjects` donne le périmètre d'une recherche
186
193
  (`{ kind: 'ids' }`). Un projet passe de l'un à l'autre par la liaison, rien d'autre ne change.
@@ -207,14 +214,14 @@ await tuples.write([
207
214
 
208
215
  const ada: Actor = { id: 'ada', type: 'user', roles: [], attributes: {} };
209
216
 
210
- // Check user:ada change appointment:42 : { allowed: true }
217
+ // Check user:ada scheduling_appointment_cancel appointment:42 : { allowed: true }
211
218
  export const decision = await authorizer.check({
212
219
  actor: ada,
213
220
  permission: cancel,
214
221
  resource: { type: 'appointment', id: '42' },
215
222
  });
216
223
 
217
- // ListObjects user:ada change appointment : { kind: 'ids', ids: ['42'] }, les identifiants que la recherche peut lire
224
+ // ListObjects user:ada scheduling_appointment_cancel appointment : { kind: 'ids', ids: ['42'] }, les identifiants que la recherche peut lire
218
225
  export const scope = await authorizer.listAccessible({ actor: ada, permission: cancel, resourceType: 'appointment' });
219
226
  ```
220
227
 
@@ -288,8 +295,9 @@ points d'accès des tuples, et contre un vrai serveur quand `DDD_TS_KIT_OPENFGA_
288
295
  le *job* d'intégration du dépôt démarre `openfga/openfga` v1.22.0, épinglé par *digest*. Un projet
289
296
  soumet ses propres adaptateurs aux mêmes suites, chaque test sur un magasin à lui (`createStore`,
290
297
  puis `ensureAuthorizationModel`). Les tuples qu'écrit le contrat du magasin portent sur des
291
- documents et des groupes (`document:1#editor@group:eng#member`, `document:1#parent@group:eng`) :
292
- le magasin sur lequel il s'exécute détient un modèle qui les décrit.
298
+ documents et des groupes (`document:1#editor@group:eng`, que le serveur tient comme
299
+ `group:eng#member`, et `document:1#parent@group:eng`) : le magasin sur lequel il s'exécute
300
+ détient un modèle qui les décrit.
293
301
 
294
302
  <!-- checked sample -->
295
303
  ```ts
@@ -343,8 +351,9 @@ relationTupleStoreContract(
343
351
  non plus.
344
352
  - Le sujet d'un acteur est `<type>:<id>` ; un identifiant qui contient un caractère qu'OpenFGA
345
353
  refuse dans un identifiant d'objet demande `subjectOf`.
346
- - `expand` de `RelationBasedAuthorizer` n'a pas d'équivalent ici : utilisez l'API `Expand`
347
- d'OpenFGA pour le débogage.
354
+ - `explain` de `RelationBasedAuthorizer` n'a pas d'équivalent ici : utilisez l'API `Expand`
355
+ d'OpenFGA pour le débogage, où une relation dérivée nommée d'après une permission porte le nom
356
+ que lui donne `relationNameOf` (`docs_document_edit`).
348
357
 
349
358
  ## Voir aussi
350
359
 
package/README.md CHANGED
@@ -28,26 +28,33 @@ store in your own database.
28
28
  ## The model, from the schema
29
29
 
30
30
  The schema is the one `RelationBasedAuthorizer` evaluates in process: types, the relations a
31
- tuple can hold, and the permissions derived from them. `authorizationModelOf` turns it into the
31
+ tuple can hold, and the relations derived from them, among which the ones named after a
32
+ permission. `authorizationModelOf` turns it into the
32
33
  body of `WriteAuthorizationModel` (schema 1.1). Here is a simplified schema, in the spirit of
33
34
  the one of the example application:
34
35
 
35
36
  <!-- checked sample -->
36
37
  ```ts
37
- import { defineSchema, from, union } from '@ddd-ts-kit/auth/rebac';
38
+ import { definePermissions } from '@ddd-ts-kit/auth';
39
+ import { defineSchema, via } from '@ddd-ts-kit/auth/rebac';
38
40
  import { authorizationModelOf } from '@ddd-ts-kit/openfga';
39
41
 
42
+ export const schedulingPermissions = definePermissions('scheduling', {
43
+ 'appointment.cancel': { description: 'Cancel an appointment' },
44
+ });
45
+
40
46
  // Who is what to which element: a practice has managers, a calendar its holder and assistants.
41
47
  export const relationshipSchema = defineSchema({
42
48
  user: {},
43
- practice: { relations: { manager: ['user'] }, permissions: { manage: union('manager') } },
49
+ practice: { relations: { manager: ['user'] }, derived: { manage: 'manager' } },
44
50
  calendar: {
45
51
  relations: { holder: ['user'], assistant: ['user'], practice: ['practice'] },
46
- permissions: { run: union('holder', 'assistant', from('practice', 'manage')) },
52
+ derived: { run: { anyOf: ['holder', 'assistant', via('practice', 'manage')] } },
47
53
  },
48
54
  appointment: {
49
55
  relations: { patient: ['user'], calendar: ['calendar'] },
50
- permissions: { change: union('patient', from('calendar', 'run')) },
56
+ // To cancel an appointment is to hold `change` on it: the derived relation named after the permission grants it.
57
+ derived: { change: { anyOf: ['patient', via('calendar', 'run')] }, [schedulingPermissions['appointment.cancel'].id]: 'change' },
51
58
  },
52
59
  });
53
60
 
@@ -81,15 +88,22 @@ type appointment
81
88
  define patient: [user]
82
89
  define calendar: [calendar]
83
90
  define change: patient or run from calendar
91
+ define scheduling_appointment_cancel: change
84
92
  ```
85
93
 
94
+ A derived relation named after a permission id cannot keep its name: OpenFGA refuses `:` in a
95
+ relation name. `relationNameOf` writes `scheduling:appointment.cancel` as
96
+ `scheduling_appointment_cancel`, in the model as in every `Check` and `ListObjects`; no
97
+ permission id holds `_`, so two never become one name.
98
+
86
99
  | Schema of `@ddd-ts-kit/auth/rebac` | OpenFGA |
87
100
  |---|---|
88
101
  | a relation and the subjects it lists: `editor: ['user', 'group#member']` | a directly assignable relation (`this`) with `directly_related_user_types` |
89
- | a name in a rewrite: `union('owner', 'editor')` | a computed userset |
90
- | `union(...)`, `intersection(...)` | `union`, `intersection` |
91
- | `exclusion(base, subtract)` | `difference` |
92
- | `from('parent', 'edit')` | a tuple to userset |
102
+ | a name among the ways: `edit: 'owner'`, `anyOf: ['owner', 'editor']` | a computed userset |
103
+ | `anyOf`, `allOf` | `union`, `intersection` |
104
+ | `butNot` | `difference` |
105
+ | `via('parent', 'edit')` | a tuple to userset, `edit from parent` |
106
+ | a derived relation named `docs:document.edit` | the relation `docs_document_edit` |
93
107
 
94
108
  `ensureAuthorizationModel(client, schema)` writes the generated model when the latest one of the
95
109
  store differs, and answers the id in force and the differences (OpenFGA keeps every model; checks
@@ -143,42 +157,35 @@ calendar#run differs: the schema says union(holder, assistant, from(practice, ma
143
157
 
144
158
  ## The store and the authorizer
145
159
 
146
- In the composition root, one client bound to one store serves both adapters. The mapping says,
147
- per resource type, which relation of the model each permission of the kit stands for, as for
148
- `RelationBasedAuthorizer`:
160
+ In the composition root, one client bound to one store serves both adapters. Both read the
161
+ schema: the store to give a subject the userset its relation says (`group:eng` is written
162
+ `group:eng#member`), the authorizer to ask a permission as the derived relation named after it,
163
+ as `RelationBasedAuthorizer` does:
149
164
 
150
165
  <!-- checked sample -->
151
166
  ```ts
152
- import { definePermissions } from '@ddd-ts-kit/auth';
153
- import type { PermissionMapping, Schema } from '@ddd-ts-kit/auth/rebac';
167
+ import type { Schema } from '@ddd-ts-kit/auth/rebac';
154
168
  import { OpenFgaAuthorizer, OpenFgaRelationTupleStore } from '@ddd-ts-kit/openfga';
155
169
  import { openFgaClient } from '@ddd-ts-kit/openfga/sdk';
156
170
 
157
- declare const relationshipSchema: Schema;
171
+ declare const relationshipSchema: Schema; // the one of the block above, with scheduling:appointment.cancel derived on an appointment
158
172
  declare const config: { readonly openfga: { readonly url: string; readonly storeId: string } };
159
173
 
160
- export const schedulingPermissions = definePermissions('scheduling', {
161
- 'appointment.cancel': { description: 'Cancel an appointment' },
162
- });
163
-
164
- // To cancel an appointment is to hold the relation `change` on it.
165
- const mapping: PermissionMapping = {
166
- appointment: { [schedulingPermissions['appointment.cancel'].id]: 'change' },
167
- };
168
-
169
174
  const client = openFgaClient({ apiUrl: config.openfga.url, storeId: config.openfga.storeId });
170
175
 
171
176
  // The same two ports as the in-process authorizer and a tuple store in your database.
172
177
  export const tuples = new OpenFgaRelationTupleStore(client, relationshipSchema);
173
- export const authorizer = new OpenFgaAuthorizer({ client, mapping, listObjectsLimit: 1000 });
178
+ export const authorizer = new OpenFgaAuthorizer({ client, schema: relationshipSchema, listObjectsLimit: 1000 });
174
179
  ```
175
180
 
176
181
  - `OpenFgaRelationTupleStore` passes `relationTupleStoreContract`, as the PostgreSQL store does:
177
182
  writing a tuple twice and deleting one that is not there change nothing (the conflict options
178
- of OpenFGA 1.10 and later), writes and deletes go by 100, reads follow every page. A read by
179
- subject is one read per relation of the schema that accepts the kind of the subject, since
180
- OpenFGA reads by user within one object type.
181
- - `OpenFgaAuthorizer` passes `authorizerContract`, with the mapping and the denial codes of
183
+ of OpenFGA 1.10 and later), writes and deletes go by 100, reads follow every page. A tuple of
184
+ the kit names its subject alone; the store writes the userset the schema gives it
185
+ (`group:eng#member`) and reads it back alone. A read by subject is one read per relation of
186
+ the schema that accepts the type of the subject, since OpenFGA reads by user within one object
187
+ type.
188
+ - `OpenFgaAuthorizer` passes `authorizerContract`, with the schema and the denial codes of
182
189
  `RelationBasedAuthorizer` (`ANONYMOUS`, `RESOURCE_REQUIRED`, `UNMAPPED_PERMISSION`,
183
190
  `NO_RELATION`): `Check` decides, `ListObjects` gives the scope of a search (`{ kind: 'ids' }`).
184
191
  A project moves between the two by binding, nothing else changes.
@@ -205,14 +212,14 @@ await tuples.write([
205
212
 
206
213
  const ada: Actor = { id: 'ada', type: 'user', roles: [], attributes: {} };
207
214
 
208
- // Check user:ada change appointment:42: { allowed: true }
215
+ // Check user:ada scheduling_appointment_cancel appointment:42: { allowed: true }
209
216
  export const decision = await authorizer.check({
210
217
  actor: ada,
211
218
  permission: cancel,
212
219
  resource: { type: 'appointment', id: '42' },
213
220
  });
214
221
 
215
- // ListObjects user:ada change appointment: { kind: 'ids', ids: ['42'] }, the ids the search may read
222
+ // ListObjects user:ada scheduling_appointment_cancel appointment: { kind: 'ids', ids: ['42'] }, the ids the search may read
216
223
  export const scope = await authorizer.listAccessible({ actor: ada, permission: cancel, resourceType: 'appointment' });
217
224
  ```
218
225
 
@@ -284,8 +291,8 @@ endpoints, and against a real server when `DDD_TS_KIT_OPENFGA_URL` is set: the i
284
291
  of the repository starts `openfga/openfga` v1.22.0, pinned by digest. A project holds its own
285
292
  adapters to the same suites, each test on a store of its own (`createStore`, then
286
293
  `ensureAuthorizationModel`). The tuples the store contract writes are about documents and groups
287
- (`document:1#editor@group:eng#member`, `document:1#parent@group:eng`): the store it runs on holds
288
- a model that describes them.
294
+ (`document:1#editor@group:eng`, held by the server as `group:eng#member`, and
295
+ `document:1#parent@group:eng`): the store it runs on holds a model that describes them.
289
296
 
290
297
  <!-- checked sample -->
291
298
  ```ts
@@ -337,8 +344,9 @@ relationTupleStoreContract(
337
344
  - No conditional tuples (OpenFGA conditions): the schema of the kit has no caveats either.
338
345
  - The subject of an actor is `<type>:<id>`; an id holding a character OpenFGA refuses in an
339
346
  object id needs `subjectOf`.
340
- - `expand` of `RelationBasedAuthorizer` has no equivalent here: use the `Expand` API of OpenFGA
341
- for debugging.
347
+ - `explain` of `RelationBasedAuthorizer` has no equivalent here: use the `Expand` API of OpenFGA
348
+ for debugging, where a derived relation named after a permission bears the name
349
+ `relationNameOf` gives it (`docs_document_edit`).
342
350
 
343
351
  ## See also
344
352
 
@@ -1,10 +1,10 @@
1
1
  import type { Actor } from '@ddd-ts-kit/kernel';
2
- import type { PermissionMapping } from '@ddd-ts-kit/auth/rebac';
2
+ import type { Schema } from '@ddd-ts-kit/auth/rebac';
3
3
  import type { OpenFgaApi } from '../client/open-fga-api.js';
4
4
  export interface OpenFgaAuthorizerOptions {
5
5
  readonly client: OpenFgaApi;
6
- /** Per resource type, the relation of the model each permission of the kit stands for, as for `RelationBasedAuthorizer`. */
7
- readonly mapping: PermissionMapping;
6
+ /** The relationship schema the model of the store was generated from: a permission is asked as the derived relation named after it. */
7
+ readonly schema: Schema;
8
8
  /** The subject an actor is in the tuples. Default `<actor type>:<actor id>`, such as `user:ada`. */
9
9
  readonly subjectOf?: (actor: Actor) => string;
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-authorizer-options.d.ts","sourceRoot":"","sources":["../../src/authorizer/open-fga-authorizer-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,4HAA4H;IAC5H,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,oGAAoG;IACpG,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC;IAC9C;;;;;OAKG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACpC"}
1
+ {"version":3,"file":"open-fga-authorizer-options.d.ts","sourceRoot":"","sources":["../../src/authorizer/open-fga-authorizer-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,uIAAuI;IACvI,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oGAAoG;IACpG,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,MAAM,CAAC;IAC9C;;;;;OAKG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACpC"}
@@ -2,7 +2,7 @@ import { type AccessScope, type Authorizer, type CheckRequest, type Decision, ty
2
2
  import type { OpenFgaAuthorizerOptions } from './open-fga-authorizer-options.js';
3
3
  /**
4
4
  * The `Authorizer` port of `@ddd-ts-kit/auth` answered by OpenFGA: `Check` for a decision,
5
- * `ListObjects` for the scope of a search. The same permissions, mapping and denial codes as the
5
+ * `ListObjects` for the scope of a search. The same schema, permissions and denial codes as the
6
6
  * in-process `RelationBasedAuthorizer`, so a project moves from one to the other by binding. Like
7
7
  * it, a listing that may be incomplete is refused: an answer as long as `listObjectsLimit` may
8
8
  * have been cut by the server, and a search narrowed by it would lose elements in silence.
@@ -12,6 +12,8 @@ export declare class OpenFgaAuthorizer implements Authorizer {
12
12
  constructor(options: OpenFgaAuthorizerOptions);
13
13
  check({ actor, permission, resource }: CheckRequest): Promise<Decision>;
14
14
  listAccessible({ actor, permission, resourceType }: ListRequest): Promise<AccessScope>;
15
+ /** Whether the type derives a relation named after the permission. */
16
+ private grants;
15
17
  private subjectOf;
16
18
  }
17
19
  //# sourceMappingURL=open-fga-authorizer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-authorizer.d.ts","sourceRoot":"","sources":["../../src/authorizer/open-fga-authorizer.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,K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ReverseExpansionLimitError } from '@ddd-ts-kit/auth/rebac';
2
2
  import { ALLOWED, DenialReason, deny, } from '@ddd-ts-kit/auth';
3
3
  import { isAnonymous } from '@ddd-ts-kit/kernel';
4
+ import { relationNameOf } from '../model/relation-name-of.js';
4
5
  /** `OPENFGA_LIST_OBJECTS_MAX_RESULTS` of a server that leaves it at its default. */
5
6
  const SERVER_LIST_OBJECTS_LIMIT = 1000;
6
7
  /**
7
8
  * The `Authorizer` port of `@ddd-ts-kit/auth` answered by OpenFGA: `Check` for a decision,
8
- * `ListObjects` for the scope of a search. The same permissions, mapping and denial codes as the
9
+ * `ListObjects` for the scope of a search. The same schema, permissions and denial codes as the
9
10
  * in-process `RelationBasedAuthorizer`, so a project moves from one to the other by binding. Like
10
11
  * it, a listing that may be incomplete is refused: an answer as long as `listObjectsLimit` may
11
12
  * have been cut by the server, and a search narrowed by it would lose elements in silence.
@@ -22,22 +23,21 @@ export class OpenFgaAuthorizer {
22
23
  if (resource === undefined) {
23
24
  return deny(DenialReason.resourceRequired);
24
25
  }
25
- const relation = this.options.mapping[resource.type]?.[permission.id];
26
- if (relation === undefined) {
26
+ if (!this.grants(resource.type, permission.id)) {
27
27
  return deny(DenialReason.unmappedPermission);
28
28
  }
29
29
  const object = `${resource.type}:${resource.id}`;
30
+ const relation = relationNameOf(permission.id);
30
31
  const { allowed } = await this.options.client.check({ user: this.subjectOf(actor), relation, object });
31
32
  return allowed === true ? ALLOWED : deny(DenialReason.noRelation);
32
33
  }
33
34
  async listAccessible({ actor, permission, resourceType }) {
34
- const relation = this.options.mapping[resourceType]?.[permission.id];
35
- if (isAnonymous(actor) || relation === undefined) {
35
+ if (isAnonymous(actor) || !this.grants(resourceType, permission.id)) {
36
36
  return { kind: 'none' };
37
37
  }
38
38
  const { objects } = await this.options.client.listObjects({
39
39
  user: this.subjectOf(actor),
40
- relation,
40
+ relation: relationNameOf(permission.id),
41
41
  type: resourceType,
42
42
  });
43
43
  const limit = this.options.listObjectsLimit ?? SERVER_LIST_OBJECTS_LIMIT;
@@ -46,6 +46,10 @@ export class OpenFgaAuthorizer {
46
46
  }
47
47
  return { kind: 'ids', ids: objects.map((object) => object.slice(resourceType.length + 1)).sort() };
48
48
  }
49
+ /** Whether the type derives a relation named after the permission. */
50
+ grants(resourceType, permissionId) {
51
+ return this.options.schema.derived(resourceType)[permissionId] !== undefined;
52
+ }
49
53
  subjectOf(actor) {
50
54
  return this.options.subjectOf?.(actor) ?? `${actor.type}:${actor.id}`;
51
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-authorizer.js","sourceRoot":"","sources":["../../src/authorizer/open-fga-authorizer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EACL,OAAO,EACP,YAAY,EACZ,IAAI,GAML,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAc,MAAM,oBAAoB,CAAC;AAG7D,oFAAoF;AACpF,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,OAAO,iBAAiB;IACC,OAAO;IAApC,YAA6B,OAAiC;uBAAjC,OAAO;IAA6B,CAAC;IAElE,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAgB;QACvD,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;QACtC,CAAC;QAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC;QAC7C,CAAC;QAED,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QAEtE,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,OAA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IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;IACrG,CAAC;IAED,sEAAsE;IAC9D,MAAM,CAAC,YAAoB,EAAE,YAAoB;QACvD,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,KAAK,SAAS,CAAC;IAC/E,CAAC;IAEO,SAAS,CAAC,KAAY;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC;IACxE,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-client.d.ts","sourceRoot":"","sources":["../../src/client/open-fga-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEzE,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,EAAE,oBAAoB,GAAG,UAAU,CASnH"}
1
+ {"version":3,"file":"open-fga-client.d.ts","sourceRoot":"","sources":["../../src/client/open-fga-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,EAAE,oBAAoB,GAAG,UAAU,CASnH"}
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export type { OpenFgaApi, OpenFgaTupleKey } from './client/open-fga-api.js';
4
4
  export { authorizationModelOf } from './model/authorization-model-of.js';
5
5
  export { ensureAuthorizationModel } from './model/ensure-authorization-model.js';
6
6
  export { modelDrift } from './model/model-drift.js';
7
+ export { OpenFgaModelError } from './model/open-fga-model-error.js';
7
8
  export type { OpenFgaModel, OpenFgaRelationReference, OpenFgaTypeDefinition, OpenFgaUserset, } from './model/open-fga-model.js';
9
+ export { relationNameOf } from './model/relation-name-of.js';
8
10
  export { OpenFgaRelationTupleStore } from './store/open-fga-relation-tuple-store.js';
9
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,YAAY,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AAC5F,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,YAAY,EACV,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,YAAY,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACzF,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,YAAY,EACV,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,cAAc,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC"}
package/dist/index.js CHANGED
@@ -2,5 +2,7 @@ export { OpenFgaAuthorizer } from './authorizer/open-fga-authorizer.js';
2
2
  export { authorizationModelOf } from './model/authorization-model-of.js';
3
3
  export { ensureAuthorizationModel } from './model/ensure-authorization-model.js';
4
4
  export { modelDrift } from './model/model-drift.js';
5
+ export { OpenFgaModelError } from './model/open-fga-model-error.js';
6
+ export { relationNameOf } from './model/relation-name-of.js';
5
7
  export { OpenFgaRelationTupleStore } from './store/open-fga-relation-tuple-store.js';
6
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAGxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAOpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAGrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAOjE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC"}
@@ -3,8 +3,9 @@ import type { OpenFgaModel } from './open-fga-model.js';
3
3
  /**
4
4
  * The authorization model of OpenFGA for a relationship schema: one source of truth, the schema
5
5
  * the project declares with `defineSchema`, from which the model is generated and checked
6
- * (`modelDrift`), never written by hand next to it. A relation of the schema is directly
7
- * assignable to the subjects it lists; a permission is the rewrite that derives it.
6
+ * (`modelDrift`), never written by hand next to it. A stored relation of the schema is directly
7
+ * assignable to the subjects it lists; a derived relation is the rewrite that derives it, under
8
+ * the name `relationNameOf` gives it.
8
9
  */
9
10
  export declare function authorizationModelOf(schema: Schema): OpenFgaModel;
10
11
  //# sourceMappingURL=authorization-model-of.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-model-of.d.ts","sourceRoot":"","sources":["../../src/model/authorization-model-of.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EACV,YAAY,EAIb,MAAM,qBAAqB,CAAC;AAG7B;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAEjE"}
1
+ {"version":3,"file":"authorization-model-of.d.ts","sourceRoot":"","sources":["../../src/model/authorization-model-of.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAErD,OAAO,KAAK,EAAE,YAAY,EAAmE,MAAM,kBAAkB,CAAC;AAItH;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAEjE"}
@@ -1,28 +1,32 @@
1
+ import { OpenFgaModelError } from './open-fga-model-error.js';
2
+ import { relationNameOf } from './relation-name-of.js';
1
3
  import { usersetOf } from './userset-of.js';
2
4
  /**
3
5
  * The authorization model of OpenFGA for a relationship schema: one source of truth, the schema
4
6
  * the project declares with `defineSchema`, from which the model is generated and checked
5
- * (`modelDrift`), never written by hand next to it. A relation of the schema is directly
6
- * assignable to the subjects it lists; a permission is the rewrite that derives it.
7
+ * (`modelDrift`), never written by hand next to it. A stored relation of the schema is directly
8
+ * assignable to the subjects it lists; a derived relation is the rewrite that derives it, under
9
+ * the name `relationNameOf` gives it.
7
10
  */
8
11
  export function authorizationModelOf(schema) {
9
12
  return { schema_version: '1.1', type_definitions: schema.types().map((type) => typeDefinitionOf(schema, type)) };
10
13
  }
11
14
  function typeDefinitionOf(schema, type) {
12
15
  const relations = Object.entries(schema.relations(type));
13
- const permissions = Object.entries(schema.permissions(type));
14
- if (relations.length === 0 && permissions.length === 0) {
16
+ const derived = Object.entries(schema.derived(type));
17
+ if (relations.length === 0 && derived.length === 0) {
15
18
  return { type };
16
19
  }
17
- const direct = relations.map(([name]) => [name, { this: {} }]);
18
- const derived = permissions.map(([name, rewrite]) => [name, usersetOf(rewrite)]);
20
+ const stored = relations.map(([name]) => [name, { this: {} }]);
21
+ const rewritten = derived.map(([name, ways]) => [relationNameOf(name), usersetOf(ways)]);
22
+ assertDistinct(type, [...stored, ...rewritten].map(([name]) => name));
19
23
  const assignable = relations.map(([name, subjects]) => [
20
24
  name,
21
25
  { directly_related_user_types: subjects.map(referenceOf) },
22
26
  ]);
23
27
  return {
24
28
  type,
25
- relations: Object.fromEntries([...direct, ...derived]),
29
+ relations: Object.fromEntries([...stored, ...rewritten]),
26
30
  metadata: { relations: Object.fromEntries(assignable) },
27
31
  };
28
32
  }
@@ -31,4 +35,10 @@ function referenceOf(subject) {
31
35
  const [type = subject, relation] = subject.split('#');
32
36
  return relation === undefined ? { type } : { type, relation };
33
37
  }
38
+ function assertDistinct(type, names) {
39
+ const twice = names.find((name, index) => names.indexOf(name) !== index);
40
+ if (twice !== undefined) {
41
+ throw new OpenFgaModelError(`"${type}" has two relations that OpenFGA would both call "${twice}".`);
42
+ }
43
+ }
34
44
  //# sourceMappingURL=authorization-model-of.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authorization-model-of.js","sourceRoot":"","sources":["../../src/model/authorization-model-of.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAc;IACjD,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,gBAAgB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;AACnH,CAAC;AAED,SAAS,gBAAgB,CAAC,MAAc,EAAE,IAAY;IACpD,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;IACzD,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;IAE7D,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvD,OAAO,EAAE,IAAI,EAAE,CAAC;IAClB,CAAC;IAED,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAA4B,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;IACzF,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,EAA4B,EA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AAQ,EAAE,EAAE,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE;KACxD,CAAC;AACJ,CAAC;AAMD,+EAA+E;AAC/E,SAAS,WAAW,CAAC,OAAe;IAClC,MAAM,CAAC,IAAI,GAAG,OAAO,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEtD,OAAO,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAChE,CAAC;AAED,SAAS,cAAc,CAAC,IAAY,EAAE,KAAwB;IAC5D,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;IAEzE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,IAAI,iBAAiB,CAAC,IAAI,IAAI,qDAAqD,KAAK,IAAI,CAAC,CAAC;IACtG,CAAC;AACH,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ensure-authorization-model.d.ts","sourceRoot":"","sources":["../../src/model/ensure-authorization-model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAI5D;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC,CAY5E"}
1
+ {"version":3,"file":"ensure-authorization-model.d.ts","sourceRoot":"","sources":["../../src/model/ensure-authorization-model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAIzD;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC,CAY5E"}
@@ -1 +1 @@
1
- {"version":3,"file":"ensure-authorization-model.js","sourceRoot":"","sources":["../../src/model/ensure-authorization-model.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,MAAkB,EAClB,MAAc;IAEd,MAAM,QAAQ,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,EAAE,mBAAmB,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,4BAA4B,EAAE,CAAC;IAClF,MAAM,OAAO,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAE3C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;IACvE,CAAC;IAED,MAAM,EAAE,sBAAsB,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;IAE3F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC"}
1
+ {"version":3,"file":"ensure-authorization-model.js","sourceRoot":"","sources":["../../src/model/ensure-authorization-model.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,MAAkB,EAClB,MAAc;IAEd,MAAM,QAAQ,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,EAAE,mBAAmB,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,4BAA4B,EAAE,CAAC;IAClF,MAAM,OAAO,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAE3C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;IACvE,CAAC;IAED,MAAM,EAAE,sBAAsB,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;IAE3F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"model-drift.d.ts","sourceRoot":"","sources":["../../src/model/model-drift.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,GAAG,SAAS,MAAM,EAAE,CAUrF"}
1
+ {"version":3,"file":"model-drift.d.ts","sourceRoot":"","sources":["../../src/model/model-drift.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAA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AAK,SAAS,EAAE,CAAC;QACzB,OAAO,CAAC,GAAG,IAAI,wCAAwC,IAAI,EAAE,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,6BAA6B,MAAM,eAAe,IAAI,EAAE,CAAC,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,5 @@
1
+ /** A schema OpenFGA cannot hold as it is: a relation name it refuses, or two names that become one. */
2
+ export declare class OpenFgaModelError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ //# sourceMappingURL=open-fga-model-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"open-fga-model-error.d.ts","sourceRoot":"","sources":["../../src/model/open-fga-model-error.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF"}
@@ -0,0 +1,8 @@
1
+ /** A schema OpenFGA cannot hold as it is: a relation name it refuses, or two names that become one. */
2
+ export class OpenFgaModelError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = 'OpenFgaModelError';
6
+ }
7
+ }
8
+ //# sourceMappingURL=open-fga-model-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"open-fga-model-error.js","sourceRoot":"","sources":["../../src/model/open-fga-model-error.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC1C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The name a relation of the schema bears in the model of OpenFGA. A relation keeps its name. A
3
+ * derived relation named after a permission id cannot, since OpenFGA refuses `:` in a relation
4
+ * name: `docs:document.edit` becomes `docs_document_edit`, the same way everywhere (the model,
5
+ * `Check`, `ListObjects`). No permission id holds `_`, so two ids never become one name.
6
+ */
7
+ export declare function relationNameOf(name: string): string;
8
+ //# sourceMappingURL=relation-name-of.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relation-name-of.d.ts","sourceRoot":"","sources":["../../src/model/relation-name-of.ts"],"names":[],"mappings":"AAMA;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAUnD"}
@@ -0,0 +1,18 @@
1
+ import { OpenFgaModelError } from './open-fga-model-error.js';
2
+ /** What OpenFGA admits as a relation name: 1 to 50 characters, none of them `:`, `#`, `@` or a space. */
3
+ const OPENFGA_RELATION_NAME = /^[^:#@\s]{1,50}$/;
4
+ const PERMISSION_ID_SEPARATORS = /[:.]/g;
5
+ /**
6
+ * The name a relation of the schema bears in the model of OpenFGA. A relation keeps its name. A
7
+ * derived relation named after a permission id cannot, since OpenFGA refuses `:` in a relation
8
+ * name: `docs:document.edit` becomes `docs_document_edit`, the same way everywhere (the model,
9
+ * `Check`, `ListObjects`). No permission id holds `_`, so two ids never become one name.
10
+ */
11
+ export function relationNameOf(name) {
12
+ const legal = name.replace(PERMISSION_ID_SEPARATORS, '_');
13
+ if (!OPENFGA_RELATION_NAME.test(legal)) {
14
+ throw new OpenFgaModelError(`"${name}" cannot be a relation of OpenFGA as "${legal}": a relation name has 1 to 50 characters, none of them ":", "#", "@" or a space.`);
15
+ }
16
+ return legal;
17
+ }
18
+ //# sourceMappingURL=relation-name-of.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relation-name-of.js","sourceRoot":"","sources":["../../src/model/relation-name-of.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE3D,yGAAyG;AACzG,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;IAE1D,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,iBAAiB,CACzB,IAAI,IAAI,yCAAyC,KAAK,mFAAmF,CAC1I,CAAC;IACJ,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -1,8 +1,8 @@
1
- import type { Rewrite } from '@ddd-ts-kit/auth/rebac';
1
+ import { type DerivedRelation } from '@ddd-ts-kit/auth/rebac';
2
2
  import type { OpenFgaUserset } from './open-fga-model.js';
3
3
  /**
4
- * A rewrite of the relationship schema in the words of OpenFGA: a name is a computed userset,
5
- * `from` a tuple to userset, `exclusion` a difference; union and intersection keep their name.
4
+ * A derived relation of the schema in the words of OpenFGA: a name is a computed userset, `via`
5
+ * a tuple to userset, `anyOf` a union, `allOf` an intersection, `butNot` a difference.
6
6
  */
7
- export declare function usersetOf(rewrite: Rewrite): OpenFgaUserset;
7
+ export declare function usersetOf(derived: DerivedRelation): OpenFgaUserset;
8
8
  //# sourceMappingURL=userset-of.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"userset-of.d.ts","sourceRoot":"","sources":["../../src/model/userset-of.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,cAAc,CAoB1D"}
1
+ {"version":3,"file":"userset-of.d.ts","sourceRoot":"","sources":["../../src/model/userset-of.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,eAAe,EAAY,MAAM,wBAAwB,CAAC;AAChF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,eAAe,GAAG,cAAc,CAMlE"}
@@ -1,25 +1,30 @@
1
+ import { waysOf } from '@ddd-ts-kit/auth/rebac';
2
+ import { relationNameOf } from './relation-name-of.js';
1
3
  /**
2
- * A rewrite of the relationship schema in the words of OpenFGA: a name is a computed userset,
3
- * `from` a tuple to userset, `exclusion` a difference; union and intersection keep their name.
4
+ * A derived relation of the schema in the words of OpenFGA: a name is a computed userset, `via`
5
+ * a tuple to userset, `anyOf` a union, `allOf` an intersection, `butNot` a difference.
4
6
  */
5
- export function usersetOf(rewrite) {
6
- if (typeof rewrite === 'string') {
7
- return { computedUserset: { relation: rewrite } };
8
- }
9
- switch (rewrite.kind) {
10
- case 'from':
11
- return {
12
- tupleToUserset: {
13
- tupleset: { relation: rewrite.relation },
14
- computedUserset: { relation: rewrite.permission },
15
- },
16
- };
17
- case 'exclusion':
18
- return { difference: { base: usersetOf(rewrite.base), subtract: usersetOf(rewrite.subtract) } };
19
- case 'union':
20
- return { union: { child: rewrite.children.map(usersetOf) } };
21
- case 'intersection':
22
- return { intersection: { child: rewrite.children.map(usersetOf) } };
7
+ export function usersetOf(derived) {
8
+ const { anyOf, allOf, butNot } = waysOf(derived);
9
+ const required = [...(anyOf.length === 0 ? [] : [oneOf(anyOf)]), ...allOf.map(usersetOfWay)];
10
+ const held = required.length === 1 && required[0] !== undefined ? required[0] : { intersection: { child: required } };
11
+ return butNot.length === 0 ? held : { difference: { base: held, subtract: oneOf(butNot) } };
12
+ }
13
+ function oneOf(ways) {
14
+ const [first, ...others] = ways;
15
+ return others.length === 0 && first !== undefined
16
+ ? usersetOfWay(first)
17
+ : { union: { child: ways.map(usersetOfWay) } };
18
+ }
19
+ function usersetOfWay(way) {
20
+ if (typeof way === 'string') {
21
+ return { computedUserset: { relation: relationNameOf(way) } };
23
22
  }
23
+ return {
24
+ tupleToUserset: {
25
+ tupleset: { relation: way.via },
26
+ computedUserset: { relation: relationNameOf(way.holds) },
27
+ },
28
+ };
24
29
  }
25
30
  //# sourceMappingURL=userset-of.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"userset-of.js","sourceRoot":"","sources":["../../src/model/userset-of.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,OAAgB;IACxC,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,EAAE,eAAe,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC;IACpD,CAAC;IAED,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACrB,KAAK,MAAM;YACT,OAAO;gBACL,cAAc,EAAE;oBACd,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE;oBACxC,eAAe,EAAE,EAAE,QAAQ,EAAE,OAAO,CAAC,UAAU,EAAE;iBAClD;aACF,CAAC;QACJ,KAAK,WAAW;YACd,OAAO,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QAClG,KAAK,OAAO;YACV,OAAO,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,EAAE,CAAC;QAC/D,KAAK,cAAc;YACjB,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,EAAE,CAAC;IACxE,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"userset-of.js","sourceRoot":"","sources":["../../src/model/userset-of.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAkC,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,OAAwB;IAChD,MAAM,EAAE,KAAK,EAAE,KA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c,EAAE;YACd,QAAQ,EAAE,EAAE,QAAQ,EAAE,GAAG,CAAC,GAAG,EAAE;YAC/B,eAAe,EAAE,EAAE,QAAQ,EAAE,cAAc,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;SACzD;KACF,CAAC;AACJ,CAAC"}
package/dist/sdk.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,YAAY,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC"}
1
+ {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,YAAY,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC"}
package/dist/sdk.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC"}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC"}
@@ -2,10 +2,12 @@ import { type RelationTuple, type RelationTupleStore, type Schema } from '@ddd-t
2
2
  import type { OpenFgaApi } from '../client/open-fga-api.js';
3
3
  /**
4
4
  * The relation tuples of `@ddd-ts-kit/auth` in an OpenFGA store, held to the same contract as the
5
- * tuple store of PostgreSQL. Writing a tuple twice and deleting one that is not there change
6
- * nothing (the conflict options of OpenFGA 1.10 and later). A write is a call to a service: it
7
- * does not join the transaction of the unit of work, so a tuple written with an aggregate goes
8
- * through the outbox or is retried, and must be idempotent, as it is here.
5
+ * tuple store of PostgreSQL. A tuple of the kit names its subject alone (`group:eng`) and the
6
+ * schema says what it stands for; OpenFGA wants it in the tuple (`group:eng#member`), so the
7
+ * userset is added on write and removed on read. Writing a tuple twice and deleting one that is
8
+ * not there change nothing (the conflict options of OpenFGA 1.10 and later). A write is a call to
9
+ * a service: it does not join the transaction of the unit of work, so a tuple written with an
10
+ * aggregate goes through the outbox or is retried, and must be idempotent, as it is here.
9
11
  */
10
12
  export declare class OpenFgaRelationTupleStore implements RelationTupleStore {
11
13
  private readonly client;
@@ -15,10 +17,12 @@ export declare class OpenFgaRelationTupleStore implements RelationTupleStore {
15
17
  delete(tuples: readonly RelationTuple[]): Promise<void>;
16
18
  readByObject(object: string, relation: string): Promise<readonly RelationTuple[]>;
17
19
  /**
18
- * OpenFGA reads by subject only within one object type: one read per relation of the schema
19
- * that accepts the kind of the subject (`user`, or the userset `group#member`).
20
+ * OpenFGA reads by user only within one object type: one read per relation of the schema
21
+ * that accepts the type of the subject, as itself or as what it stands for there.
20
22
  */
21
23
  readBySubject(subject: string): Promise<readonly RelationTuple[]>;
24
+ /** The tuple as OpenFGA stores it: the userset the schema gives the subject in this relation, if any. */
25
+ private keyOf;
22
26
  private relationsAccepting;
23
27
  private readAll;
24
28
  }
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-relation-tuple-store.d.ts","sourceRoot":"","sources":["../../src/store/open-fga-relation-tuple-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,MAAM,EACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,2BAA2B,CAAC;AAQ7E;;;;;;GAMG;AACH,qBAAa,yBAA0B,YAAW,kBAAkB;IAEhE,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAFzB,YACmB,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,MAAM,EAC7B;IAEE,KAAK,CAAC,MAAM,EAAE,SAAS,aAAa,EAAE,G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,KAAK;IAMb,OAAO,CAAC,kBAAkB;YAeZ,OAAO;CAgBtB"}
@@ -1,14 +1,16 @@
1
- import { parseSubject, tupleKey, } from '@ddd-ts-kit/auth/rebac';
1
+ import { parseObject, tupleKey, } from '@ddd-ts-kit/auth/rebac';
2
2
  /** OpenFGA answers a page of tuples at a time; this many, at most, per read. */
3
3
  const PAGE_SIZE = 100;
4
4
  /** How many tuples one write sends: the limit of a write of the OpenFGA API. */
5
5
  const CHUNK = 100;
6
6
  /**
7
7
  * The relation tuples of `@ddd-ts-kit/auth` in an OpenFGA store, held to the same contract as the
8
- * tuple store of PostgreSQL. Writing a tuple twice and deleting one that is not there change
9
- * nothing (the conflict options of OpenFGA 1.10 and later). A write is a call to a service: it
10
- * does not join the transaction of the unit of work, so a tuple written with an aggregate goes
11
- * through the outbox or is retried, and must be idempotent, as it is here.
8
+ * tuple store of PostgreSQL. A tuple of the kit names its subject alone (`group:eng`) and the
9
+ * schema says what it stands for; OpenFGA wants it in the tuple (`group:eng#member`), so the
10
+ * userset is added on write and removed on read. Writing a tuple twice and deleting one that is
11
+ * not there change nothing (the conflict options of OpenFGA 1.10 and later). A write is a call to
12
+ * a service: it does not join the transaction of the unit of work, so a tuple written with an
13
+ * aggregate goes through the outbox or is retried, and must be idempotent, as it is here.
12
14
  */
13
15
  export class OpenFgaRelationTupleStore {
14
16
  client;
@@ -18,12 +20,12 @@ export class OpenFgaRelationTupleStore {
18
20
  this.schema = schema;
19
21
  }
20
22
  async write(tuples) {
21
- for (const chunk of chunksOf(distinct(tuples))) {
23
+ for (const chunk of chunksOf(distinct(tuples.map((tuple) => this.keyOf(tuple))))) {
22
24
  await this.client.write({ writes: chunk }, { conflict: { onDuplicateWrites: 'ignore' } });
23
25
  }
24
26
  }
25
27
  async delete(tuples) {
26
- for (const chunk of chunksOf(distinct(tuples))) {
28
+ for (const chunk of chunksOf(distinct(tuples.map((tuple) => this.keyOf(tuple))))) {
27
29
  await this.client.write({ deletes: chunk }, { conflict: { onMissingDeletes: 'ignore' } });
28
30
  }
29
31
  }
@@ -31,19 +33,27 @@ export class OpenFgaRelationTupleStore {
31
33
  return this.readAll({ object, relation });
32
34
  }
33
35
  /**
34
- * OpenFGA reads by subject only within one object type: one read per relation of the schema
35
- * that accepts the kind of the subject (`user`, or the userset `group#member`).
36
+ * OpenFGA reads by user only within one object type: one read per relation of the schema
37
+ * that accepts the type of the subject, as itself or as what it stands for there.
36
38
  */
37
39
  async readBySubject(subject) {
38
- const read = this.relationsAccepting(subject).map(([type, relation]) => this.readAll({ user: subject, relation, object: `${type}:` }));
40
+ const read = this.relationsAccepting(subject).map(({ type, relation, user }) => this.readAll({ user, relation, object: `${type}:` }));
39
41
  return (await Promise.all(read)).flat();
40
42
  }
43
+ /** The tuple as OpenFGA stores it: the userset the schema gives the subject in this relation, if any. */
44
+ keyOf({ object, relation, subject }) {
45
+ const standsFor = this.schema.standsFor(parseObject(object).type, relation, parseObject(subject).type);
46
+ return { object, relation, user: standsFor === undefined ? subject : `${subject}#${standsFor}` };
47
+ }
41
48
  relationsAccepting(subject) {
42
- const { type, relation } = parseSubject(subject);
43
- const kind = relation === undefined ? type : `${type}#${relation}`;
44
- return this.schema.types().flatMap((object) => Object.entries(this.schema.relations(object))
45
- .filter(([, subjects]) => subjects.includes(kind))
46
- .map(([name]) => [object, name]));
49
+ const subjectType = parseObject(subject).type;
50
+ return this.schema.types().flatMap((type) => Object.keys(this.schema.relations(type)).flatMap((relation) => {
51
+ const standsFor = this.schema.standsFor(type, relation, subjectType);
52
+ const accepted = this.schema.acceptedKindOf(type, relation, subjectType) !== undefined;
53
+ return accepted
54
+ ? [{ type, relation, user: standsFor === undefined ? subject : `${subject}#${standsFor}` }]
55
+ : [];
56
+ }));
47
57
  }
48
58
  async readAll(filter) {
49
59
  const tuples = [];
@@ -53,19 +63,20 @@ export class OpenFgaRelationTupleStore {
53
63
  pageSize: PAGE_SIZE,
54
64
  ...(continuationToken === undefined ? {} : { continuationToken }),
55
65
  });
56
- tuples.push(...page.tuples.map(({ key }) => ({ object: key.object, relation: key.relation, subject: key.user })));
66
+ tuples.push(...page.tuples.map(({ key }) => tupleOf(key)));
57
67
  continuationToken = page.continuation_token === '' ? undefined : page.continuation_token;
58
68
  } while (continuationToken !== undefined);
59
69
  return tuples;
60
70
  }
61
71
  }
72
+ /** The tuple as the kit reads it: the subject alone, the userset OpenFGA holds left to the schema. */
73
+ function tupleOf({ object, relation, user }) {
74
+ return { object, relation, subject: user.split('#')[0] ?? user };
75
+ }
62
76
  /** Each tuple once: OpenFGA refuses a request that names one tuple twice, whatever its conflict options. */
63
- function distinct(tuples) {
64
- const keys = new Map(tuples.map(({ object, relation, subject }) => [
65
- tupleKey({ object, relation, subject }),
66
- { object, relation, user: subject },
67
- ]));
68
- return [...keys.values()];
77
+ function distinct(keys) {
78
+ const byKey = new Map(keys.map((key) => [tupleKey({ object: key.object, relation: key.relation, subject: key.user }), key]));
79
+ return [...byKey.values()];
69
80
  }
70
81
  function chunksOf(keys) {
71
82
  const chunks = [];
@@ -1 +1 @@
1
- {"version":3,"file":"open-fga-relation-tuple-store.js","sourceRoot":"","sources":["../../src/store/open-fga-relation-tuple-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,QAAQ,GAIT,MAAM,wBAAwB,CAAC;AAGhC,gFAAgF;AAChF,MAAM,SAAS,GAAG,GAAG,CAAC;AAEtB,gFAAgF;AAChF,MAAM,KAAK,GAAG,GAAG,CAAC;AAElB;;;;;;GAMG;AACH,MAAM,OAAO,yBAAyB;IAEjB,MAAM;IACN,MAAM;IAFzB,YACmB,MAAkB,EAClB,MAAc;sBADd,MAAM;sBACN,MAAM;IACtB,CAAC;IAEJ,KAAK,CAAC,KAAK,CAAC,MAAgC;QAC1C,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YAC/C,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,MAA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AG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,QAAQ,CAAC,IAAgC;IAChD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,KAAK,EAAE,CAAC;QACxD,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ddd-ts-kit/openfga",
3
- "version": "0.84.1",
3
+ "version": "0.86.0",
4
4
  "description": "The relation tuple store and the authorizer of @ddd-ts-kit/auth on OpenFGA, with the authorization model generated from the relationship schema.",
5
5
  "keywords": [
6
6
  "ddd",
@@ -42,8 +42,8 @@
42
42
  "dist"
43
43
  ],
44
44
  "dependencies": {
45
- "@ddd-ts-kit/auth": "0.84.1",
46
- "@ddd-ts-kit/kernel": "0.84.1"
45
+ "@ddd-ts-kit/auth": "0.86.0",
46
+ "@ddd-ts-kit/kernel": "0.86.0"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "@openfga/sdk": "^0.9.7"
@@ -54,7 +54,7 @@
54
54
  }
55
55
  },
56
56
  "devDependencies": {
57
- "@ddd-ts-kit/testing": "0.84.1",
57
+ "@ddd-ts-kit/testing": "0.86.0",
58
58
  "@openfga/sdk": "0.9.7"
59
59
  }
60
60
  }