JavaScript and Node.js SDK for OpenFGA
This is an autogenerated JavaScript SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition, and includes TS typings.
Table of Contents
About
OpenFGA is an open source Fine-Grained Authorization solution inspired by Google's Zanzibar paper. It was created by the FGA team at Auth0 based on Auth0 Fine-Grained Authorization (FGA), available under a permissive license (Apache-2) and welcomes community contributions.
OpenFGA is designed to make it easy for application builders to model their permission layer, and to add and integrate fine-grained authorization into their applications. OpenFGA’s design is optimized for reliability and low latency at a high scale.
Resources
Installation
Using npm:
npm install @openfga/sdk
Using yarn:
yarn add @openfga/sdk
Getting Started
Initializing the API Client
Learn how to initialize your SDK
We strongly recommend you initialize the OpenFgaClient
only once and then re-use it throughout your app, otherwise you will incur the cost of having to re-initialize multiple times or at every request, the cost of reduced connection pooling and re-use, and would be particularly costly in the client credentials flow, as that flow will be preformed on every request.
The OpenFgaClient
will by default retry API requests up to 15 times on 429 and 5xx errors.
No Credentials
const { OpenFgaClient } = require('@openfga/sdk');
const fgaClient = new OpenFgaClient({
apiUrl: process.env.FGA_API_URL,
storeId: process.env.FGA_STORE_ID,
authorizationModelId: process.env.FGA_MODEL_ID,
});
API Token
const { OpenFgaClient } = require('@openfga/sdk');
const fgaClient = new OpenFgaClient({
apiUrl: process.env.FGA_API_URL,
storeId: process.env.FGA_STORE_ID,
authorizationModelId: process.env.FGA_MODEL_ID,
credentials: {
method: CredentialsMethod.ApiToken,
config: {
token: process.env.FGA_API_TOKEN,
}
}
});
Client Credentials
const { OpenFgaClient } = require('@openfga/sdk');
const fgaClient = new OpenFgaClient({
apiUrl: process.env.FGA_API_URL,
storeId: process.env.FGA_STORE_ID,
authorizationModelId: process.env.FGA_MODEL_ID,
credentials: {
method: CredentialsMethod.ClientCredentials,
config: {
apiTokenIssuer: process.env.FGA_API_TOKEN_ISSUER,
apiAudience: process.env.FGA_API_AUDIENCE,
clientId: process.env.FGA_CLIENT_ID,
clientSecret: process.env.FGA_CLIENT_SECRET,
}
}
});
Get your Store ID
You need your store id to call the OpenFGA API (unless it is to call the CreateStore or ListStores methods).
If your server is configured with authentication enabled, you also need to have your credentials ready.
Calling the API
Note regarding casing in the OpenFgaClient:
All input parameters are in camelCase
, all response parameters will match the API and are in snake_case
.
Note: The Client interface might see several changes over the next few months as we get more feedback before it stabilizes.
Stores
List Stores
Get a paginated list of stores.
API Documentation
const options = { pageSize: 10, continuationToken: "..." };
const { stores } = await fgaClient.listStores(options);
Create Store
Initialize a store.
API Documentation
const { id: storeId } = await fgaClient.createStore({
name: "FGA Demo Store",
});
Get Store
Get information about the current store.
API Documentation
const store = await fgaClient.getStore();
Delete Store
Delete a store.
API Documentation
await fgaClient.deleteStore();
Authorization Models
Read Authorization Models
Read all authorization models in the store.
API Documentation
Requires a client initialized with a storeId
const options = { pageSize: 10, continuationToken: "..." };
const { authorization_models: authorizationModels } = await fgaClient.readAuthorizationModels(options);
Write Authorization Model
Create a new authorization model.
API Documentation
Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.
Learn more about the OpenFGA configuration language.
You can use the OpenFGA Syntax Transformer to convert between the friendly DSL and the JSON authorization model.
const { authorization_model_id: id } = await fgaClient.writeAuthorizationModel({
schema_version: "1.1",
type_definitions: [{
type: "user",
}, {
type: "document",
relations: {
"writer": { "this": {} },
"viewer": {
"union": {
"child": [
{ "this": {} },
{ "computedUserset": {
"object": "",
"relation": "writer" }
}
]
}
}
} }],
});
Read a Single Authorization Model
Read a particular authorization model.
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
const { authorization_model: authorizationModel } = await fgaClient.readAuthorizationModel(options);
Read the Latest Authorization Model
Reads the latest authorization model (note: this ignores the model id in configuration).
API Documentation
const { authorization_model: authorizationModel } = await fgaClient.readLatestAuthorizationModel();
Relationship Tuples
Read Relationship Tuple Changes (Watch)
Reads the list of historical relationship tuple writes and deletes.
API Documentation
const type = 'document';
const options = {
pageSize: 25,
continuationToken: 'eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==',
};
const response = await fgaClient.readChanges({ type }, options);
Read Relationship Tuples
Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model.
API Documentation
const body = {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:roadmap",
};
const body = {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
object: "document:roadmap",
};
const body = {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:",
};
const body = {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
object: "document:",
};
const body = {
object: "document:roadmap",
};
const body = {};
const { tuples } = await fgaClient.read(body);
Write (Create and Delete) Relationship Tuples
Create and/or delete relationship tuples to update the system state.
API Documentation
Transaction mode (default)
By default, write runs in a transaction mode where any invalid operation (deleting a non-existing tuple, creating an existing tuple, one of the tuples was invalid) or a server error will fail the entire operation.
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
await fgaClient.write({
writes: [{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "viewer", object: "document:roadmap" }],
deletes: [{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "editor", object: "document:roadmap" }],
}, options);
await fgaClient.writeTuples([{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "viewer", object: "document:roadmap" }], options);
await fgaClient.deleteTuples([{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "editor", object: "document:roadmap" }], options);
Non-transaction mode
The SDK will split the writes into separate requests and send them in parallel chunks (default = 1 item per chunk, each chunk is a transaction).
// if you'd like to disable the transaction mode for writes (requests will be sent in parallel writes)
options.transaction = {
disable: true,
maxPerChunk: 1, // defaults to 1 - each chunk is a transaction (even in non-transaction mode)
maxParallelRequests: 10, // max requests to issue in parallel
};
const response = await fgaClient.write({
writes: [{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "viewer", object: "document:roadmap" }],
deletes: [{ user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "editor", object: "document:roadmap" }],
}, options);
/*
response = {
writes: [{ tuple_key: { user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "viewer", object: "document:roadmap", status: "success" } }],
deletes: [{ tuple_key: { user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", relation: "editor", object: "document:roadmap", status: "failure", err: <FgaError ...> } }],
};
*/
Relationship Queries
Check
Check if a user has a particular relation with an object.
API Documentation
const options = {
authorizationModelId: "01GXSA8YR785C4FYS3C0RTG7B1",
};
const result = await fgaClient.check({
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:roadmap",
}, options);
Batch Check
Run a set of checks. Batch Check will return allowed: false
if it encounters an error, and will return the error in the body.
If 429s or 5xxs are encountered, the underlying check will retry up to 15 times before giving up.
const options = {
authorizationModelId: "01GXSA8YR785C4FYS3C0RTG7B1",
}
const { responses } = await fgaClient.batchCheck([{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:budget",
}, {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "member",
object: "document:budget",
}, {
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:roadmap",
contextualTuples: [{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "writer",
object: "document:roadmap"
}],
}], options);
Expand
Expands the relationships in userset tree format.
API Documentation
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
const { tree } = await fgaClient.expand({
relation: "viewer",
object: "document:roadmap",
}, options);
List Objects
List the objects of a particular type that the user has a certain relation to.
API Documentation
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
const response = await fgaClient.listObjects({
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
type: "document",
contextualTuples: [{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "writer",
object: "document:budget"
}],
}, options);
List Relations
List the relations a user has with an object. This wraps around BatchCheck to allow checking multiple relationships at once.
Note: Any error encountered when checking any relation will be treated as allowed: false
;
const options = {};
options.authorization_model_id = "1uHxCSuTP0VKPYSnkq1pbb1jeZw";
const response = await fgaClient.listRelations({
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
object: "document:roadmap",
relations: ["can_view", "can_edit", "can_delete"],
contextualTuples: [{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "writer",
object: "document:roadmap"
}],
}, options);
List Users
List the users who have a certain relation to a particular type.
API Documentation
const options = {};
options.authorization_model_id = "1uHxCSuTP0VKPYSnkq1pbb1jeZw";
const userFilters = [{type: "user"}];
const response = await fgaClient.listUsers({
object: {
type: "document",
id: "roadmap"
},
relation: "can_read",
user_filters: userFilters,
context: {
"view_count": 100
},
contextualTuples:
[{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "editor",
object: "folder:product"
}, {
user: "folder:product",
relation: "parent",
object: "document:roadmap"
}]
}, options);
Assertions
Read Assertions
Read assertions for a particular authorization model.
API Documentation
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
const response = await fgaClient.readAssertions(options);
Write Assertions
Update the assertions for a particular authorization model.
API Documentation
const options = {};
options.authorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1";
const response = await fgaClient.writeAssertions([{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "viewer",
object: "document:roadmap",
expectation: true,
}], options);
Retries
If a network request fails with a 429 or 5xx error from the server, the SDK will automatically retry the request up to 15 times with a minimum wait time of 100 milliseconds between each attempt.
To customize this behavior, create an object with maxRetry
and minWaitInMs
properties. maxRetry
determines the maximum number of retries (up to 15), while minWaitInMs
sets the minimum wait time between retries in milliseconds.
Apply your custom retry values by setting to retryParams
on the to the configuration object passed to the OpenFgaClient
call.
const { OpenFgaClient } = require('@openfga/sdk');
const fgaClient = new OpenFgaClient({
apiUrl: process.env.FGA_API_URL,
storeId: process.env.FGA_STORE_ID,
authorizationModelId: process.env.FGA_MODEL_ID,
retryParams: {
maxRetry: 3,
minWaitInMs: 250
}
});
API Endpoints
Method | HTTP request | Description |
---|
ListStores | GET /stores | List all stores |
CreateStore | POST /stores | Create a store |
GetStore | GET /stores/{store_id} | Get a store |
DeleteStore | DELETE /stores/{store_id} | Delete a store |
ReadAuthorizationModels | GET /stores/{store_id}/authorization-models | Return all the authorization models for a particular store |
WriteAuthorizationModel | POST /stores/{store_id}/authorization-models | Create a new authorization model |
ReadAuthorizationModel | GET /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model |
ReadChanges | GET /stores/{store_id}/changes | Return a list of all the tuple changes |
Read | POST /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules |
Write | POST /stores/{store_id}/write | Add or delete tuples from the store |
Check | POST /stores/{store_id}/check | Check whether a user is authorized to access an object |
Expand | POST /stores/{store_id}/expand | Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship |
ListObjects | POST /stores/{store_id}/list-objects | [EXPERIMENTAL] Get all objects of the given type that the user has a relation with |
ReadAssertions | GET /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID |
WriteAssertions | PUT /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID |
Models
Models
Contributing
Issues
If you have found a bug or if you have a feature request, please report them on the sdk-generator repo issues section. Please do not report security vulnerabilities on the public GitHub issue tracker.
Pull Requests
All changes made to this repo will be overwritten on the next generation, so we kindly ask that you send all pull requests related to the SDKs to the sdk-generator repo instead.
Author
OpenFGA
License
This project is licensed under the Apache-2.0 license. See the LICENSE file for more info.
The code in this repo was auto generated by OpenAPI Generator from a template based on the typescript-axios template and go template, licensed under the Apache License 2.0.