# Create a new user identity (/api/0.22.2/auth/createUser)

`POST /api/v1/auth/users`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "email": {
      "examples": [
        "user@example.com"
      ],
      "format": "email",
      "type": "string"
    },
    "name": {
      "additionalProperties": false,
      "properties": {
        "first": {
          "examples": [
            "John"
          ],
          "type": "string"
        },
        "last": {
          "examples": [
            "Doe"
          ],
          "type": "string"
        }
      },
      "required": [
        "first",
        "last"
      ],
      "type": "object"
    },
    "password": {
      "examples": [
        "securepassword123"
      ],
      "maxLength": 72,
      "minLength": 8,
      "type": "string"
    }
  },
  "required": [
    "email",
    "password",
    "name"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "AdditionalProperties": {
      "additionalProperties": {},
      "type": "object"
    },
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "credentials": {
      "additionalProperties": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "config": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "identifiers": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "type": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "version": {
            "format": "int64",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "type": "object"
    },
    "id": {
      "type": "string"
    },
    "metadata_admin": {},
    "metadata_public": {},
    "organization_id": {
      "additionalProperties": false,
      "type": "object"
    },
    "recovery_addresses": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "via": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "value",
          "via"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "schema_id": {
      "type": "string"
    },
    "schema_url": {
      "type": "string"
    },
    "state": {
      "type": "string"
    },
    "state_changed_at": {
      "format": "date-time",
      "type": "string"
    },
    "traits": {},
    "updated_at": {
      "format": "date-time",
      "type": "string"
    },
    "verifiable_addresses": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "verified": {
            "type": "boolean"
          },
          "verified_at": {
            "format": "date-time",
            "type": "string"
          },
          "via": {
            "type": "string"
          }
        },
        "required": [
          "status",
          "value",
          "verified",
          "via"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "id",
    "schema_id",
    "schema_url",
    "traits"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get the active tenant for the authenticated user (/api/0.22.2/auth/getActiveTenant)

`GET /api/v1/auth/active-tenant`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "tenant": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "enterprise_id": {
          "type": [
            "string",
            "null"
          ]
        },
        "enterprise_template": {
          "type": [
            "string",
            "null"
          ]
        },
        "id": {
          "type": "string"
        },
        "name": {
          "type": "string"
        },
        "stripe_customer_id": {
          "type": [
            "string",
            "null"
          ]
        },
        "type": {
          "type": "string"
        },
        "updated_at": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "id",
        "name",
        "stripe_customer_id",
        "enterprise_template",
        "enterprise_id",
        "type",
        "created_at",
        "updated_at"
      ],
      "type": "object"
    }
  },
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get current identity (/api/0.22.2/auth/getIdentity)

`GET /api/v1/auth/identity`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "AdditionalProperties": {
      "additionalProperties": {},
      "type": "object"
    },
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "credentials": {
      "additionalProperties": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "config": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "identifiers": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "type": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "version": {
            "format": "int64",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "type": "object"
    },
    "id": {
      "type": "string"
    },
    "metadata_admin": {},
    "metadata_public": {},
    "organization_id": {
      "additionalProperties": false,
      "type": "object"
    },
    "recovery_addresses": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "via": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "value",
          "via"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "schema_id": {
      "type": "string"
    },
    "schema_url": {
      "type": "string"
    },
    "state": {
      "type": "string"
    },
    "state_changed_at": {
      "format": "date-time",
      "type": "string"
    },
    "traits": {},
    "updated_at": {
      "format": "date-time",
      "type": "string"
    },
    "verifiable_addresses": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "AdditionalProperties": {
            "additionalProperties": {},
            "type": "object"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "verified": {
            "type": "boolean"
          },
          "verified_at": {
            "format": "date-time",
            "type": "string"
          },
          "via": {
            "type": "string"
          }
        },
        "required": [
          "status",
          "value",
          "verified",
          "via"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "id",
    "schema_id",
    "schema_url",
    "traits"
  ],
  "type": "object"
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get current session (/api/0.22.2/auth/getSession)

`GET /api/v1/auth/session`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "identity": {
      "additionalProperties": false,
      "properties": {
        "AdditionalProperties": {
          "additionalProperties": {},
          "type": "object"
        },
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "credentials": {
          "additionalProperties": {
            "additionalProperties": false,
            "properties": {
              "AdditionalProperties": {
                "additionalProperties": {},
                "type": "object"
              },
              "config": {
                "additionalProperties": {},
                "type": "object"
              },
              "created_at": {
                "format": "date-time",
                "type": "string"
              },
              "identifiers": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "type": {
                "type": "string"
              },
              "updated_at": {
                "format": "date-time",
                "type": "string"
              },
              "version": {
                "format": "int64",
                "type": "integer"
              }
            },
            "type": "object"
          },
          "type": "object"
        },
        "id": {
          "type": "string"
        },
        "metadata_admin": {},
        "metadata_public": {},
        "organization_id": {
          "additionalProperties": false,
          "type": "object"
        },
        "recovery_addresses": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "AdditionalProperties": {
                "additionalProperties": {},
                "type": "object"
              },
              "created_at": {
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "updated_at": {
                "format": "date-time",
                "type": "string"
              },
              "value": {
                "type": "string"
              },
              "via": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "value",
              "via"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "schema_id": {
          "type": "string"
        },
        "schema_url": {
          "type": "string"
        },
        "state": {
          "type": "string"
        },
        "state_changed_at": {
          "format": "date-time",
          "type": "string"
        },
        "traits": {},
        "updated_at": {
          "format": "date-time",
          "type": "string"
        },
        "verifiable_addresses": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "AdditionalProperties": {
                "additionalProperties": {},
                "type": "object"
              },
              "created_at": {
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "status": {
                "type": "string"
              },
              "updated_at": {
                "format": "date-time",
                "type": "string"
              },
              "value": {
                "type": "string"
              },
              "verified": {
                "type": "boolean"
              },
              "verified_at": {
                "format": "date-time",
                "type": "string"
              },
              "via": {
                "type": "string"
              }
            },
            "required": [
              "status",
              "value",
              "verified",
              "via"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        }
      },
      "required": [
        "id",
        "schema_id",
        "schema_url",
        "traits"
      ],
      "type": "object"
    },
    "session": {
      "additionalProperties": false,
      "properties": {
        "AdditionalProperties": {
          "additionalProperties": {},
          "type": "object"
        },
        "active": {
          "type": "boolean"
        },
        "authenticated_at": {
          "format": "date-time",
          "type": "string"
        },
        "authentication_methods": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "AdditionalProperties": {
                "additionalProperties": {},
                "type": "object"
              },
              "aal": {
                "type": "string"
              },
              "completed_at": {
                "format": "date-time",
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "organization": {
                "type": "string"
              },
              "provider": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "authenticator_assurance_level": {
          "type": "string"
        },
        "devices": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "AdditionalProperties": {
                "additionalProperties": {},
                "type": "object"
              },
              "id": {
                "type": "string"
              },
              "ip_address": {
                "type": "string"
              },
              "location": {
                "type": "string"
              },
              "user_agent": {
                "type": "string"
              }
            },
            "required": [
              "id"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "expires_at": {
          "format": "date-time",
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "identity": {
          "additionalProperties": false,
          "properties": {
            "AdditionalProperties": {
              "additionalProperties": {},
              "type": "object"
            },
            "created_at": {
              "format": "date-time",
              "type": "string"
            },
            "credentials": {
              "additionalProperties": {
                "$ref": "#/components/schemas/IdentityCredentials"
              },
              "type": "object"
            },
            "id": {
              "type": "string"
            },
            "metadata_admin": {},
            "metadata_public": {},
            "organization_id": {
              "$ref": "#/components/schemas/NullableString"
            },
            "recovery_addresses": {
              "items": {
                "$ref": "#/components/schemas/RecoveryIdentityAddress"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "schema_id": {
              "type": "string"
            },
            "schema_url": {
              "type": "string"
            },
            "state": {
              "type": "string"
            },
            "state_changed_at": {
              "format": "date-time",
              "type": "string"
            },
            "traits": {},
            "updated_at": {
              "format": "date-time",
              "type": "string"
            },
            "verifiable_addresses": {
              "items": {
                "$ref": "#/components/schemas/VerifiableIdentityAddress"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "required": [
            "id",
            "schema_id",
            "schema_url",
            "traits"
          ],
          "type": "object"
        },
        "issued_at": {
          "format": "date-time",
          "type": "string"
        },
        "tokenized": {
          "type": "string"
        }
      },
      "required": [
        "id"
      ],
      "type": "object"
    },
    "tenant": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "enterprise_id": {
          "type": [
            "string",
            "null"
          ]
        },
        "enterprise_template": {
          "type": [
            "string",
            "null"
          ]
        },
        "id": {
          "type": "string"
        },
        "name": {
          "type": "string"
        },
        "stripe_customer_id": {
          "type": [
            "string",
            "null"
          ]
        },
        "type": {
          "type": "string"
        },
        "updated_at": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "id",
        "name",
        "stripe_customer_id",
        "enterprise_template",
        "enterprise_id",
        "type",
        "created_at",
        "updated_at"
      ],
      "type": "object"
    }
  },
  "required": [
    "session",
    "identity"
  ],
  "type": "object"
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Auth (/api/0.22.2/auth)

## Auth endpoints [#auth-endpoints]

- [Create a new user identity](./createUser)
- [Get authenticated user identity](./whoAmI)
- [Get current identity](./getIdentity)
- [Get current session](./getSession)
- [Get the active tenant for the authenticated user](./getActiveTenant)
- [List tenants the authenticated user belongs to](./listTenants)
- [Logout user](./logout)

# List tenants the authenticated user belongs to (/api/0.22.2/auth/listTenants)

`GET /api/v1/auth/tenants`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "tenants": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "is_active": {
            "examples": [
              true
            ],
            "type": "boolean"
          },
          "tenant": {
            "additionalProperties": false,
            "properties": {
              "created_at": {
                "format": "date-time",
                "type": "string"
              },
              "enterprise_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "enterprise_template": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "stripe_customer_id": {
                "type": [
                  "string",
                  "null"
                ]
              },
              "type": {
                "type": "string"
              },
              "updated_at": {
                "format": "date-time",
                "type": "string"
              }
            },
            "required": [
              "id",
              "name",
              "stripe_customer_id",
              "enterprise_template",
              "enterprise_id",
              "type",
              "created_at",
              "updated_at"
            ],
            "type": "object"
          }
        },
        "required": [
          "is_active",
          "tenant"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "tenants"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Logout user (/api/0.22.2/auth/logout)

`POST /api/v1/auth/logout`

## Parameters

- `Cookie` (header): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "logout_token": {
      "examples": [
        "tok_test_abc123xyz"
      ],
      "type": "string"
    },
    "logout_url": {
      "examples": [
        "http://auth.test.example.com/self-service/logout?token=tok_test_abc123xyz"
      ],
      "type": "string"
    }
  },
  "required": [
    "logout_url",
    "logout_token"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get authenticated user identity (/api/0.22.2/auth/whoAmI)

`GET /api/v1/auth/whoami`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "authenticated": {
      "examples": [
        true
      ],
      "type": "boolean"
    },
    "user_id": {
      "examples": [
        "550e8400-e29b-41d4-a716-446655440000"
      ],
      "type": "string"
    }
  },
  "required": [
    "authenticated",
    "user_id"
  ],
  "type": "object"
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Archive all Stripe config (/api/0.22.2/configuration/archiveAllStripeConfig)

`POST /api/v1/stripe/admin/config/archive-all`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "force": {
      "type": "boolean"
    }
  },
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "archive_errors": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "archived_items": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "message": {
      "type": "string"
    },
    "total_archived": {
      "format": "int64",
      "type": "integer"
    },
    "total_errors": {
      "format": "int64",
      "type": "integer"
    },
    "warning": {
      "type": "string"
    }
  },
  "required": [
    "message",
    "archived_items",
    "archive_errors",
    "total_archived",
    "total_errors"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create or update email template (/api/0.22.2/configuration/createOrUpdateEmailTemplate)

`POST /api/v1/email/templates`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "html_body": {
      "examples": [
        "<h1>Welcome!</h1>"
      ],
      "type": "string"
    },
    "subject": {
      "examples": [
        "Welcome to Test Platform"
      ],
      "type": "string"
    },
    "type": {
      "examples": [
        "test_welcome"
      ],
      "type": "string"
    }
  },
  "required": [
    "type",
    "subject",
    "html_body"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "template": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "html_body": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "subject": {
          "type": "string"
        },
        "tenant_id": {
          "type": [
            "string",
            "null"
          ]
        },
        "type": {
          "type": "string"
        },
        "updated_at": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "id",
        "type",
        "subject",
        "html_body",
        "created_at",
        "updated_at",
        "tenant_id"
      ],
      "type": "object"
    }
  },
  "required": [
    "message",
    "template"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create or update a system email template (/api/0.22.2/configuration/createOrUpdateSystemEmailTemplate)

`POST /api/v1/email/system-templates`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "html_body": {
      "examples": [
        "<h1>Verify your email</h1>"
      ],
      "type": "string"
    },
    "name": {
      "examples": [
        "verification"
      ],
      "type": "string"
    },
    "plaintext_body": {
      "examples": [
        "Verify your email"
      ],
      "type": "string"
    },
    "subject": {
      "examples": [
        "Verify your email"
      ],
      "type": "string"
    }
  },
  "required": [
    "name",
    "subject",
    "html_body"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "template": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "html_body": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "name": {
          "type": "string"
        },
        "plaintext_body": {
          "type": "string"
        },
        "subject": {
          "type": "string"
        },
        "updated_at": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "id",
        "name",
        "subject",
        "html_body",
        "plaintext_body",
        "created_at",
        "updated_at"
      ],
      "type": "object"
    }
  },
  "required": [
    "message",
    "template"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Delete email template (/api/0.22.2/configuration/deleteEmailTemplate)

`DELETE /api/v1/email/templates/{type}`

## Parameters

- `type` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Delete a system email template (/api/0.22.2/configuration/deleteSystemEmailTemplate)

`DELETE /api/v1/email/system-templates/{name}`

## Parameters

- `name` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Deploy Keto namespace configurations (/api/0.22.2/configuration/deployPermissionNamespaces)

`POST /api/v1/permissions/namespaces`

## Request body

Content type: `multipart/form-data`

```json
{
  "properties": {
    "namespaces": {
      "contentEncoding": "binary",
      "contentMediaType": "application/octet-stream",
      "format": "binary",
      "type": "string"
    }
  },
  "required": [
    "namespaces"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "managed_mode": {
      "type": "boolean"
    },
    "message": {
      "type": "string"
    },
    "path": {
      "type": "string"
    },
    "roles_backfilled": {
      "format": "int64",
      "type": "integer"
    },
    "roles_synced": {
      "format": "int64",
      "type": "integer"
    },
    "tenant_id": {
      "type": "string"
    }
  },
  "required": [
    "message",
    "tenant_id",
    "path",
    "managed_mode"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get all email templates (/api/0.22.2/configuration/getEmailTemplates)

`GET /api/v1/email/templates`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "count": {
      "format": "int64",
      "type": "integer"
    },
    "templates": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "html_body": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "tenant_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "type": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "type",
          "subject",
          "html_body",
          "created_at",
          "updated_at",
          "tenant_id"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "templates",
    "count"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get required permission namespaces (/api/0.22.2/configuration/getPermissionRequirements)

`GET /api/v1/permissions/requirements`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "files": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "contents": {
            "type": "string"
          },
          "name": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "contents"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "namespaces": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "file": {
            "type": "string"
          },
          "namespace": {
            "type": "string"
          },
          "permits": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "relations": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "relations_metadata": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "display_name": {
                  "type": "string"
                },
                "group": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "name": {
                  "type": "string"
                },
                "roles": {
                  "items": {
                    "type": "string"
                  },
                  "type": [
                    "array",
                    "null"
                  ]
                },
                "sub_group": {
                  "type": [
                    "string",
                    "null"
                  ]
                },
                "subjects": {
                  "items": {
                    "type": "string"
                  },
                  "type": [
                    "array",
                    "null"
                  ]
                }
              },
              "required": [
                "name",
                "display_name",
                "group",
                "sub_group",
                "roles",
                "subjects"
              ],
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "subject_relations": {
            "additionalProperties": {
              "items": {
                "type": "string"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "type": "object"
          }
        },
        "required": [
          "namespace",
          "file",
          "relations",
          "permits",
          "subject_relations"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "files",
    "namespaces"
  ],
  "type": "object"
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get config history (/api/0.22.2/configuration/getStripeConfigHistory)

`GET /api/v1/stripe/admin/config/history`

## Parameters

- `limit` (query): 
- `offset` (query): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "configs": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "config": {
            "additionalProperties": false,
            "properties": {
              "coupons": {
                "items": {
                  "$ref": "#/components/schemas/CouponWithStripeID"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "meters": {
                "items": {
                  "$ref": "#/components/schemas/MeterWithStripeID"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "products": {
                "items": {
                  "$ref": "#/components/schemas/ProductWithStripeIDs"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "promotion_codes": {
                "items": {
                  "$ref": "#/components/schemas/PromotionCodeWithStripeID"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "version": {
                "type": "string"
              }
            },
            "required": [
              "version",
              "products"
            ],
            "type": "object"
          },
          "created_at": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "parse_error": {
            "type": "string"
          },
          "updated_at": {
            "type": "string"
          },
          "version": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "config",
          "version",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "pagination": {
      "additionalProperties": false,
      "properties": {
        "has_next": {
          "type": "boolean"
        },
        "has_prev": {
          "type": "boolean"
        },
        "page": {
          "format": "int64",
          "type": "integer"
        },
        "per_page": {
          "format": "int64",
          "type": "integer"
        },
        "total": {
          "format": "int64",
          "type": "integer"
        },
        "total_pages": {
          "format": "int64",
          "type": "integer"
        }
      },
      "required": [
        "total",
        "page",
        "per_page",
        "total_pages",
        "has_next",
        "has_prev"
      ],
      "type": "object"
    }
  },
  "required": [
    "configs",
    "pagination"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get Stripe config schema (/api/0.22.2/configuration/getStripeConfigSchema)

`GET /api/v1/stripe/schema`

## Responses

### 200

OK

```json
{
  "contentEncoding": "base64",
  "type": "string"
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get Stripe config status (/api/0.22.2/configuration/getStripeConfigStatus)

`POST /api/v1/stripe/admin/config/status`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": {},
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "drift": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "kind": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "reason": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          }
        },
        "required": [
          "kind",
          "id",
          "state"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "pending": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "kind": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "reason": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          }
        },
        "required": [
          "kind",
          "id",
          "state"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "summary": {
      "additionalProperties": false,
      "properties": {
        "drift": {
          "format": "int64",
          "type": "integer"
        },
        "pending": {
          "format": "int64",
          "type": "integer"
        },
        "untracked": {
          "format": "int64",
          "type": "integer"
        }
      },
      "required": [
        "pending",
        "drift",
        "untracked"
      ],
      "type": "object"
    },
    "untracked": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "id": {
            "type": "string"
          },
          "kind": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "reason": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          }
        },
        "required": [
          "kind",
          "id",
          "state"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "pending",
    "drift",
    "untracked",
    "summary"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get all system email templates (/api/0.22.2/configuration/getSystemEmailTemplates)

`GET /api/v1/email/system-templates`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "count": {
      "format": "int64",
      "type": "integer"
    },
    "templates": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "html_body": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "plaintext_body": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "subject",
          "html_body",
          "plaintext_body",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "templates",
    "count"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Configuration (/api/0.22.2/configuration)

## Configuration endpoints [#configuration-endpoints]

- [Archive all Stripe config](./archiveAllStripeConfig)
- [Create or update a system email template](./createOrUpdateSystemEmailTemplate)
- [Create or update email template](./createOrUpdateEmailTemplate)
- [Delete a system email template](./deleteSystemEmailTemplate)
- [Delete email template](./deleteEmailTemplate)
- [Deploy Keto namespace configurations](./deployPermissionNamespaces)
- [Get all email templates](./getEmailTemplates)
- [Get all system email templates](./getSystemEmailTemplates)
- [Get config history](./getStripeConfigHistory)
- [Get required permission namespaces](./getPermissionRequirements)
- [Get Stripe config schema](./getStripeConfigSchema)
- [Get Stripe config status](./getStripeConfigStatus)
- [Pull config from Stripe](./pullStripeConfig)
- [Send a raw HTML email](./sendEmailHTML)
- [Send an email using an app template](./sendEmail)
- [Serve a system email template file](./serveSystemEmailTemplate)
- [Serve an email template file](./serveEmailTemplate)
- [Update Stripe config](./updateStripeConfig)
- [Validate Stripe config](./validateStripeConfig)

# Pull config from Stripe (/api/0.22.2/configuration/pullStripeConfig)

`GET /api/v1/stripe/admin/config/pull`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "coupons": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "amount_off": {
            "format": "int64",
            "type": "integer"
          },
          "applies_to": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "currency": {
            "type": "string"
          },
          "duration": {
            "type": "string"
          },
          "duration_in_months": {
            "format": "int64",
            "type": "integer"
          },
          "id": {
            "type": "string"
          },
          "max_redemptions": {
            "format": "int64",
            "type": "integer"
          },
          "metadata": {
            "additionalProperties": {
              "type": "string"
            },
            "type": "object"
          },
          "name": {
            "type": "string"
          },
          "percent_off": {
            "format": "double",
            "type": "number"
          },
          "redeem_by": {
            "format": "int64",
            "type": "integer"
          },
          "stripe_id": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "duration"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "meters": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "customer_mapping": {
            "additionalProperties": false,
            "properties": {
              "event_payload_key": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "required": [
              "event_payload_key",
              "type"
            ],
            "type": "object"
          },
          "default_aggregation": {
            "additionalProperties": false,
            "properties": {
              "formula": {
                "type": "string"
              }
            },
            "required": [
              "formula"
            ],
            "type": "object"
          },
          "display_name": {
            "type": "string"
          },
          "event_name": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          },
          "value_settings": {
            "additionalProperties": false,
            "properties": {
              "event_payload_key": {
                "type": "string"
              }
            },
            "required": [
              "event_payload_key"
            ],
            "type": "object"
          }
        },
        "required": [
          "id",
          "display_name",
          "event_name",
          "default_aggregation"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "products": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "description": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "metadata": {
            "additionalProperties": {
              "type": "string"
            },
            "type": "object"
          },
          "name": {
            "type": "string"
          },
          "prices": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "amount": {
                  "format": "double",
                  "type": "number"
                },
                "billing_scheme": {
                  "type": "string"
                },
                "currency": {
                  "type": "string"
                },
                "default": {
                  "type": "boolean"
                },
                "enterprise_id": {
                  "type": "string"
                },
                "enterprise_template": {
                  "type": "string"
                },
                "id": {
                  "type": "string"
                },
                "interval": {
                  "type": "string"
                },
                "interval_count": {
                  "format": "int64",
                  "type": "integer"
                },
                "metadata": {
                  "additionalProperties": {
                    "type": "string"
                  },
                  "type": "object"
                },
                "meter": {
                  "type": "string"
                },
                "public": {
                  "type": "boolean"
                },
                "stripe_id": {
                  "type": "string"
                },
                "tax_included_in_price": {
                  "type": "boolean"
                },
                "tiers": {
                  "items": {
                    "$ref": "#/components/schemas/Tier"
                  },
                  "type": [
                    "array",
                    "null"
                  ]
                },
                "tiers_mode": {
                  "type": "string"
                },
                "ui": {
                  "$ref": "#/components/schemas/PriceUI"
                },
                "usage_type": {
                  "type": "string"
                }
              },
              "required": [
                "id",
                "currency"
              ],
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "stripe_id": {
            "type": "string"
          },
          "type": {
            "type": "string"
          },
          "ui": {
            "additionalProperties": false,
            "properties": {
              "badge": {
                "type": "string"
              },
              "cta_text": {
                "type": "string"
              },
              "display_name": {
                "type": "string"
              },
              "features": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "highlighted": {
                "type": "boolean"
              },
              "sort_order": {
                "format": "int64",
                "type": "integer"
              },
              "tagline": {
                "type": "string"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "id",
          "name",
          "prices"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "promotion_codes": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "active": {
            "type": "boolean"
          },
          "code": {
            "type": "string"
          },
          "coupon": {
            "type": "string"
          },
          "expires_at": {
            "format": "int64",
            "type": "integer"
          },
          "first_time_transaction": {
            "type": "boolean"
          },
          "id": {
            "type": "string"
          },
          "max_redemptions": {
            "format": "int64",
            "type": "integer"
          },
          "metadata": {
            "additionalProperties": {
              "type": "string"
            },
            "type": "object"
          },
          "minimum_amount": {
            "format": "int64",
            "type": "integer"
          },
          "minimum_amount_currency": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "code",
          "coupon"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "version": {
      "type": "string"
    },
    "webhooks": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "connect": {
            "type": "boolean"
          },
          "events": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "id": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "required": [
          "url",
          "events"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "version",
    "products"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Send an email using an app template (/api/0.22.2/configuration/sendEmail)

`POST /api/v1/email/send`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "data": {
      "additionalProperties": {},
      "type": "object"
    },
    "template_type": {
      "examples": [
        "tenant-user-invite"
      ],
      "type": "string"
    },
    "to": {
      "examples": [
        "user@example.com"
      ],
      "type": "string"
    }
  },
  "required": [
    "to",
    "template_type"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Send a raw HTML email (/api/0.22.2/configuration/sendEmailHTML)

`POST /api/v1/email/send/html`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "body": {
      "examples": [
        "<h1>Hello</h1>"
      ],
      "type": "string"
    },
    "plain": {
      "examples": [
        "Hello"
      ],
      "type": "string"
    },
    "subject": {
      "examples": [
        "Welcome"
      ],
      "type": "string"
    },
    "to": {
      "examples": [
        "user@example.com"
      ],
      "type": "string"
    }
  },
  "required": [
    "to",
    "subject",
    "body"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Serve an email template file (/api/0.22.2/configuration/serveEmailTemplate)

`GET /api/v1/email/templates/{template_name}/{type}`

## Parameters

- `template_name` (path, required): 
- `type` (path, required): 

## Responses

### 200

OK

```json
{
  "contentEncoding": "base64",
  "type": "string"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Serve a system email template file (/api/0.22.2/configuration/serveSystemEmailTemplate)

`GET /api/v1/email/system-templates/{name}/{type}`

## Parameters

- `name` (path, required): 
- `type` (path, required): 

## Responses

### 200

OK

```json
{
  "contentEncoding": "base64",
  "type": "string"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Update Stripe config (/api/0.22.2/configuration/updateStripeConfig)

`POST /api/v1/stripe/admin/config`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": {},
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "changes": {
      "additionalProperties": false,
      "properties": {
        "coupons": {
          "additionalProperties": false,
          "properties": {
            "archived": {
              "items": {
                "$ref": "#/components/schemas/CouponChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "created": {
              "items": {
                "$ref": "#/components/schemas/CouponChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/CouponChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        },
        "meters": {
          "additionalProperties": false,
          "properties": {
            "archived": {
              "items": {
                "$ref": "#/components/schemas/MeterChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "created": {
              "items": {
                "$ref": "#/components/schemas/MeterChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/MeterChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        },
        "prices": {
          "additionalProperties": false,
          "properties": {
            "archived": {
              "items": {
                "$ref": "#/components/schemas/PriceChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "created": {
              "items": {
                "$ref": "#/components/schemas/PriceChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/PriceChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        },
        "products": {
          "additionalProperties": false,
          "properties": {
            "archived": {
              "items": {
                "$ref": "#/components/schemas/ProductChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "created": {
              "items": {
                "$ref": "#/components/schemas/ProductChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/ProductChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        },
        "promotion_codes": {
          "additionalProperties": false,
          "properties": {
            "created": {
              "items": {
                "$ref": "#/components/schemas/PromotionCodeChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "deactivated": {
              "items": {
                "$ref": "#/components/schemas/PromotionCodeChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/PromotionCodeChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        },
        "webhooks": {
          "additionalProperties": false,
          "properties": {
            "created": {
              "items": {
                "$ref": "#/components/schemas/WebhookChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "deleted": {
              "items": {
                "$ref": "#/components/schemas/WebhookChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "unchanged": {
              "items": {
                "$ref": "#/components/schemas/WebhookChange"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "updated": {
              "items": {
                "$ref": "#/components/schemas/WebhookChange"
              },
              "type": [
                "array",
                "null"
              ]
            }
          },
          "type": "object"
        }
      },
      "type": "object"
    },
    "config": {
      "additionalProperties": false,
      "properties": {
        "coupons": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "amount_off": {
                "format": "int64",
                "type": "integer"
              },
              "applies_to": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "currency": {
                "type": "string"
              },
              "duration": {
                "type": "string"
              },
              "duration_in_months": {
                "format": "int64",
                "type": "integer"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "percent_off": {
                "format": "double",
                "type": "number"
              },
              "redeem_by": {
                "format": "int64",
                "type": "integer"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "duration"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "meters": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "customer_mapping": {
                "$ref": "#/components/schemas/MeterCustomerMapping"
              },
              "default_aggregation": {
                "$ref": "#/components/schemas/MeterDefaultAggregation"
              },
              "display_name": {
                "type": "string"
              },
              "event_name": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              },
              "value_settings": {
                "$ref": "#/components/schemas/MeterValueSettings"
              }
            },
            "required": [
              "id",
              "display_name",
              "event_name",
              "default_aggregation"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "products": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "description": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "prices": {
                "items": {
                  "$ref": "#/components/schemas/Price"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "stripe_id": {
                "type": "string"
              },
              "type": {
                "type": "string"
              },
              "ui": {
                "$ref": "#/components/schemas/ProductUI"
              }
            },
            "required": [
              "id",
              "name",
              "prices"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "promotion_codes": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "active": {
                "type": "boolean"
              },
              "code": {
                "type": "string"
              },
              "coupon": {
                "type": "string"
              },
              "expires_at": {
                "format": "int64",
                "type": "integer"
              },
              "first_time_transaction": {
                "type": "boolean"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "minimum_amount": {
                "format": "int64",
                "type": "integer"
              },
              "minimum_amount_currency": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "code",
              "coupon"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "version": {
          "type": "string"
        },
        "webhooks": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "connect": {
                "type": "boolean"
              },
              "events": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "id": {
                "type": "string"
              },
              "url": {
                "type": "string"
              }
            },
            "required": [
              "url",
              "events"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        }
      },
      "required": [
        "version",
        "products"
      ],
      "type": "object"
    },
    "errors": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Validate Stripe config (/api/0.22.2/configuration/validateStripeConfig)

`POST /api/v1/stripe/admin/config/validate`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": {},
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "type": "string"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Generate type definitions for the database schema (/api/0.22.2/database/generateDatabaseTypes)

`GET /api/v1/database/typegen`

## Parameters

- `language` (query): 
- `schemas` (query): 

## Responses

### 200

OK

```json
{
  "contentEncoding": "base64",
  "type": "string"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get the status of applied migrations (/api/0.22.2/database/getDatabaseMigrationStatus)

`GET /api/v1/database/migrations/status`

## Responses

### 200

OK

```json
{
  "items": {
    "additionalProperties": false,
    "properties": {
      "dirty": {
        "type": "boolean"
      },
      "version": {
        "format": "int64",
        "type": "integer"
      }
    },
    "required": [
      "version",
      "dirty"
    ],
    "type": "object"
  },
  "type": [
    "array",
    "null"
  ]
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Database (/api/0.22.2/database)

## Database endpoints [#database-endpoints]

- [Apply database migrations](./uploadDatabaseMigrations)
- [Generate type definitions for the database schema](./generateDatabaseTypes)
- [Get the status of applied migrations](./getDatabaseMigrationStatus)
- [Roll back database migrations](./rollbackDatabaseMigrations)

# Roll back database migrations (/api/0.22.2/database/rollbackDatabaseMigrations)

`POST /api/v1/database/migrations/down`

## Request body

Content type: `multipart/form-data`

```json
{
  "properties": {
    "migrations": {
      "contentEncoding": "binary",
      "contentMediaType": "application/octet-stream",
      "format": "binary",
      "type": "string"
    },
    "steps": {
      "type": "string"
    }
  },
  "required": [
    "migrations",
    "steps"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Apply database migrations (/api/0.22.2/database/uploadDatabaseMigrations)

`POST /api/v1/database/migrations`

## Request body

Content type: `multipart/form-data`

```json
{
  "properties": {
    "migrations": {
      "contentEncoding": "binary",
      "contentMediaType": "application/octet-stream",
      "format": "binary",
      "type": "string"
    }
  },
  "required": [
    "migrations"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "status": {
      "format": "int64",
      "type": "integer"
    }
  },
  "required": [
    "status",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# API Reference (/api/0.22.2)

<Component type="info" title="Version 0.22.2">
This reference is generated from the OpenAPI spec. Endpoints and schemas on this page match this version.
</Component>

## Base URL [#base-url]

All endpoints are rooted at `/api/v1`.

```bash
curl "$OMNIBASE_URL/api/v1/tenants" \
  -H "Authorization: Bearer $OMNIBASE_TOKEN"
```

Authenticated requests use `Authorization: Bearer <token>`. Tenant-scoped requests can use the tenant JWT returned when a tenant is created.

## Resources [#resources]

<Component>
<Component href="./auth" title="Auth">
Sessions, identities, and tenant switching
</Component>

<Component href="./configuration" title="Configuration">
Database migrations, email templates, and Stripe config
</Component>

<Component href="./database" title="Database">
Migration status and database type generation
</Component>

<Component href="./payments" title="Payments">
Checkout, invoices, metered usage, and customer portals
</Component>

<Component href="./permissions" title="Permissions">
Relationship-based access control checks
</Component>

<Component href="./storage" title="Storage">
File uploads, downloads, and object visibility
</Component>

<Component href="./stripe" title="Stripe">
Products, prices, meters, and webhook configuration
</Component>

<Component href="./tenants" title="Tenants">
Tenants, roles, subscriptions, and invitations
</Component>
</Component>

# Add a line item to a Stripe invoice (/api/0.22.2/payments/addInvoiceLineItem)

`POST /api/v1/payments/invoices/{invoice_id}/items`

## Parameters

- `invoice_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "amount": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "maxLength": 3,
      "minLength": 3,
      "type": "string"
    },
    "description": {
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "amount",
    "description",
    "currency"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount": {
      "format": "int64",
      "type": "integer"
    },
    "description": {
      "type": "string"
    },
    "id": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "amount",
    "description"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Add a line item to a Stripe invoice using a price ID (/api/0.22.2/payments/addInvoiceLineItemWithPriceId)

`POST /api/v1/payments/invoices/{invoice_id}/items/price`

## Parameters

- `invoice_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "currency": {
      "maxLength": 3,
      "minLength": 3,
      "type": "string"
    },
    "description": {
      "minLength": 1,
      "type": "string"
    },
    "metadata": {
      "additionalProperties": {
        "type": "string"
      },
      "type": "object"
    },
    "price_id": {
      "type": "string"
    },
    "quantity": {
      "format": "int64",
      "type": "integer"
    },
    "stripe_price_id": {
      "type": "string"
    }
  },
  "required": [
    "quantity",
    "description",
    "currency"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount": {
      "format": "int64",
      "type": "integer"
    },
    "description": {
      "type": "string"
    },
    "id": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "amount",
    "description"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a Stripe checkout session (/api/0.22.2/payments/createCheckout)

`POST /api/v1/payments/checkout`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "allow_promotion_codes": {
      "type": "boolean"
    },
    "cancel_url": {
      "minLength": 1,
      "type": "string"
    },
    "price_id": {
      "minLength": 1,
      "type": "string"
    },
    "promotion_code": {
      "type": "string"
    },
    "success_url": {
      "minLength": 1,
      "type": "string"
    },
    "trial_period_days": {
      "format": "int64",
      "type": "integer"
    }
  },
  "required": [
    "price_id",
    "success_url",
    "cancel_url"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "session_id": {
      "type": "string"
    },
    "url": {
      "type": "string"
    }
  },
  "required": [
    "url",
    "session_id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 403

Forbidden

```json
{
  "title": "Forbidden",
  "status": 403,
  "detail": "Insufficient permissions."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a Stripe customer portal session (/api/0.22.2/payments/createCustomerPortal)

`POST /api/v1/payments/portal`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "return_url": {
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "return_url"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "url": {
      "type": "string"
    }
  },
  "required": [
    "url"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a Stripe invoice (/api/0.22.2/payments/createInvoice)

`POST /api/v1/payments/invoices`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "auto_advance": {
      "type": "boolean"
    },
    "collection_method": {
      "enum": [
        "charge_automatically",
        "send_invoice"
      ],
      "type": "string"
    },
    "currency": {
      "maxLength": 3,
      "minLength": 3,
      "type": "string"
    },
    "days_until_due": {
      "format": "int64",
      "maximum": 365,
      "minimum": 0,
      "type": "integer"
    },
    "description": {
      "type": "string"
    },
    "metadata": {
      "additionalProperties": {
        "type": "string"
      },
      "type": "object"
    }
  },
  "required": [
    "currency"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount_due": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "type": "string"
    },
    "customer_id": {
      "type": "string"
    },
    "hosted_invoice_url": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "invoice_pdf": {
      "type": "string"
    },
    "status": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "status",
    "amount_due",
    "currency",
    "customer_id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Finalize a Stripe invoice (/api/0.22.2/payments/finalizeInvoice)

`POST /api/v1/payments/invoices/{invoice_id}/finalize`

## Parameters

- `invoice_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "auto_advance": {
      "type": "boolean"
    }
  },
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount_due": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "type": "string"
    },
    "customer_id": {
      "type": "string"
    },
    "hosted_invoice_url": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "invoice_pdf": {
      "type": "string"
    },
    "status": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "status",
    "amount_due",
    "currency",
    "customer_id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get a Stripe invoice (/api/0.22.2/payments/getInvoice)

`GET /api/v1/payments/invoices/{invoice_id}`

## Parameters

- `invoice_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount_due": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "type": "string"
    },
    "customer_id": {
      "type": "string"
    },
    "hosted_invoice_url": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "invoice_pdf": {
      "type": "string"
    },
    "status": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "status",
    "amount_due",
    "currency",
    "customer_id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Payments (/api/0.22.2/payments)

## Payments endpoints [#payments-endpoints]

- [Add a line item to a Stripe invoice](./addInvoiceLineItem)
- [Add a line item to a Stripe invoice using a price ID](./addInvoiceLineItemWithPriceId)
- [Create a Stripe checkout session](./createCheckout)
- [Create a Stripe customer portal session](./createCustomerPortal)
- [Create a Stripe invoice](./createInvoice)
- [Finalize a Stripe invoice](./finalizeInvoice)
- [Get a Stripe invoice](./getInvoice)
- [Record a Stripe meter usage event](./recordUsage)
- [Update a Stripe invoice](./updateInvoice)

# Record a Stripe meter usage event (/api/0.22.2/payments/recordUsage)

`POST /api/v1/payments/usage`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "idempotency_key": {
      "maxLength": 100,
      "type": "string"
    },
    "meter_event_name": {
      "minLength": 1,
      "type": "string"
    },
    "value": {
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "meter_event_name",
    "value"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Update a Stripe invoice (/api/0.22.2/payments/updateInvoice)

`PATCH /api/v1/payments/invoices/{invoice_id}`

## Parameters

- `invoice_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "description": {
      "type": "string"
    },
    "metadata": {
      "additionalProperties": {
        "type": "string"
      },
      "type": "object"
    }
  },
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "amount_due": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "type": "string"
    },
    "customer_id": {
      "type": "string"
    },
    "hosted_invoice_url": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "invoice_pdf": {
      "type": "string"
    },
    "status": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "status",
    "amount_due",
    "currency",
    "customer_id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Check permission (/api/0.22.2/permissions/checkPermission)

`POST /api/v1/permissions/check`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "namespace": {
      "examples": [
        "Tenant"
      ],
      "minLength": 1,
      "type": "string"
    },
    "object": {
      "examples": [
        "tenant_test_123"
      ],
      "minLength": 1,
      "type": "string"
    },
    "relation": {
      "examples": [
        "can_invite_user"
      ],
      "minLength": 1,
      "type": "string"
    },
    "subject_set": {
      "additionalProperties": false,
      "properties": {
        "namespace": {
          "examples": [
            "User"
          ],
          "type": "string"
        },
        "object": {
          "examples": [
            "550e8400-e29b-41d4-a716-446655440000"
          ],
          "type": "string"
        },
        "relation": {
          "type": "string"
        }
      },
      "required": [
        "namespace",
        "object"
      ],
      "type": "object"
    }
  },
  "required": [
    "namespace",
    "object",
    "relation",
    "subject_set"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "allowed": {
      "type": "boolean"
    }
  },
  "required": [
    "allowed"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create relationship (/api/0.22.2/permissions/createRelationship)

`POST /api/v1/permissions/relationships`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "namespace": {
      "examples": [
        "Tenant"
      ],
      "type": "string"
    },
    "object": {
      "examples": [
        "tenant_test_123"
      ],
      "type": "string"
    },
    "relation": {
      "examples": [
        "can_invite_user"
      ],
      "type": "string"
    },
    "subject_set": {
      "additionalProperties": false,
      "properties": {
        "namespace": {
          "examples": [
            "User"
          ],
          "type": "string"
        },
        "object": {
          "examples": [
            "550e8400-e29b-41d4-a716-446655440000"
          ],
          "type": "string"
        },
        "relation": {
          "type": "string"
        }
      },
      "required": [
        "namespace",
        "object"
      ],
      "type": "object"
    }
  },
  "required": [
    "namespace",
    "object",
    "relation",
    "subject_set"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Delete relationship (/api/0.22.2/permissions/deleteRelationship)

`DELETE /api/v1/permissions/relationships`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "namespace": {
      "examples": [
        "Tenant"
      ],
      "type": "string"
    },
    "object": {
      "examples": [
        "tenant_test_123"
      ],
      "type": "string"
    },
    "relation": {
      "examples": [
        "can_invite_user"
      ],
      "type": "string"
    },
    "subject_set": {
      "additionalProperties": false,
      "properties": {
        "namespace": {
          "examples": [
            "User"
          ],
          "type": "string"
        },
        "object": {
          "examples": [
            "550e8400-e29b-41d4-a716-446655440000"
          ],
          "type": "string"
        },
        "relation": {
          "type": "string"
        }
      },
      "required": [
        "namespace",
        "object"
      ],
      "type": "object"
    }
  },
  "required": [
    "namespace",
    "object",
    "relation",
    "subject_set"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Permissions (/api/0.22.2/permissions)

## Permissions endpoints [#permissions-endpoints]

- [Check permission](./checkPermission)
- [Create relationship](./createRelationship)
- [Delete relationship](./deleteRelationship)

# Delete file from storage (/api/0.22.2/storage/deleteObject)

`DELETE /api/v1/storage/object`

Storage object paths are unique across the entire bucket, not per tenant. Prefix paths with the tenant ID or another unique namespace, for example `tenants/<tenant_id>/avatars/me.png`.

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "path": {
      "description": "Bucket-wide object path. Prefix with the tenant ID or another unique namespace.",
      "examples": [
        "tenants/00000000-0000-4000-8000-000000000000/avatars/me.png"
      ],
      "type": "string"
    }
  },
  "required": [
    "path"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Download file from storage (/api/0.22.2/storage/downloadFile)

`POST /api/v1/storage/download`

Storage object paths are unique across the entire bucket, not per tenant. Prefix paths with the tenant ID or another unique namespace, for example `tenants/<tenant_id>/avatars/me.png`.

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "path": {
      "description": "Bucket-wide object path. Prefix with the tenant ID or another unique namespace.",
      "examples": [
        "tenants/00000000-0000-4000-8000-000000000000/avatars/me.png"
      ],
      "type": "string"
    }
  },
  "required": [
    "path"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "download_url": {
      "type": "string"
    }
  },
  "required": [
    "download_url"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Storage (/api/0.22.2/storage)

## Storage endpoints [#storage-endpoints]

- [Delete file from storage](./deleteObject)
- [Download file from storage](./downloadFile)
- [Make a file publicly accessible](./makeFilePublic)
- [Upload file to storage](./uploadFile)

# Make a file publicly accessible (/api/0.22.2/storage/makeFilePublic)

`POST /api/v1/storage/make-public`

Storage object paths are unique across the entire bucket, not per tenant. Prefix paths with the tenant ID or another unique namespace, for example `tenants/<tenant_id>/avatars/me.png`.

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "path": {
      "description": "Bucket-wide object path. Prefix with the tenant ID or another unique namespace.",
      "examples": [
        "tenants/00000000-0000-4000-8000-000000000000/avatars/me.png"
      ],
      "type": "string"
    }
  },
  "required": [
    "path"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "path": {
      "type": "string"
    }
  },
  "required": [
    "message",
    "path"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Upload file to storage (/api/0.22.2/storage/uploadFile)

`POST /api/v1/storage/upload`

Storage object paths are unique across the entire bucket, not per tenant. Prefix paths with the tenant ID or another unique namespace, for example `tenants/<tenant_id>/avatars/me.png`. Uploading to an existing path returns 409 Conflict.

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "metadata": {
      "additionalProperties": {},
      "type": "object"
    },
    "path": {
      "description": "Bucket-wide object path. Prefix with the tenant ID or another unique namespace.",
      "examples": [
        "tenants/00000000-0000-4000-8000-000000000000/avatars/me.png"
      ],
      "type": "string"
    }
  },
  "required": [
    "path"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "id": {
      "type": "string"
    },
    "path": {
      "type": "string"
    },
    "upload_url": {
      "type": "string"
    }
  },
  "required": [
    "upload_url",
    "path",
    "id"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Apply custom enterprise pricing (/api/0.22.2/stripe/applyEnterpriseCustom)

`POST /api/v1/stripe/admin/enterprise/apply-custom`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "enterprise_id": {
      "type": "string"
    },
    "tenant_id": {
      "type": "string"
    }
  },
  "required": [
    "tenant_id",
    "enterprise_id"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "prices_swapped": {
      "format": "int64",
      "type": "integer"
    },
    "swapped_details": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "tenant_id": {
      "type": "string"
    }
  },
  "required": [
    "message",
    "tenant_id",
    "prices_swapped"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Apply enterprise template pricing (/api/0.22.2/stripe/applyEnterpriseTemplate)

`POST /api/v1/stripe/admin/enterprise/apply-template`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "enterprise_template": {
      "type": "string"
    },
    "tenant_id": {
      "type": "string"
    }
  },
  "required": [
    "tenant_id",
    "enterprise_template"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "prices_swapped": {
      "format": "int64",
      "type": "integer"
    },
    "swapped_details": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "tenant_id": {
      "type": "string"
    }
  },
  "required": [
    "message",
    "tenant_id",
    "prices_swapped"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Calculate cost for a price (/api/0.22.2/stripe/calculatePriceCost)

`POST /api/v1/stripe/config/prices/{price_id}/calculate`

## Parameters

- `price_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "quantity": {
      "format": "int64",
      "minimum": 0,
      "type": "integer"
    }
  },
  "required": [
    "quantity"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "billing_scheme": {
      "type": "string"
    },
    "cost_cents": {
      "format": "int64",
      "type": "integer"
    },
    "currency": {
      "type": "string"
    },
    "effective_unit_cost_cents": {
      "format": "double",
      "type": "number"
    },
    "price_id": {
      "type": "string"
    },
    "quantity": {
      "format": "int64",
      "type": "integer"
    },
    "tiers_mode": {
      "type": "string"
    }
  },
  "required": [
    "price_id",
    "quantity",
    "cost_cents",
    "effective_unit_cost_cents",
    "currency",
    "billing_scheme"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Convert Stripe ID to config ID (/api/0.22.2/stripe/convertStripeIDToConfigID)

`GET /api/v1/stripe/convert/stripe-id/{stripe_id}`

## Parameters

- `stripe_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "config_id": {
      "type": "string"
    },
    "config_uuid": {
      "type": "string"
    },
    "item_type": {
      "type": "string"
    },
    "stripe_id": {
      "type": "string"
    }
  },
  "required": [
    "stripe_id",
    "config_id",
    "item_type",
    "config_uuid"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get enterprise prices by ID (/api/0.22.2/stripe/getEnterprisePricesByID)

`GET /api/v1/stripe/admin/enterprise/prices/by-id/{enterprise_id}`

## Parameters

- `enterprise_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "count": {
      "format": "int64",
      "type": "integer"
    },
    "prices": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "amount": {
            "format": "double",
            "type": "number"
          },
          "billing_scheme": {
            "type": "string"
          },
          "currency": {
            "type": "string"
          },
          "default": {
            "type": "boolean"
          },
          "enterprise_id": {
            "type": "string"
          },
          "enterprise_template": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "interval": {
            "type": "string"
          },
          "interval_count": {
            "format": "int64",
            "type": "integer"
          },
          "metadata": {
            "additionalProperties": {
              "type": "string"
            },
            "type": "object"
          },
          "meter": {
            "type": "string"
          },
          "public": {
            "type": "boolean"
          },
          "stripe_id": {
            "type": "string"
          },
          "tax_included_in_price": {
            "type": "boolean"
          },
          "tiers": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "flat_amount": {
                  "format": "int64",
                  "type": "integer"
                },
                "unit_amount": {
                  "format": "int64",
                  "type": "integer"
                },
                "up_to": {}
              },
              "required": [
                "up_to"
              ],
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "tiers_mode": {
            "type": "string"
          },
          "ui": {
            "additionalProperties": false,
            "properties": {
              "billing_period": {
                "type": "string"
              },
              "display_name": {
                "type": "string"
              },
              "features": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "limits": {
                "items": {
                  "$ref": "#/components/schemas/PriceLimit"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "price_display": {
                "$ref": "#/components/schemas/PriceDisplay"
              }
            },
            "type": "object"
          },
          "usage_type": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "currency"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "prices",
    "count"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get enterprise prices by template (/api/0.22.2/stripe/getEnterprisePricesByTemplate)

`GET /api/v1/stripe/admin/enterprise/prices/by-template/{template}`

## Parameters

- `template` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "count": {
      "format": "int64",
      "type": "integer"
    },
    "prices": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "amount": {
            "format": "double",
            "type": "number"
          },
          "billing_scheme": {
            "type": "string"
          },
          "currency": {
            "type": "string"
          },
          "default": {
            "type": "boolean"
          },
          "enterprise_id": {
            "type": "string"
          },
          "enterprise_template": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "interval": {
            "type": "string"
          },
          "interval_count": {
            "format": "int64",
            "type": "integer"
          },
          "metadata": {
            "additionalProperties": {
              "type": "string"
            },
            "type": "object"
          },
          "meter": {
            "type": "string"
          },
          "public": {
            "type": "boolean"
          },
          "stripe_id": {
            "type": "string"
          },
          "tax_included_in_price": {
            "type": "boolean"
          },
          "tiers": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "flat_amount": {
                  "format": "int64",
                  "type": "integer"
                },
                "unit_amount": {
                  "format": "int64",
                  "type": "integer"
                },
                "up_to": {}
              },
              "required": [
                "up_to"
              ],
              "type": "object"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "tiers_mode": {
            "type": "string"
          },
          "ui": {
            "additionalProperties": false,
            "properties": {
              "billing_period": {
                "type": "string"
              },
              "display_name": {
                "type": "string"
              },
              "features": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "limits": {
                "items": {
                  "$ref": "#/components/schemas/PriceLimit"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "price_display": {
                "$ref": "#/components/schemas/PriceDisplay"
              }
            },
            "type": "object"
          },
          "usage_type": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "currency"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "prices",
    "count"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get meter by ID (/api/0.22.2/stripe/getMeterByID)

`GET /api/v1/stripe/config/meters/{meter_id}`

## Parameters

- `meter_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "meter": {
      "additionalProperties": false,
      "properties": {
        "customer_mapping": {
          "additionalProperties": false,
          "properties": {
            "event_payload_key": {
              "type": "string"
            },
            "type": {
              "type": "string"
            }
          },
          "required": [
            "event_payload_key",
            "type"
          ],
          "type": "object"
        },
        "default_aggregation": {
          "additionalProperties": false,
          "properties": {
            "formula": {
              "type": "string"
            }
          },
          "required": [
            "formula"
          ],
          "type": "object"
        },
        "display_name": {
          "type": "string"
        },
        "event_name": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "stripe_id": {
          "type": "string"
        },
        "value_settings": {
          "additionalProperties": false,
          "properties": {
            "event_payload_key": {
              "type": "string"
            }
          },
          "required": [
            "event_payload_key"
          ],
          "type": "object"
        }
      },
      "required": [
        "id",
        "display_name",
        "event_name",
        "default_aggregation"
      ],
      "type": "object"
    }
  },
  "required": [
    "meter"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get price by ID (/api/0.22.2/stripe/getPriceByID)

`GET /api/v1/stripe/config/prices/{price_id}`

## Parameters

- `price_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "price": {
      "additionalProperties": false,
      "properties": {
        "amount": {
          "format": "double",
          "type": "number"
        },
        "billing_scheme": {
          "type": "string"
        },
        "currency": {
          "type": "string"
        },
        "default": {
          "type": "boolean"
        },
        "enterprise_id": {
          "type": "string"
        },
        "enterprise_template": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "interval": {
          "type": "string"
        },
        "interval_count": {
          "format": "int64",
          "type": "integer"
        },
        "metadata": {
          "additionalProperties": {
            "type": "string"
          },
          "type": "object"
        },
        "meter": {
          "type": "string"
        },
        "public": {
          "type": "boolean"
        },
        "stripe_id": {
          "type": "string"
        },
        "tax_included_in_price": {
          "type": "boolean"
        },
        "tiers": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "flat_amount": {
                "format": "int64",
                "type": "integer"
              },
              "unit_amount": {
                "format": "int64",
                "type": "integer"
              },
              "up_to": {}
            },
            "required": [
              "up_to"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "tiers_mode": {
          "type": "string"
        },
        "ui": {
          "additionalProperties": false,
          "properties": {
            "billing_period": {
              "type": "string"
            },
            "display_name": {
              "type": "string"
            },
            "features": {
              "items": {
                "type": "string"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "limits": {
              "items": {
                "$ref": "#/components/schemas/PriceLimit"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "price_display": {
              "$ref": "#/components/schemas/PriceDisplay"
            }
          },
          "type": "object"
        },
        "usage_type": {
          "type": "string"
        }
      },
      "required": [
        "id",
        "currency"
      ],
      "type": "object"
    },
    "product": {
      "additionalProperties": false,
      "properties": {
        "description": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "metadata": {
          "additionalProperties": {
            "type": "string"
          },
          "type": "object"
        },
        "name": {
          "type": "string"
        },
        "prices": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "amount": {
                "format": "double",
                "type": "number"
              },
              "billing_scheme": {
                "type": "string"
              },
              "currency": {
                "type": "string"
              },
              "default": {
                "type": "boolean"
              },
              "enterprise_id": {
                "type": "string"
              },
              "enterprise_template": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "interval": {
                "type": "string"
              },
              "interval_count": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "meter": {
                "type": "string"
              },
              "public": {
                "type": "boolean"
              },
              "stripe_id": {
                "type": "string"
              },
              "tax_included_in_price": {
                "type": "boolean"
              },
              "tiers": {
                "items": {
                  "$ref": "#/components/schemas/Tier"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "tiers_mode": {
                "type": "string"
              },
              "ui": {
                "$ref": "#/components/schemas/PriceUI"
              },
              "usage_type": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "currency"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "stripe_id": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "ui": {
          "additionalProperties": false,
          "properties": {
            "badge": {
              "type": "string"
            },
            "cta_text": {
              "type": "string"
            },
            "display_name": {
              "type": "string"
            },
            "features": {
              "items": {
                "type": "string"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "highlighted": {
              "type": "boolean"
            },
            "sort_order": {
              "format": "int64",
              "type": "integer"
            },
            "tagline": {
              "type": "string"
            }
          },
          "type": "object"
        }
      },
      "required": [
        "id",
        "name",
        "prices"
      ],
      "type": "object"
    }
  },
  "required": [
    "price",
    "product"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get product by ID (/api/0.22.2/stripe/getProductByID)

`GET /api/v1/stripe/config/products/{product_id}`

## Parameters

- `product_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "product": {
      "additionalProperties": false,
      "properties": {
        "description": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "metadata": {
          "additionalProperties": {
            "type": "string"
          },
          "type": "object"
        },
        "name": {
          "type": "string"
        },
        "prices": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "amount": {
                "format": "double",
                "type": "number"
              },
              "billing_scheme": {
                "type": "string"
              },
              "currency": {
                "type": "string"
              },
              "default": {
                "type": "boolean"
              },
              "enterprise_id": {
                "type": "string"
              },
              "enterprise_template": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "interval": {
                "type": "string"
              },
              "interval_count": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "meter": {
                "type": "string"
              },
              "public": {
                "type": "boolean"
              },
              "stripe_id": {
                "type": "string"
              },
              "tax_included_in_price": {
                "type": "boolean"
              },
              "tiers": {
                "items": {
                  "$ref": "#/components/schemas/Tier"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "tiers_mode": {
                "type": "string"
              },
              "ui": {
                "$ref": "#/components/schemas/PriceUI"
              },
              "usage_type": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "currency"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "stripe_id": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "ui": {
          "additionalProperties": false,
          "properties": {
            "badge": {
              "type": "string"
            },
            "cta_text": {
              "type": "string"
            },
            "display_name": {
              "type": "string"
            },
            "features": {
              "items": {
                "type": "string"
              },
              "type": [
                "array",
                "null"
              ]
            },
            "highlighted": {
              "type": "boolean"
            },
            "sort_order": {
              "format": "int64",
              "type": "integer"
            },
            "tagline": {
              "type": "string"
            }
          },
          "type": "object"
        }
      },
      "required": [
        "id",
        "name",
        "prices"
      ],
      "type": "object"
    }
  },
  "required": [
    "product"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get public Stripe config (/api/0.22.2/stripe/getStripeConfig)

`GET /api/v1/stripe/config`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "config": {
      "additionalProperties": false,
      "properties": {
        "coupons": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "amount_off": {
                "format": "int64",
                "type": "integer"
              },
              "applies_to": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "currency": {
                "type": "string"
              },
              "duration": {
                "type": "string"
              },
              "duration_in_months": {
                "format": "int64",
                "type": "integer"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "percent_off": {
                "format": "double",
                "type": "number"
              },
              "redeem_by": {
                "format": "int64",
                "type": "integer"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "duration"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "meters": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "customer_mapping": {
                "$ref": "#/components/schemas/MeterCustomerMapping"
              },
              "default_aggregation": {
                "$ref": "#/components/schemas/MeterDefaultAggregation"
              },
              "display_name": {
                "type": "string"
              },
              "event_name": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              },
              "value_settings": {
                "$ref": "#/components/schemas/MeterValueSettings"
              }
            },
            "required": [
              "id",
              "display_name",
              "event_name",
              "default_aggregation"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "products": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "description": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "prices": {
                "items": {
                  "$ref": "#/components/schemas/PriceWithStripeID"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "stripe_id": {
                "type": "string"
              },
              "type": {
                "type": "string"
              },
              "ui": {
                "$ref": "#/components/schemas/ProductUI"
              }
            },
            "required": [
              "id",
              "name",
              "prices"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "promotion_codes": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "active": {
                "type": "boolean"
              },
              "code": {
                "type": "string"
              },
              "coupon": {
                "type": "string"
              },
              "expires_at": {
                "format": "int64",
                "type": "integer"
              },
              "first_time_transaction": {
                "type": "boolean"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "minimum_amount": {
                "format": "int64",
                "type": "integer"
              },
              "minimum_amount_currency": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "code",
              "coupon"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "version": {
          "type": "string"
        }
      },
      "required": [
        "version",
        "products"
      ],
      "type": "object"
    },
    "created_at": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "updated_at": {
      "type": "string"
    },
    "version": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "config",
    "version",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get full Stripe config (admin) (/api/0.22.2/stripe/getStripeConfigAdmin)

`GET /api/v1/stripe/admin/config`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "config": {
      "additionalProperties": false,
      "properties": {
        "coupons": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "amount_off": {
                "format": "int64",
                "type": "integer"
              },
              "applies_to": {
                "items": {
                  "type": "string"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "currency": {
                "type": "string"
              },
              "duration": {
                "type": "string"
              },
              "duration_in_months": {
                "format": "int64",
                "type": "integer"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "percent_off": {
                "format": "double",
                "type": "number"
              },
              "redeem_by": {
                "format": "int64",
                "type": "integer"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "duration"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "meters": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "customer_mapping": {
                "$ref": "#/components/schemas/MeterCustomerMapping"
              },
              "default_aggregation": {
                "$ref": "#/components/schemas/MeterDefaultAggregation"
              },
              "display_name": {
                "type": "string"
              },
              "event_name": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              },
              "value_settings": {
                "$ref": "#/components/schemas/MeterValueSettings"
              }
            },
            "required": [
              "id",
              "display_name",
              "event_name",
              "default_aggregation"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "products": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "description": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "name": {
                "type": "string"
              },
              "prices": {
                "items": {
                  "$ref": "#/components/schemas/PriceWithStripeID"
                },
                "type": [
                  "array",
                  "null"
                ]
              },
              "stripe_id": {
                "type": "string"
              },
              "type": {
                "type": "string"
              },
              "ui": {
                "$ref": "#/components/schemas/ProductUI"
              }
            },
            "required": [
              "id",
              "name",
              "prices"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "promotion_codes": {
          "items": {
            "additionalProperties": false,
            "properties": {
              "active": {
                "type": "boolean"
              },
              "code": {
                "type": "string"
              },
              "coupon": {
                "type": "string"
              },
              "expires_at": {
                "format": "int64",
                "type": "integer"
              },
              "first_time_transaction": {
                "type": "boolean"
              },
              "id": {
                "type": "string"
              },
              "max_redemptions": {
                "format": "int64",
                "type": "integer"
              },
              "metadata": {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              "minimum_amount": {
                "format": "int64",
                "type": "integer"
              },
              "minimum_amount_currency": {
                "type": "string"
              },
              "stripe_id": {
                "type": "string"
              }
            },
            "required": [
              "id",
              "code",
              "coupon"
            ],
            "type": "object"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "version": {
          "type": "string"
        }
      },
      "required": [
        "version",
        "products"
      ],
      "type": "object"
    },
    "created_at": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "updated_at": {
      "type": "string"
    },
    "version": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "config",
    "version",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Stripe (/api/0.22.2/stripe)

## Stripe endpoints [#stripe-endpoints]

- [Apply custom enterprise pricing](./applyEnterpriseCustom)
- [Apply enterprise template pricing](./applyEnterpriseTemplate)
- [Calculate cost for a price](./calculatePriceCost)
- [Convert Stripe ID to config ID](./convertStripeIDToConfigID)
- [Get enterprise prices by ID](./getEnterprisePricesByID)
- [Get enterprise prices by template](./getEnterprisePricesByTemplate)
- [Get full Stripe config (admin)](./getStripeConfigAdmin)
- [Get meter by ID](./getMeterByID)
- [Get price by ID](./getPriceByID)
- [Get product by ID](./getProductByID)
- [Get public Stripe config](./getStripeConfig)
- [List all webhooks](./listWebhooks)

# List all webhooks (/api/0.22.2/stripe/listWebhooks)

`GET /api/v1/stripe/admin/webhooks`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "count": {
      "format": "int64",
      "type": "integer"
    },
    "webhooks": {
      "items": {
        "additionalProperties": false,
        "properties": {
          "config_id": {
            "type": "string"
          },
          "connect": {
            "type": "boolean"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "events": {
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "id": {
            "type": "string"
          },
          "secret": {
            "type": "string"
          },
          "stripe_id": {
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "stripe_id",
          "url",
          "secret",
          "events",
          "connect",
          "config_id",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "webhooks",
    "count"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Accept a tenant invite (/api/0.22.2/tenants/acceptInvite)

`PUT /api/v1/tenants/invites/accept`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "token": {
      "examples": [
        "tok_test_abc123xyz"
      ],
      "type": "string"
    }
  },
  "required": [
    "token"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "examples": [
        "Successfully joined organization"
      ],
      "type": "string"
    },
    "tenant_id": {
      "examples": [
        "550e8400-e29b-41d4-a716-446655440000"
      ],
      "type": "string"
    }
  },
  "required": [
    "tenant_id",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 403

Forbidden

```json
{
  "title": "Forbidden",
  "status": 403,
  "detail": "Insufficient permissions."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Add a subscription to the tenant (/api/0.22.2/tenants/addSubscription)

`POST /api/v1/tenants/subscriptions`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "idempotency_key": {
      "maxLength": 255,
      "minLength": 1,
      "type": "string"
    },
    "plan_id": {
      "examples": [
        "price_test_basic"
      ],
      "minLength": 1,
      "type": "string"
    },
    "quantity": {
      "examples": [
        5
      ],
      "format": "int64",
      "type": "integer"
    }
  },
  "required": [
    "plan_id",
    "idempotency_key"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "status": {
      "type": "string"
    },
    "subscription_id": {
      "type": "string"
    }
  },
  "required": [
    "subscription_id",
    "status",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 403

Forbidden

```json
{
  "title": "Forbidden",
  "status": 403,
  "detail": "Insufficient permissions."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a tenant invite (/api/0.22.2/tenants/createInvite)

`POST /api/v1/tenants/invites`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "email": {
      "examples": [
        "test@example.com"
      ],
      "format": "email",
      "type": "string"
    },
    "invite_url": {
      "examples": [
        "https://app.example.com/accept-invite"
      ],
      "format": "uri",
      "type": "string"
    },
    "role": {
      "examples": [
        "member"
      ],
      "type": "string"
    }
  },
  "required": [
    "email",
    "role",
    "invite_url"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "invite": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "email": {
          "type": "string"
        },
        "expires_at": {
          "format": "date-time",
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "inviter_id": {
          "type": "string"
        },
        "role": {
          "type": "string"
        },
        "tenant_id": {
          "type": "string"
        },
        "token": {
          "type": "string"
        },
        "used_at": {
          "format": "date-time",
          "type": [
            "string",
            "null"
          ]
        }
      },
      "required": [
        "id",
        "tenant_id",
        "email",
        "role",
        "token",
        "inviter_id",
        "expires_at",
        "used_at",
        "created_at"
      ],
      "type": "object"
    },
    "message": {
      "examples": [
        "Invite sent successfully"
      ],
      "type": "string"
    }
  },
  "required": [
    "invite",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a role (/api/0.22.2/tenants/createRole)

`POST /api/v1/tenants/roles`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "permissions": {
      "examples": [
        [
          "project:*#view",
          "tenant#read"
        ]
      ],
      "items": {
        "minLength": 1,
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "role_name": {
      "examples": [
        "test_project_viewer"
      ],
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "role_name",
    "permissions"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "permissions": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "role_name": {
      "type": "string"
    },
    "template_id": {
      "type": "string"
    },
    "tenant_id": {
      "type": "string"
    },
    "updated_at": {
      "format": "date-time",
      "type": "string"
    },
    "user_ids": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "id",
    "tenant_id",
    "role_name",
    "permissions",
    "template_id",
    "user_ids",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a tenant (/api/0.22.2/tenants/createTenant)

`POST /api/v1/tenants`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "billing_email": {
      "examples": [
        "billing@test.example.com"
      ],
      "type": "string"
    },
    "name": {
      "examples": [
        "Test Organization"
      ],
      "minLength": 1,
      "type": "string"
    },
    "type": {
      "examples": [
        "organization"
      ],
      "type": "string"
    }
  },
  "required": [
    "name",
    "billing_email",
    "type"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "tenant": {
      "additionalProperties": false,
      "properties": {
        "created_at": {
          "format": "date-time",
          "type": "string"
        },
        "enterprise_id": {
          "type": "string"
        },
        "enterprise_template": {
          "type": "string"
        },
        "id": {
          "type": "string"
        },
        "name": {
          "type": "string"
        },
        "stripe_customer_id": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "updated_at": {
          "format": "date-time",
          "type": "string"
        }
      },
      "required": [
        "id",
        "name",
        "type",
        "created_at",
        "updated_at"
      ],
      "type": "object"
    }
  },
  "required": [
    "tenant",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Delete a role (/api/0.22.2/tenants/deleteRole)

`DELETE /api/v1/tenants/roles/{role_id}`

## Parameters

- `role_id` (path, required): 

## Responses

### 200

OK

```json
{}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Delete the current tenant (/api/0.22.2/tenants/deleteTenant)

`DELETE /api/v1/tenants`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get tenant billing status (/api/0.22.2/tenants/getTenantBillingStatus)

`GET /api/v1/tenants/billing-status`

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "is_active": {
      "type": "boolean"
    }
  },
  "required": [
    "is_active"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get tenant by ID (/api/0.22.2/tenants/getTenantByID)

`GET /api/v1/tenants/by-id/{tenant_id}`

## Parameters

- `tenant_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "enterprise_id": {
      "type": [
        "string",
        "null"
      ]
    },
    "enterprise_template": {
      "type": [
        "string",
        "null"
      ]
    },
    "id": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "stripe_customer_id": {
      "type": [
        "string",
        "null"
      ]
    },
    "type": {
      "type": "string"
    },
    "updated_at": {
      "format": "date-time",
      "type": "string"
    }
  },
  "required": [
    "id",
    "name",
    "stripe_customer_id",
    "enterprise_template",
    "enterprise_id",
    "type",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get tenant by Stripe customer ID (/api/0.22.2/tenants/getTenantByStripeCustomerID)

`GET /api/v1/tenants/by-stripe-customer/{stripe_customer_id}`

## Parameters

- `stripe_customer_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "enterprise_id": {
      "type": [
        "string",
        "null"
      ]
    },
    "enterprise_template": {
      "type": [
        "string",
        "null"
      ]
    },
    "id": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "stripe_customer_id": {
      "type": [
        "string",
        "null"
      ]
    },
    "type": {
      "type": "string"
    },
    "updated_at": {
      "format": "date-time",
      "type": "string"
    }
  },
  "required": [
    "id",
    "name",
    "stripe_customer_id",
    "enterprise_template",
    "enterprise_id",
    "type",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Get a single tenant subscription (/api/0.22.2/tenants/getTenantSubscription)

`GET /api/v1/tenants/subscriptions/{config_price_id}`

## Parameters

- `config_price_id` (path, required): 

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "cancel_at_period_end": {
      "type": "boolean"
    },
    "canceled_at": {
      "format": "int64",
      "type": "integer"
    },
    "config_price_id": {
      "type": "string"
    },
    "current_period_end": {
      "format": "int64",
      "type": "integer"
    },
    "current_period_start": {
      "format": "int64",
      "type": "integer"
    },
    "is_legacy_price": {
      "type": "boolean"
    },
    "status": {
      "type": "string"
    },
    "subscription_id": {
      "type": "string"
    },
    "trial_end": {
      "format": "int64",
      "type": "integer"
    },
    "trial_start": {
      "format": "int64",
      "type": "integer"
    }
  },
  "required": [
    "subscription_id",
    "config_price_id",
    "status",
    "is_legacy_price",
    "current_period_start",
    "current_period_end",
    "cancel_at_period_end"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Tenants (/api/0.22.2/tenants)

## Tenants endpoints [#tenants-endpoints]

- [Accept a tenant invite](./acceptInvite)
- [Add a subscription to the tenant](./addSubscription)
- [Create a role](./createRole)
- [Create a tenant](./createTenant)
- [Create a tenant invite](./createInvite)
- [Delete a role](./deleteRole)
- [Delete the current tenant](./deleteTenant)
- [Get a single tenant subscription](./getTenantSubscription)
- [Get tenant billing status](./getTenantBillingStatus)
- [Get tenant by ID](./getTenantByID)
- [Get tenant by Stripe customer ID](./getTenantByStripeCustomerID)
- [List role definitions](./listRoleDefinitions)
- [List roles for the tenant](./listRoles)
- [List subscriptions for the tenant](./listTenantSubscriptions)
- [List users in the tenant](./listTenantUsers)
- [Remove a subscription from the tenant](./removeSubscription)
- [Remove a user from the tenant](./removeTenantUser)
- [Switch the active tenant](./switchActiveTenant)
- [Update a role](./updateRole)
- [Update a tenant user's role](./updateTenantUserRole)

# List role definitions (/api/0.22.2/tenants/listRoleDefinitions)

`GET /api/v1/tenants/roles/definitions`

## Parameters

- `subject` (query): 

## Responses

### 200

OK

```json
{
  "items": {
    "additionalProperties": false,
    "properties": {
      "id": {
        "type": "string"
      },
      "namespace": {
        "type": "string"
      },
      "relations": {
        "items": {
          "type": "string"
        },
        "type": [
          "array",
          "null"
        ]
      },
      "relations_metadata": {
        "items": {
          "additionalProperties": false,
          "properties": {
            "display_name": {
              "type": "string"
            },
            "group": {
              "type": [
                "string",
                "null"
              ]
            },
            "name": {
              "type": "string"
            },
            "sub_group": {
              "type": [
                "string",
                "null"
              ]
            }
          },
          "required": [
            "name",
            "display_name",
            "group",
            "sub_group"
          ],
          "type": "object"
        },
        "type": [
          "array",
          "null"
        ]
      },
      "subject_relations": {
        "additionalProperties": {
          "items": {
            "type": "string"
          },
          "type": [
            "array",
            "null"
          ]
        },
        "type": "object"
      },
      "updated_at": {
        "format": "date-time",
        "type": "string"
      }
    },
    "required": [
      "id",
      "namespace",
      "relations",
      "relations_metadata",
      "subject_relations",
      "updated_at"
    ],
    "type": "object"
  },
  "type": [
    "array",
    "null"
  ]
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# List roles for the tenant (/api/0.22.2/tenants/listRoles)

`GET /api/v1/tenants/roles`

## Responses

### 200

OK

```json
{
  "items": {
    "additionalProperties": false,
    "properties": {
      "created_at": {
        "format": "date-time",
        "type": "string"
      },
      "id": {
        "type": "string"
      },
      "permissions": {
        "items": {
          "type": "string"
        },
        "type": [
          "array",
          "null"
        ]
      },
      "role_name": {
        "type": "string"
      },
      "template_id": {
        "type": "string"
      },
      "tenant_id": {
        "type": "string"
      },
      "updated_at": {
        "format": "date-time",
        "type": "string"
      },
      "user_ids": {
        "items": {
          "type": "string"
        },
        "type": [
          "array",
          "null"
        ]
      }
    },
    "required": [
      "id",
      "tenant_id",
      "role_name",
      "permissions",
      "template_id",
      "user_ids",
      "created_at",
      "updated_at"
    ],
    "type": "object"
  },
  "type": [
    "array",
    "null"
  ]
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# List subscriptions for the tenant (/api/0.22.2/tenants/listTenantSubscriptions)

`GET /api/v1/tenants/subscriptions`

## Responses

### 200

OK

```json
{
  "items": {
    "additionalProperties": false,
    "properties": {
      "cancel_at_period_end": {
        "type": "boolean"
      },
      "canceled_at": {
        "format": "int64",
        "type": "integer"
      },
      "config_price_id": {
        "type": "string"
      },
      "current_period_end": {
        "format": "int64",
        "type": "integer"
      },
      "current_period_start": {
        "format": "int64",
        "type": "integer"
      },
      "is_legacy_price": {
        "type": "boolean"
      },
      "status": {
        "type": "string"
      },
      "subscription_id": {
        "type": "string"
      },
      "trial_end": {
        "format": "int64",
        "type": "integer"
      },
      "trial_start": {
        "format": "int64",
        "type": "integer"
      }
    },
    "required": [
      "subscription_id",
      "config_price_id",
      "status",
      "is_legacy_price",
      "current_period_start",
      "current_period_end",
      "cancel_at_period_end"
    ],
    "type": "object"
  },
  "type": [
    "array",
    "null"
  ]
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# List users in the tenant (/api/0.22.2/tenants/listTenantUsers)

`GET /api/v1/tenants/users`

## Responses

### 200

OK

```json
{
  "items": {
    "additionalProperties": false,
    "properties": {
      "email": {
        "examples": [
          "test@example.com"
        ],
        "type": "string"
      },
      "first_name": {
        "examples": [
          "John"
        ],
        "type": "string"
      },
      "last_name": {
        "examples": [
          "Doe"
        ],
        "type": "string"
      },
      "role": {
        "examples": [
          "member"
        ],
        "type": "string"
      },
      "user_id": {
        "examples": [
          "550e8400-e29b-41d4-a716-446655440000"
        ],
        "type": "string"
      }
    },
    "required": [
      "user_id",
      "first_name",
      "last_name",
      "email",
      "role"
    ],
    "type": "object"
  },
  "type": [
    "array",
    "null"
  ]
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Remove a subscription from the tenant (/api/0.22.2/tenants/removeSubscription)

`DELETE /api/v1/tenants/subscriptions`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "plan_id": {
      "examples": [
        "price_test_basic"
      ],
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "plan_id"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "type": "string"
    },
    "status": {
      "type": "string"
    },
    "subscription_id": {
      "type": "string"
    }
  },
  "required": [
    "subscription_id",
    "status",
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 403

Forbidden

```json
{
  "title": "Forbidden",
  "status": 403,
  "detail": "Insufficient permissions."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 409

Conflict

```json
{
  "title": "Conflict",
  "status": 409,
  "detail": "The resource already exists."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 429

Too Many Requests

```json
{
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded."
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Remove a user from the tenant (/api/0.22.2/tenants/removeTenantUser)

`DELETE /api/v1/tenants/users`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "user_id": {
      "examples": [
        "550e8400-e29b-41d4-a716-446655440001"
      ],
      "minLength": 1,
      "type": "string"
    }
  },
  "required": [
    "user_id"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Switch the active tenant (/api/0.22.2/tenants/switchActiveTenant)

`PUT /api/v1/tenants/switch-active`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "tenant_id": {
      "examples": [
        "550e8400-e29b-41d4-a716-446655440000"
      ],
      "format": "uuid",
      "type": "string"
    }
  },
  "required": [
    "tenant_id"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "examples": [
        "Successfully switched tenants"
      ],
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Update a role (/api/0.22.2/tenants/updateRole)

`PUT /api/v1/tenants/roles/{role_id}`

## Parameters

- `role_id` (path, required): 

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "permissions": {
      "examples": [
        [
          "project:*#view",
          "project:*#edit"
        ]
      ],
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "permissions"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "created_at": {
      "format": "date-time",
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "permissions": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    },
    "role_name": {
      "type": "string"
    },
    "template_id": {
      "type": "string"
    },
    "tenant_id": {
      "type": "string"
    },
    "updated_at": {
      "format": "date-time",
      "type": "string"
    },
    "user_ids": {
      "items": {
        "type": "string"
      },
      "type": [
        "array",
        "null"
      ]
    }
  },
  "required": [
    "id",
    "tenant_id",
    "role_name",
    "permissions",
    "template_id",
    "user_ids",
    "created_at",
    "updated_at"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Update a tenant user's role (/api/0.22.2/tenants/updateTenantUserRole)

`PUT /api/v1/tenants/users`

## Request body

Content type: `application/json`

```json
{
  "additionalProperties": false,
  "properties": {
    "role": {
      "examples": [
        "member"
      ],
      "type": "string"
    },
    "user_id": {
      "examples": [
        "550e8400-e29b-41d4-a716-446655440001"
      ],
      "type": "string"
    }
  },
  "required": [
    "role",
    "user_id"
  ],
  "type": "object"
}
```

## Responses

### 200

OK

```json
{
  "additionalProperties": false,
  "properties": {
    "message": {
      "examples": [
        "User role updated successfully"
      ],
      "type": "string"
    }
  },
  "required": [
    "message"
  ],
  "type": "object"
}
```

### 400

Bad Request

```json
{
  "title": "Bad Request",
  "status": 400,
  "detail": "The request could not be processed."
}
```

### 401

Unauthorized

```json
{
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required."
}
```

### 404

Not Found

```json
{
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource was not found."
}
```

### 422

Unprocessable Entity

```json
{
  "title": "Unprocessable Entity",
  "status": 422,
  "detail": "Validation failed.",
  "errors": [
    {
      "message": "expected required property path to be present",
      "location": "body.path"
    }
  ]
}
```

### 500

Internal Server Error

```json
{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Internal server error."
}
```


# Create a new user identity (/api/dev/auth/createUser)



# Get the active tenant for the authenticated user (/api/dev/auth/getActiveTenant)



# Get current identity (/api/dev/auth/getIdentity)



# Get current session (/api/dev/auth/getSession)



# Auth (/api/dev/auth)

## Auth endpoints [#auth-endpoints]

- [Create a new user identity](./createUser)
- [Get authenticated user identity](./whoAmI)
- [Get current identity](./getIdentity)
- [Get current session](./getSession)
- [Get the active tenant for the authenticated user](./getActiveTenant)
- [List tenants the authenticated user belongs to](./listTenants)
- [Logout user](./logout)

# List tenants the authenticated user belongs to (/api/dev/auth/listTenants)



# Logout user (/api/dev/auth/logout)



# Get authenticated user identity (/api/dev/auth/whoAmI)



# Archive all Stripe config (/api/dev/configuration/archiveAllStripeConfig)



# Create or update email template (/api/dev/configuration/createOrUpdateEmailTemplate)



# Create or update a system email template (/api/dev/configuration/createOrUpdateSystemEmailTemplate)



# Delete email template (/api/dev/configuration/deleteEmailTemplate)



# Delete a system email template (/api/dev/configuration/deleteSystemEmailTemplate)



# Deploy Keto namespace configurations (/api/dev/configuration/deployPermissionNamespaces)



# Get all email templates (/api/dev/configuration/getEmailTemplates)



# Get required permission namespaces (/api/dev/configuration/getPermissionRequirements)



# Get config history (/api/dev/configuration/getStripeConfigHistory)



# Get Stripe config schema (/api/dev/configuration/getStripeConfigSchema)



# Get Stripe config status (/api/dev/configuration/getStripeConfigStatus)



# Get all system email templates (/api/dev/configuration/getSystemEmailTemplates)



# Configuration (/api/dev/configuration)

## Configuration endpoints [#configuration-endpoints]

- [Archive all Stripe config](./archiveAllStripeConfig)
- [Create or update a system email template](./createOrUpdateSystemEmailTemplate)
- [Create or update email template](./createOrUpdateEmailTemplate)
- [Delete a system email template](./deleteSystemEmailTemplate)
- [Delete email template](./deleteEmailTemplate)
- [Deploy Keto namespace configurations](./deployPermissionNamespaces)
- [Get all email templates](./getEmailTemplates)
- [Get all system email templates](./getSystemEmailTemplates)
- [Get config history](./getStripeConfigHistory)
- [Get required permission namespaces](./getPermissionRequirements)
- [Get Stripe config schema](./getStripeConfigSchema)
- [Get Stripe config status](./getStripeConfigStatus)
- [Pull config from Stripe](./pullStripeConfig)
- [Send a raw HTML email](./sendEmailHTML)
- [Send an email using an app template](./sendEmail)
- [Serve a system email template file](./serveSystemEmailTemplate)
- [Serve an email template file](./serveEmailTemplate)
- [Update Stripe config](./updateStripeConfig)
- [Validate Stripe config](./validateStripeConfig)

# Pull config from Stripe (/api/dev/configuration/pullStripeConfig)



# Send an email using an app template (/api/dev/configuration/sendEmail)



# Send a raw HTML email (/api/dev/configuration/sendEmailHTML)



# Serve an email template file (/api/dev/configuration/serveEmailTemplate)



# Serve a system email template file (/api/dev/configuration/serveSystemEmailTemplate)



# Update Stripe config (/api/dev/configuration/updateStripeConfig)



# Validate Stripe config (/api/dev/configuration/validateStripeConfig)



# Generate type definitions for the database schema (/api/dev/database/generateDatabaseTypes)



# Get the status of applied migrations (/api/dev/database/getDatabaseMigrationStatus)



# Database (/api/dev/database)

## Database endpoints [#database-endpoints]

- [Apply database migrations](./uploadDatabaseMigrations)
- [Generate type definitions for the database schema](./generateDatabaseTypes)
- [Get the status of applied migrations](./getDatabaseMigrationStatus)
- [Roll back database migrations](./rollbackDatabaseMigrations)

# Roll back database migrations (/api/dev/database/rollbackDatabaseMigrations)



# Apply database migrations (/api/dev/database/uploadDatabaseMigrations)



# API Reference (/api/dev)

<Component type="info" title="Version dev">
This reference is generated from the OpenAPI spec. Endpoints and schemas on this page match this version.
</Component>

## Base URL [#base-url]

All endpoints are rooted at `/api/v1`.

```bash
curl "$OMNIBASE_URL/api/v1/tenants" \
  -H "Authorization: Bearer $OMNIBASE_TOKEN"
```

Authenticated requests use `Authorization: Bearer <token>`. Tenant-scoped requests can use the tenant JWT returned when a tenant is created.

## Resources [#resources]

<Component>
<Component href="./auth" title="Auth">
Sessions, identities, and tenant switching
</Component>

<Component href="./configuration" title="Configuration">
Database migrations, email templates, and Stripe config
</Component>

<Component href="./database" title="Database">
Migration status and database type generation
</Component>

<Component href="./permissions" title="Permissions">
Relationship-based access control checks
</Component>

<Component href="./storage" title="Storage">
File uploads, downloads, and object visibility
</Component>

<Component href="./stripe" title="Stripe">
Products, prices, meters, and webhook configuration
</Component>

<Component href="./tenants" title="Tenants">
Tenants, roles, subscriptions, and invitations
</Component>
</Component>

# Check permission (/api/dev/permissions/checkPermission)



# Create relationship (/api/dev/permissions/createRelationship)



# Delete relationship (/api/dev/permissions/deleteRelationship)



# Permissions (/api/dev/permissions)

## Permissions endpoints [#permissions-endpoints]

- [Check permission](./checkPermission)
- [Create relationship](./createRelationship)
- [Delete relationship](./deleteRelationship)

# Delete file from storage (/api/dev/storage/deleteObject)



# Download file from storage (/api/dev/storage/downloadFile)



# Get temporary S3 credentials (/api/dev/storage/getStorageCredentials)



# Storage (/api/dev/storage)

## Storage endpoints [#storage-endpoints]

- [Delete file from storage](./deleteObject)
- [Download file from storage](./downloadFile)
- [Get temporary S3 credentials](./getStorageCredentials)
- [Make a file publicly accessible](./makeFilePublic)
- [Upload file to storage](./uploadFile)

# Make a file publicly accessible (/api/dev/storage/makeFilePublic)



# Upload file to storage (/api/dev/storage/uploadFile)



# Calculate cost for a price (/api/dev/stripe/calculatePriceCost)



# Get meter by ID (/api/dev/stripe/getMeterByID)



# Get price by ID (/api/dev/stripe/getPriceByID)



# Get product by ID (/api/dev/stripe/getProductByID)



# Get public Stripe config (/api/dev/stripe/getStripeConfig)



# Get full Stripe config (admin) (/api/dev/stripe/getStripeConfigAdmin)



# Stripe (/api/dev/stripe)

## Stripe endpoints [#stripe-endpoints]

- [Calculate cost for a price](./calculatePriceCost)
- [Get full Stripe config (admin)](./getStripeConfigAdmin)
- [Get meter by ID](./getMeterByID)
- [Get price by ID](./getPriceByID)
- [Get product by ID](./getProductByID)
- [Get public Stripe config](./getStripeConfig)
- [List all webhooks](./listWebhooks)

# List all webhooks (/api/dev/stripe/listWebhooks)



# Accept a tenant invite (/api/dev/tenants/acceptInvite)



# Create a tenant invite (/api/dev/tenants/createInvite)



# Create a role (/api/dev/tenants/createRole)



# Create a tenant (/api/dev/tenants/createTenant)



# Delete a role (/api/dev/tenants/deleteRole)



# Delete the current tenant (/api/dev/tenants/deleteTenant)



# Get tenant by ID (/api/dev/tenants/getTenantByID)



# Get tenant by Stripe customer ID (/api/dev/tenants/getTenantByStripeCustomerID)



# Tenants (/api/dev/tenants)

## Tenants endpoints [#tenants-endpoints]

- [Accept a tenant invite](./acceptInvite)
- [Create a role](./createRole)
- [Create a tenant](./createTenant)
- [Create a tenant invite](./createInvite)
- [Delete a role](./deleteRole)
- [Delete the current tenant](./deleteTenant)
- [Get tenant by ID](./getTenantByID)
- [Get tenant by Stripe customer ID](./getTenantByStripeCustomerID)
- [List role definitions](./listRoleDefinitions)
- [List roles for the tenant](./listRoles)
- [List users in the tenant](./listTenantUsers)
- [Remove a user from the tenant](./removeTenantUser)
- [Switch the active tenant](./switchActiveTenant)
- [Update a role](./updateRole)
- [Update a tenant user's role](./updateTenantUserRole)

# List role definitions (/api/dev/tenants/listRoleDefinitions)



# List roles for the tenant (/api/dev/tenants/listRoles)



# List users in the tenant (/api/dev/tenants/listTenantUsers)



# Remove a user from the tenant (/api/dev/tenants/removeTenantUser)



# Switch the active tenant (/api/dev/tenants/switchActiveTenant)



# Update a role (/api/dev/tenants/updateRole)



# Update a tenant user's role (/api/dev/tenants/updateTenantUserRole)



# API Changelog (/api)

**Latest: v0.22.2**

[Read the API v0.22.2 docs](/api/0.22.2)

All API releases are listed below, newest first. Each version links to its docs, or to its GitHub release when the docs for that version are no longer published. See the [changelog for every package](/changelog).

## v0.23.0 [#v0230]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.23.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.2...api-v0.23.0)

**Bug Fixes**

* **api:** rewrite proxied auth redirects and forward session token cookie [b0ab2b4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b0ab2b41fbf7b9dfdf8eed48c931970cfc585327)
* **stripe:** recreate price on parent product changes ([#207](https://github.com/PhoenixSolutionsGroup/omnibase/issues/207)) [bc65581](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bc655817c3b6326baac306e81a6759bba53d608d)
* **stripe:** Return 422 when config_id not found instead of 404 [c880b99](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c880b99ebab26ffc5176b0d89b825e2ee31eaed3)
* Update middleware to resolve `omnibase_session_token` cookie [dbafb9e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/dbafb9e468547ef5ab3f28f57418f1098ea55308)

**Features**

* **storage:** fetch short-lived tokens for storage from managed-hosting for non self-hosted apps [b587328](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b5873287723eb132066f243ce4e721acb550a19a)
* **stripe:** accept custom metadata and client_reference_id on create checkout ([#206](https://github.com/PhoenixSolutionsGroup/omnibase/issues/206)) [3e571a6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3e571a6b44208da26165b9af4b0a6bf027e5564c)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* **stripe:** for managed apps proxy stripe requests through managed hosting api [9d969b4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9d969b4304a954a33095b05019376d0d3ca60ce5)
* **stripe:** Use LineItems for Stripe Checkout instead of single PriceID [7b6052d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b6052d02fb24690b2bb3c00fad0e40ccd8b52a7)

## v0.22.2 [#v0222]

[Docs](/api/0.22.2) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.1...api-v0.22.2)

**Bug Fixes**

* **docs:** correct services directory in docs [7f83b9a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7f83b9a2dc971060d937936c3b51b6a781c39e01)

## v0.22.1 [#v0221]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.22.1) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.0...api-v0.22.1)

**Bug Fixes**

* **api:** correct required go version in readme [62c66e6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/62c66e64b303888b32545b6b27d8032fda4268e5)

## v0.22.0 [#v0220]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.22.0) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.21.0...api-v0.22.0)

**Bug Fixes**

* **api:** add idempotency key to meter usage events [04a095f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/04a095fe1624992f8956735d180b9fd031516e52)
* **api:** cancel subscriptions when deleting a tenant [d1bc853](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d1bc8531cb5f8e7e9f8388e0436eda00a44a690f)
* **api:** correct platform fee amounts and invoice fee errors [3522f2d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3522f2d2d8816871088fa187d79522da2d3b1332)
* **api:** count all payment method types in billing status [d3f679f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d3f679f81f2bd65c43f8b0ae6555f1392708fc05)
* **api:** pass Connect account and remove only the matching subscription item [c5a817d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c5a817da72c529937778551b2e880567003cde1c)
* **api:** require idempotency key and block duplicate subscriptions [7bd793c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7bd793c7219d9d8c51c775ad0eeed1c0a3e04bab)
* **api:** restrict checkout to accessible price configs [ea61665](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ea61665ced33596be5b3e9043b73a176db58ebbf)
* **api:** set checkout customer creation only in payment mode [4d16d0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4d16d0e8e4a98cd61d94a33710243e19c379f428)
* **api:** use meter payload keys for usage events [9d594fd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9d594fde78f3f8df9cb9755e0b133979fe14d55d)
* **billing:** verify Stripe price lookup matches config ID [4cdc723](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4cdc723b1c967ca701653fcf580f12a88f661b30)
* **docs:** harden versioning and document API error responses [43957a0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/43957a00915cb71566b42aa6e3a0992fb84b53ff)
* **payments:** resolve stripe customer id from middleware [742b807](https://github.com/PhoenixSolutionsGroup/omnibase/commit/742b8072252c75e343be75aa1809330ba75df3b9)
* reconcile managed stripe webhooks atomically and prune stale endpoints [a7bfd34](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a7bfd34758131cbf86df74fadf796ff2204d2c99)
* restrict invite roles and URLs to prevent owner escalation [e74d7e5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e74d7e5db0ccb7af4fd725747fc01522cf064864)
* send branch id when registering managed webhooks [cebd9b2](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cebd9b2dbba86f92650573bb4906927385cb9cd4)
* **stripe-config:** clear default price before archiving [3669187](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3669187058df070337791487e5010ca9f634a182)
* **stripe-config:** compare status against complete Stripe state [ffbbe8f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ffbbe8f3ab054eba35d0cb0ff56a895696dc44bb)
* **stripe-config:** expand coupon applies_to and list inactive promos [7aec907](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7aec90730538c2b6df5bd4c8410a8abc85474b7d)
* **stripe-config:** only reactivate archived prices that match desired config [31e7934](https://github.com/PhoenixSolutionsGroup/omnibase/commit/31e79344c8e62f51cfe81a5cb0e3e4a9f3104b3b)
* **stripe-config:** only reactivate archived prices that match desired config ([#127](https://github.com/PhoenixSolutionsGroup/omnibase/issues/127)) [8fd3383](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8fd338338b9e5e5af5cbef2e6bf5feff85147a08)
* **stripe-config:** prefer active promotion code when config IDs collide [3d25fd0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3d25fd0d1b977c724b3eb6a83bb604fe5eae562d)
* **stripe-config:** preserve decimal amounts when pulling [1220c3e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1220c3e06c3d4eea59fb3ace14dcee65732bfab4)
* **stripe-config:** reconcile against active Stripe state [bb0240a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb0240a195add2fdc71334f60648c7c160c484fe)
* **stripe-config:** recreate metered prices when their meter is recreated [bb8bff0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb8bff0447983c637e70c6c9f88b778b92a32a98)
* **stripe:** require backend key for convert endpoint and scope to connected account [2ffe550](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ffe55067007c7387a98051c9af0ae929957fb88)
* **stripe:** require backend key for convert endpoint and scope to connected account ([#128](https://github.com/PhoenixSolutionsGroup/omnibase/issues/128)) [fab00e9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/fab00e9aab3e602e7ffed645ef42cca55c8e0568)

**Features**

* **api:** add tenant, system, and email history schema [b3bab23](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b3bab239bab383d697a39c07fcccb7e86d1a7c09)
* **api:** validate required config at startup [cfcd89f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cfcd89f55ca8a8a4aae978980138608e3655b90f)
* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **email:** record delivery history and rate limit sends per tenant [e894528](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e894528e1404d8d6451861943787865f4130b221)
* **email:** scope templates to tenants and split system/send endpoints [ca5c762](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ca5c7622b721af6a2932bdcfc2c6a97900488429)
* **permissions:** add email send and template management permissions [2f2cd52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2f2cd528291ed4e61f0cd71a10230e40ec65e962)
* **permissions:** API owns required namespaces and validates projects [1e94d44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e94d44e4c1837ffb2e1043594e65df1f05fd192)
* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)
* **stripe-config:** add drift status endpoint [8469a31](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8469a31ef4aa6c6d4779942d357c5e35cef2755e)
* **stripe-config:** pull config identities from Stripe tags [419d89e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/419d89e79dc8cdbcdfd8d17b0dd21b9daee836fa)
* **stripe-config:** reconcile managed resources against live Stripe [8cfcc16](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8cfcc16d4d86968c8c69393af40a65789d97ba73)
* **stripe-config:** scope archive-all to managed resources [1367403](https://github.com/PhoenixSolutionsGroup/omnibase/commit/136740362813e551bfdc90902db2671951f84541)
* **stripe-config:** tag managed Stripe objects with config identity [f41d24c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f41d24c778e4446dc34add9ed3ed4e76200aab69)
* support metadata on stripe products and prices [f4cf420](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f4cf420869cdb78411fe384d9c9bc473a22880d1)

## v0.21.0 [#v0210]

[Docs](/api/0.21.0) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.5...api-v0.21.0)

**Bug Fixes**

* **api:** require service key for meter usage recording [e012f4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e012f4adf23a2944c2c5e73ef6a26a9c2b6f8ecf)
* **api:** require service key for permission relationship writes [e369c15](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e369c155d0e6aaa5897f5d28852e8a98affc98a4)
* **auth:** avoid a null SES tenant header [013974b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/013974b6b2ca8c1f5c7d43e5a5a78252b35ca7f6)
* **db:** make RLS helpers SECURITY DEFINER and narrow anon_user grants [471ae36](https://github.com/PhoenixSolutionsGroup/omnibase/commit/471ae36a6419a7d2280fc2f6655d01ad1bbcf79d)

**Features**

* **api:** add app-key user mode [4f39053](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4f390532f6ecbe84b86745ed1fac690abf6a43c1)
* **api:** add tenant permission middleware [7ad856c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7ad856c26b7aa8b7be1cd85aefe8f22e7de8b3be)

## v0.20.5 [#v0205]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.5) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.4...api-v0.20.5)

**Bug Fixes**

* remove set-cookie header rewrite [32f62f1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/32f62f1989b21b51f82d07f26faa5ec3dc2bb5f6)
* skip Origin header [0aac259](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0aac25923a5c5ee5de3f301b4f6fd3506ca00a72)

## v0.20.4 [#v0204]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.4) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.3...api-v0.20.4)

**Bug Fixes**

* **api:** trim whitespace on session token header [17f2c44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/17f2c44c87ecca1a30b0d53d5deff201081a3582)

## v0.20.3 [#v0203]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.3) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.2...api-v0.20.3)

**Bug Fixes**

* retry migrations on connection failures (for scale-to-zero) [4b4e80b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4b4e80bed67a3fef233616f57c5260932315b67b)

## v0.20.2 [#v0202]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.2) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.1...api-v0.20.2)

**Bug Fixes**

* ensure /tmp dir in Dockerfile [926434f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/926434f9a78630bde5317a3ca16b9c2d7e991860)

## v0.20.1 [#v0201]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.0...api-v0.20.1)

**Bug Fixes**

* add ApiServiceKey environment variable [9e0d81a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9e0d81a25f85365978ab54801c4ef11f82410d42)
* Add Service Key to docker-compose and tests [f98fdd5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f98fdd5e5b6242c4c4041cb29ea890785ad8259c)
* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)

## v0.20.0 [#v0200]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.0) · 2026-07-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.19.1...api-v0.20.0)

**Bug Fixes**

* **api:** parse_permission caser data race under concurrent load [daa5c10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/daa5c101b9e1806dc203e3b90924efe5d0a352e9)
* **api:** perf tests missing required tenant type field [6aa8f13](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6aa8f1329a9bb29b7a723d64fff9e3e882e07982)
* **release:** pass API_VERSION through prepare + drop deleted spec asset refs [88c4426](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88c44261bae76095616304651fe6798c6c386b39)

**Features**

* **api:** add handlers/ctx helpers and slim responses [4128c98](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4128c98fdf7e0db7fc7fd5255a8757b71d61db75)
* **api:** add services/auth (kratos identity + metadata) [003bea5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/003bea578dfa62346126cfb25320c8ec02896246)
* **api:** add services/email (SMTP send with template) [88a8a87](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88a8a877423e81e8bb1b02f8bdda9932815616c1)
* **api:** add services/permissions and rbac [ac05573](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ac055734ee209fba8cc27b5cdbbe37c9d1fc81e6)
* **api:** add services/tenants (JWT, active tenant, cleanup) [ec74e4e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ec74e4e01bf8dc28d9b064baeefe4afdca689c56)
* **api:** add sqlc queries and generated repository [b2ac570](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b2ac570f169e60dc3ed16d334f37365d2f31b52d)
* **api:** collapse stripe_config pyramid into services/stripe_config [641c888](https://github.com/PhoenixSolutionsGroup/omnibase/commit/641c888ef1287d95638dfaf745c26b7b385f2b10)
* **api:** port db/payments/permissions/stripe sub-packages to huma [c75fbf3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c75fbf3e8cc4d53956ac510d34ac23f5c084eb08)
* **api:** port email + storage sub-packages to huma [3a4a2e7](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3a4a2e79a428d12fe8d047a0ad960823c0d8563a)
* **api:** port full auth sub-package to huma [a139cb5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a139cb52bd2b341e63942a2b376dd5f72655b909)
* **api:** port tenants/ sub-package to huma [121ea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/121ea9de25d960da7682eb67d3938be9439060f6)
* **api:** port whoami to huma + introduce AuthCtx resolver [8dcf4bf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8dcf4bf27cfbab8a8cab0b5e7a0c144c14b1a130)
* **api:** wire SDK gen from huma spec + split tenants tag + API_VERSION env [bd7fcdc](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bd7fcdc0e5eb7e7591aff834950ea383490063d2)
* Prisma Schema + Down Migrations + definePolicy RLS Compiler [2120c4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2120c4a1842bdf50efc17e741a5f638c3b633903)

## v0.19.1 [#v0191]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.19.1) · 2026-06-03 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.19.0...api-v0.19.1)

**Bug Fixes**

* make /health/ready checks accurate and concurrent [0973b2d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0973b2db81f6c01ab23d6fdd3ff214d101464c8e)

## v0.19.0 [#v0190]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.19.0) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.18.1...api-v0.19.0)

**Bug Fixes**

* **api:** add CORS_ALLOWED_ORIGINS to compose and drop typegen from readiness [2357c97](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2357c978237430b545eb116e23eab9c9989a67a0)
* **api:** handle FK violations, SELinux mounts, and contract test gaps [7686e20](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7686e2052d7cd275076a18844d3df88c52da39e6)
* **api:** require explicit CORS origin whitelist [9cecce6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9cecce6a4c1065a560689e6e272ab30ece121d94)
* **api:** restrict X-Stripe-Customer-Id header to service key auth [64a46bf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64a46bfeb5802ef541b2e88aad8e2221085ad00f)
* **api:** return 400 for Stripe client errors in RecordUsage [2b500c5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b500c578a461750cdd72e7c4de90326ec488733)
* **api:** use constant-time comparison for service key validation [ad7e949](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ad7e949c1daf6ba06d9f3610fb2e38f8645bd331)
* retry db connections [5bbfbcf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5bbfbcfe88f85daa9f8d24e19256998557edb7c4)

**Features**

* **api:** add make-public endpoint and object ID to OpenAPI spec [ba95243](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ba9524319ac03062a16770db8db1c7494c0b67a6)
* **api:** replace PostgREST storage with Keto per-object permissions [25f3b90](https://github.com/PhoenixSolutionsGroup/omnibase/commit/25f3b90fb832b06a0d1bd0968b771396d2b25a6b)
* mcp server [52f2a74](https://github.com/PhoenixSolutionsGroup/omnibase/commit/52f2a741476cefaf6f00be9ed892020056fb8216)

## v0.18.1 [#v0181]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.18.1) · 2026-02-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.18.0...api-v0.18.1)

**Bug Fixes**

* **api:** update webhook registration to use managed hosting registration ID [d6f29d1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d6f29d1ba33a05bccb7a637267c12a51a7391c7d)

## v0.18.0 [#v0180]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.18.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.17.0...api-v0.18.0)

**Bug Fixes**

* **api:** ensure roles array is never null in API response [f359f0c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f359f0cd90eae9de5f46303581b93e8a467ee2da)
* **api:** use JSDoc [@role](https://github.com/role) annotations for role template creation [8c06504](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8c065041a6f75f73eb235fa5e490be0deaff9610)

**Features**

* **api:** add JSDoc metadata parsing for permission relations [6ad5a80](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ad5a8083f21672a02f76c9091c0b82f2f585921)

## v0.17.0 [#v0170]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.17.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.16.0...api-v0.17.0)

**Features**

* **release:** auto-sync docker image versions to CLI on release [505ed28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/505ed28851e452b70f6a698d331e11134d05dd08)

## v0.16.0 [#v0160]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.16.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.15.0...api-v0.16.0)

**Bug Fixes**

* **api:** use Kratos API for tenant users instead of direct DB join [e11b2af](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e11b2af9be69e0f58c01786bad50f0ccebe47152)

**Features**

* **api:** add storage service to health check [47e7047](https://github.com/PhoenixSolutionsGroup/omnibase/commit/47e704748188ca112867afbcf8825cccf8d4f116)

## v0.15.0 [#v0150]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.15.0) · 2026-01-18 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.14.0...api-v0.15.0)

**Features**

* **api:** add tenant type support (organization/individual) [9ba2615](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9ba261518275a382a13afc8baf0c231e4395f6e2)

## v0.14.0 [#v0140]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.14.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.13.0...api-v0.14.0)

**Features**

* **api:** add Cloud Run identity token auth for Ory services [5daaf2e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5daaf2e13e2aab1731f3f9137b75272301c8ce69)
* **api:** add price calculation endpoint for usage cost estimation [c63b46f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c63b46ffac54424815e963585f8bfaf4d43d331e)
* **api:** add price cost calculation endpoint [2831d6c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2831d6c223629dfc06a18a11a6be37783f915d6d)

## v0.13.0 [#v0130]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.13.0) · 2026-01-13 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.6...api-v0.13.0)

**Bug Fixes**

* **api:** add pattern validation to typegen schemas parameter [378418b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/378418ba1aad76fbf63e5f1608ff20b95d12f5bd)
* **api:** handle missing products gracefully in archive operation [d2cb08b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2cb08bf008140e0b6e7934692fbc24b79bd81f3)
* **api:** include all stripe IDs in config response [20fdf21](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20fdf213968d187b24b4e0b01edaf3aef7b3bc4e)
* **api:** rewrite Location and Set-Cookie headers in auth proxy [6f81cdf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6f81cdf773a2f25b23aaedc832958da83e9f3217)

**Features**

* **api:** add comprehensive health ready endpoint [c01cf28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c01cf282b74d6ddfc8ad9d211a6489d1c320c7d9)
* **api:** add database typegen endpoint [4346e04](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4346e04bcc16a3a9543275081e9b54bb2fc98c57)
* **api:** add enterprise pricing support [839ef19](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839ef19056587801c47de72501c52888879967d1)
* **api:** add postgrest and typegen to health ready check [2540408](https://github.com/PhoenixSolutionsGroup/omnibase/commit/254040818387ee71516421efa4c304a7247194da)
* **api:** add stripe coupons and promotion codes support [9876ddf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9876ddfe15f7eff02a1ca68e5b797b39a0c4242b)

## v0.12.6 [#v0126]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.6) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.5...api-v0.12.6)

**Bug Fixes**

* **ci:** update git-user-id to phoenixsolutionsgroup from PhoenixSolutionsGroup for go package [a2f7c3e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a2f7c3e148f91b16ffa8cf15b703137af8f9fb1f)

## v0.12.5 [#v0125]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.5) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.4...api-v0.12.5)

**Bug Fixes**

* **release:** stage SDK files explicitly in prepare script [c7cdc4d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c7cdc4d2475b8f255c592ed0826ba3108304a1b2)

## v0.12.4 [#v0124]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.4) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.3...api-v0.12.4)

**Bug Fixes**

* **ci:** api redeploy [add8bee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/add8bee2728d92a6669d9fd416acdd5b3f785cc5)

## v0.12.3 [#v0123]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.3) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.2...api-v0.12.3)

**Bug Fixes**

* **cli:** add test mode and refactor docker compose to base + override pattern [713b302](https://github.com/PhoenixSolutionsGroup/omnibase/commit/713b3021f0f60d3b589afc38c12f0bc154674cdd)

## v0.12.2 [#v0122]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.2) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.1...api-v0.12.2)

**Bug Fixes**

* **release:** include generated SDK files in release commit [41e87f5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/41e87f570c313eb674054da73e57a0273020ed05)

## v0.12.1 [#v0121]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.1) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.0...api-v0.12.1)

**Bug Fixes**

* **release:** add package.json for Go projects [829ab1c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/829ab1c26705b28cf970dce475ed942aa152c83d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)

## v0.12.0 [#v0120]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.0) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.11.0...api-v0.12.0)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **api:** add tenant lookup endpoints [64d9850](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64d98500ba1a583d7bd40d8509d00c88ac50bbe6)

## v0.11.0 [#v0110]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.11.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.10.2...api-v0.11.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)

# Changelog (/changelog)

Every release of the API, CLI, SDKs, and the auth and permissions services, newest first. Pin service versions with `[versions]` in `omnibase.toml`.

## API v0.23.0 [#api-v0230]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.23.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.2...api-v0.23.0)

**Bug Fixes**

* **api:** rewrite proxied auth redirects and forward session token cookie [b0ab2b4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b0ab2b41fbf7b9dfdf8eed48c931970cfc585327)
* **stripe:** recreate price on parent product changes ([#207](https://github.com/PhoenixSolutionsGroup/omnibase/issues/207)) [bc65581](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bc655817c3b6326baac306e81a6759bba53d608d)
* **stripe:** Return 422 when config_id not found instead of 404 [c880b99](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c880b99ebab26ffc5176b0d89b825e2ee31eaed3)
* Update middleware to resolve `omnibase_session_token` cookie [dbafb9e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/dbafb9e468547ef5ab3f28f57418f1098ea55308)

**Features**

* **storage:** fetch short-lived tokens for storage from managed-hosting for non self-hosted apps [b587328](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b5873287723eb132066f243ce4e721acb550a19a)
* **stripe:** accept custom metadata and client_reference_id on create checkout ([#206](https://github.com/PhoenixSolutionsGroup/omnibase/issues/206)) [3e571a6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3e571a6b44208da26165b9af4b0a6bf027e5564c)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* **stripe:** for managed apps proxy stripe requests through managed hosting api [9d969b4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9d969b4304a954a33095b05019376d0d3ca60ce5)
* **stripe:** Use LineItems for Stripe Checkout instead of single PriceID [7b6052d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b6052d02fb24690b2bb3c00fad0e40ccd8b52a7)
## CLI v0.13.0 [#cli-v0130]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.13.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.12.0...cli-v0.13.0)

**Bug Fixes**

* **api:** renumber email migrations after main [d7934ff](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d7934ff3adfb58b66d4214437611334042700585)
* better error message when local isn't running [acd5667](https://github.com/PhoenixSolutionsGroup/omnibase/commit/acd56677ce9737e0749f5c9084fc13fa398774ff)
* **cli:** merge coupons and promotion codes from config files [af2b76f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/af2b76fe98211b16b01e3a31dc5a76d0286cf3bf)
* **cli:** reject unresolved webhook URLs consistently [f202967](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f202967e1bb02a992300ef00c5a96967c7a199fd)
* **deployments:** remove deployments name defaulting to 'default' [c580a32](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c580a3237fab66dabad0fb3f8da14692bc3a2769)
* **deployments:** use \<slug\>.omnibase-workers.app instead of \<slug\>.workers.omnibase.tech [15fe9ac](https://github.com/PhoenixSolutionsGroup/omnibase/commit/15fe9ac1b1ae42436e2bd40e77ba9b5c4e35842d)
* no console logs until omnibase starts [0e58920](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0e5892093f7e56640a8d2a3706eefa02fa161fd6)
* **payments:** add manage_billing permission [f85e692](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f85e6922f57d831dfbebde5025bd7bd97494b686)
* restrict invite roles and URLs to prevent owner escalation [e74d7e5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e74d7e5db0ccb7af4fd725747fc01522cf064864)
* **sdk:** stop tracking core-js dist and build packages before dependents [6d04e5e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6d04e5e459c905a711e6aa1ae971ea1f6360bf1e)
* update cli to use new provision args [1adec91](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1adec910d9d6e2fad4ec7b013dc2b966b257dcb5)

**Features**

* AGENTS.md file [7199fc0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7199fc0fe57d887fe6c6106bccc59cb77f1e6bb2)
* **api:** add tenant, system, and email history schema [b3bab23](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b3bab239bab383d697a39c07fcccb7e86d1a7c09)
* **api:** validate required config at startup [cfcd89f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cfcd89f55ca8a8a4aae978980138608e3655b90f)
* **cli:** add docs commands backed by static llms routes [956c7b3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/956c7b3876a02282b4b832003585b42c94b34328)
* **cli:** add stripe status command [e7a6b60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e7a6b60f30db4649467b03a54fb97c546e82affb)
* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **cli:** print a service and deployment URL summary after start [2705ad4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2705ad473167d249702ffb515f83907224d07673)
* **cli:** run start in the foreground, add -d for detached mode [f7c892a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f7c892acfc9ea96b1051af2238b73145775dde94)
* **email:** record delivery history and rate limit sends per tenant [e894528](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e894528e1404d8d6451861943787865f4130b221)
* **permissions:** add email send and template management permissions [2f2cd52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2f2cd528291ed4e61f0cd71a10230e40ec65e962)
* **permissions:** API owns required namespaces and validates projects [1e94d44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e94d44e4c1837ffb2e1043594e65df1f05fd192)
* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)
* **stripe-config:** scope archive-all to managed resources [1367403](https://github.com/PhoenixSolutionsGroup/omnibase/commit/136740362813e551bfdc90902db2671951f84541)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* support metadata on stripe products and prices [f4cf420](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f4cf420869cdb78411fe384d9c9bc473a22880d1)
## Next.js v0.10.0 [#nextjs-v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.10.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.9.1...nextjs-v0.10.0)

**Bug Fixes**

* **auth:** Logout removes `omnibase_session_token` instead of legacy `ory_*` [5a1652e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5a1652efef67754aecf976809fe54b57bb850d64)

**Features**

* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)
## Shadcn v0.10.0 [#shadcn-v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.10.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.9.1...shadcn-v0.10.0)

**Bug Fixes**

* dark mode auth page [ff1cef5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ff1cef5439e82b44dab227e1399ad4de6af406b6)
* tenant-switch bg color [39720ed](https://github.com/PhoenixSolutionsGroup/omnibase/commit/39720ed25cce38d8650d029fd31f0cfba5529c2a)

**Features**

* add icons to oidc [5a875d0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5a875d053aef58ee51829c38db99d501d23e4e3e)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* update colors to unify [265717b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/265717b56106f9e25ca57256c5bd8e39196e54ce)
* update registration form [0e66195](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0e661956c7b500691660358dda5e93a817788af5)
* update sdk button and card ui [2cdd899](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2cdd8995281256df1b01ba2d627925012624764b)
* update tenant select sdk ui [d8a580c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d8a580c2e5b3f6301656f2087a66e080d744a156)
## Permissions v0.6.0 [#permissions-v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.6.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.5.0...permissions-v0.6.0)

**Features**

* **storage:** fetch short-lived tokens for storage from managed-hosting for non self-hosted apps [b587328](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b5873287723eb132066f243ce4e721acb550a19a)
## API v0.22.2 [#api-v0222]

[Docs](/api/0.22.2) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.1...api-v0.22.2)

**Bug Fixes**

* **docs:** correct services directory in docs [7f83b9a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7f83b9a2dc971060d937936c3b51b6a781c39e01)
## API v0.22.1 [#api-v0221]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.22.1) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.22.0...api-v0.22.1)

**Bug Fixes**

* **api:** correct required go version in readme [62c66e6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/62c66e64b303888b32545b6b27d8032fda4268e5)
## API v0.22.0 [#api-v0220]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.22.0) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.21.0...api-v0.22.0)

**Bug Fixes**

* **api:** add idempotency key to meter usage events [04a095f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/04a095fe1624992f8956735d180b9fd031516e52)
* **api:** cancel subscriptions when deleting a tenant [d1bc853](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d1bc8531cb5f8e7e9f8388e0436eda00a44a690f)
* **api:** correct platform fee amounts and invoice fee errors [3522f2d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3522f2d2d8816871088fa187d79522da2d3b1332)
* **api:** count all payment method types in billing status [d3f679f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d3f679f81f2bd65c43f8b0ae6555f1392708fc05)
* **api:** pass Connect account and remove only the matching subscription item [c5a817d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c5a817da72c529937778551b2e880567003cde1c)
* **api:** require idempotency key and block duplicate subscriptions [7bd793c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7bd793c7219d9d8c51c775ad0eeed1c0a3e04bab)
* **api:** restrict checkout to accessible price configs [ea61665](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ea61665ced33596be5b3e9043b73a176db58ebbf)
* **api:** set checkout customer creation only in payment mode [4d16d0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4d16d0e8e4a98cd61d94a33710243e19c379f428)
* **api:** use meter payload keys for usage events [9d594fd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9d594fde78f3f8df9cb9755e0b133979fe14d55d)
* **billing:** verify Stripe price lookup matches config ID [4cdc723](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4cdc723b1c967ca701653fcf580f12a88f661b30)
* **docs:** harden versioning and document API error responses [43957a0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/43957a00915cb71566b42aa6e3a0992fb84b53ff)
* **payments:** resolve stripe customer id from middleware [742b807](https://github.com/PhoenixSolutionsGroup/omnibase/commit/742b8072252c75e343be75aa1809330ba75df3b9)
* reconcile managed stripe webhooks atomically and prune stale endpoints [a7bfd34](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a7bfd34758131cbf86df74fadf796ff2204d2c99)
* restrict invite roles and URLs to prevent owner escalation [e74d7e5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e74d7e5db0ccb7af4fd725747fc01522cf064864)
* send branch id when registering managed webhooks [cebd9b2](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cebd9b2dbba86f92650573bb4906927385cb9cd4)
* **stripe-config:** clear default price before archiving [3669187](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3669187058df070337791487e5010ca9f634a182)
* **stripe-config:** compare status against complete Stripe state [ffbbe8f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ffbbe8f3ab054eba35d0cb0ff56a895696dc44bb)
* **stripe-config:** expand coupon applies_to and list inactive promos [7aec907](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7aec90730538c2b6df5bd4c8410a8abc85474b7d)
* **stripe-config:** only reactivate archived prices that match desired config [31e7934](https://github.com/PhoenixSolutionsGroup/omnibase/commit/31e79344c8e62f51cfe81a5cb0e3e4a9f3104b3b)
* **stripe-config:** only reactivate archived prices that match desired config ([#127](https://github.com/PhoenixSolutionsGroup/omnibase/issues/127)) [8fd3383](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8fd338338b9e5e5af5cbef2e6bf5feff85147a08)
* **stripe-config:** prefer active promotion code when config IDs collide [3d25fd0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3d25fd0d1b977c724b3eb6a83bb604fe5eae562d)
* **stripe-config:** preserve decimal amounts when pulling [1220c3e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1220c3e06c3d4eea59fb3ace14dcee65732bfab4)
* **stripe-config:** reconcile against active Stripe state [bb0240a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb0240a195add2fdc71334f60648c7c160c484fe)
* **stripe-config:** recreate metered prices when their meter is recreated [bb8bff0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb8bff0447983c637e70c6c9f88b778b92a32a98)
* **stripe:** require backend key for convert endpoint and scope to connected account [2ffe550](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ffe55067007c7387a98051c9af0ae929957fb88)
* **stripe:** require backend key for convert endpoint and scope to connected account ([#128](https://github.com/PhoenixSolutionsGroup/omnibase/issues/128)) [fab00e9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/fab00e9aab3e602e7ffed645ef42cca55c8e0568)

**Features**

* **api:** add tenant, system, and email history schema [b3bab23](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b3bab239bab383d697a39c07fcccb7e86d1a7c09)
* **api:** validate required config at startup [cfcd89f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cfcd89f55ca8a8a4aae978980138608e3655b90f)
* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **email:** record delivery history and rate limit sends per tenant [e894528](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e894528e1404d8d6451861943787865f4130b221)
* **email:** scope templates to tenants and split system/send endpoints [ca5c762](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ca5c7622b721af6a2932bdcfc2c6a97900488429)
* **permissions:** add email send and template management permissions [2f2cd52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2f2cd528291ed4e61f0cd71a10230e40ec65e962)
* **permissions:** API owns required namespaces and validates projects [1e94d44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e94d44e4c1837ffb2e1043594e65df1f05fd192)
* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)
* **stripe-config:** add drift status endpoint [8469a31](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8469a31ef4aa6c6d4779942d357c5e35cef2755e)
* **stripe-config:** pull config identities from Stripe tags [419d89e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/419d89e79dc8cdbcdfd8d17b0dd21b9daee836fa)
* **stripe-config:** reconcile managed resources against live Stripe [8cfcc16](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8cfcc16d4d86968c8c69393af40a65789d97ba73)
* **stripe-config:** scope archive-all to managed resources [1367403](https://github.com/PhoenixSolutionsGroup/omnibase/commit/136740362813e551bfdc90902db2671951f84541)
* **stripe-config:** tag managed Stripe objects with config identity [f41d24c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f41d24c778e4446dc34add9ed3ed4e76200aab69)
* support metadata on stripe products and prices [f4cf420](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f4cf420869cdb78411fe384d9c9bc473a22880d1)
## Auth v0.5.0 [#auth-v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.5.0) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.4.4...auth-v0.5.0)

**Features**

* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **email:** scope templates to tenants and split system/send endpoints [ca5c762](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ca5c7622b721af6a2932bdcfc2c6a97900488429)
## Permissions v0.5.0 [#permissions-v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.5.0) · 2026-11-19 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.4.0...permissions-v0.5.0)

**Features**

* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **permissions:** add email send and template management permissions [2f2cd52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2f2cd528291ed4e61f0cd71a10230e40ec65e962)
* **permissions:** API owns required namespaces and validates projects [1e94d44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e94d44e4c1837ffb2e1043594e65df1f05fd192)
## API v0.21.0 [#api-v0210]

[Docs](/api/0.21.0) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.5...api-v0.21.0)

**Bug Fixes**

* **api:** require service key for meter usage recording [e012f4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e012f4adf23a2944c2c5e73ef6a26a9c2b6f8ecf)
* **api:** require service key for permission relationship writes [e369c15](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e369c155d0e6aaa5897f5d28852e8a98affc98a4)
* **auth:** avoid a null SES tenant header [013974b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/013974b6b2ca8c1f5c7d43e5a5a78252b35ca7f6)
* **db:** make RLS helpers SECURITY DEFINER and narrow anon_user grants [471ae36](https://github.com/PhoenixSolutionsGroup/omnibase/commit/471ae36a6419a7d2280fc2f6655d01ad1bbcf79d)

**Features**

* **api:** add app-key user mode [4f39053](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4f390532f6ecbe84b86745ed1fac690abf6a43c1)
* **api:** add tenant permission middleware [7ad856c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7ad856c26b7aa8b7be1cd85aefe8f22e7de8b3be)
## CLI v0.12.0 [#cli-v0120]

[Docs](/cli/0.12.0) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.11.0...cli-v0.12.0)

**Bug Fixes**

* **cli:** restart permissions [64b799e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64b799eec257c243a0bd6e5e14757d67b47f0b09)
* **db:** make RLS helpers SECURITY DEFINER and narrow anon_user grants [471ae36](https://github.com/PhoenixSolutionsGroup/omnibase/commit/471ae36a6419a7d2280fc2f6655d01ad1bbcf79d)
* **db:** move pg_trgm to the auth schema [5e3f0fa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5e3f0fa36222751c85a8e0955d156d4a25ed33f9)
* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)
* upload database migrations as files [78fb155](https://github.com/PhoenixSolutionsGroup/omnibase/commit/78fb1552cd9642f0d8e225d6dc4f20f3607fa32d)
* upload permissions archive as a file [d3dbf52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d3dbf5274b0cc1b5765994de597524531ffa7623)

**Features**

* add preview branch CLI commands [fbd41ca](https://github.com/PhoenixSolutionsGroup/omnibase/commit/fbd41ca089656d6aa6b3f2e0ff2b2852777924dd)
* **api:** add app-key user mode [4f39053](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4f390532f6ecbe84b86745ed1fac690abf6a43c1)
* **cli:** emit table GRANT/REVOKE from RLS policy codegen [aad95ce](https://github.com/PhoenixSolutionsGroup/omnibase/commit/aad95ce790608c5ab110bc95a2d08d3460410872)
## Next.js v0.9.1 [#nextjs-v091]

[Docs](/nextjs/0.9.1) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.9.0...nextjs-v0.9.1)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)
## React v0.3.7 [#react-v037]

[Docs](/react/0.3.7) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.6...react-v0.3.7)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)
## Shadcn v0.9.1 [#shadcn-v091]

[Docs](/shadcn/0.9.1) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.9.0...shadcn-v0.9.1)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)
## Auth v0.4.4 [#auth-v044]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.4.4) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.4.3...auth-v0.4.4)

**Bug Fixes**

* **auth:** avoid a null SES tenant header [013974b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/013974b6b2ca8c1f5c7d43e5a5a78252b35ca7f6)
## API v0.20.5 [#api-v0205]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.5) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.4...api-v0.20.5)

**Bug Fixes**

* remove set-cookie header rewrite [32f62f1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/32f62f1989b21b51f82d07f26faa5ec3dc2bb5f6)
* skip Origin header [0aac259](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0aac25923a5c5ee5de3f301b4f6fd3506ca00a72)
## CLI v0.11.0 [#cli-v0110]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.11.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.10.0...cli-v0.11.0)

**Bug Fixes**

* **cli:** don't fall back to .env.local for branch env resolution [8f867af](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8f867afd39b2dcd5cb0f4c07661af77b3f8db854)
* **cli:** resolve bundle entry file [948ee57](https://github.com/PhoenixSolutionsGroup/omnibase/commit/948ee571217a7d0fcb579ae99099ae736a90613b)

**Features**

* add domain to workers [f296668](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f2966681a7ab4eb4f9d3692b2414d15e39f83cb8)
* **cli:** inject branch env into worker builds, vars and env push [ae3c1e2](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ae3c1e23827a6ba2637918d96ede3ca953fb3d62)
* **cli:** load per-branch env files for config resolution [d82ad45](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d82ad45681c0252e5b2dcb285a348fa4c6ffe66a)
* **cli:** resolve branch env for omnibase start dev servers [714f683](https://github.com/PhoenixSolutionsGroup/omnibase/commit/714f6836f16bfe3c3f526c84f9e2d7936a147786)
## Next.js v0.9.0 [#nextjs-v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.9.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.4...nextjs-v0.9.0)

**Features**

* **nextjs:** support custom cookie domain for session token exchange [35cafd4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35cafd403f5de28bf9d0a76c8ff958fbebe157d2)
## Shadcn v0.9.0 [#shadcn-v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.9.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.2...shadcn-v0.9.0)

**Features**

* add "tree" mode for role-creator [88fa038](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88fa038df6c59dd5a4bc60380363015ee3f02818)
## Auth v0.4.3 [#auth-v043]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.4.3) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.4.2...auth-v0.4.3)

**Bug Fixes**

* **auth:** pass kratos config via env, not -c [b9d794e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b9d794e899d6310c7c128f1a83b55c776f0e3516)
* **auth:** retry template downloads on startup [11097e1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/11097e1d2d036976baf6321f81a8ea38c4cad9ed)
## API v0.20.4 [#api-v0204]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.4) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.3...api-v0.20.4)

**Bug Fixes**

* **api:** trim whitespace on session token header [17f2c44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/17f2c44c87ecca1a30b0d53d5deff201081a3582)
## CLI v0.10.0 [#cli-v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.10.0) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.9.0...cli-v0.10.0)

**Bug Fixes**

* **cli:** skip empty allowed return urls entries [7f51ff9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7f51ff9d3e25eb62c774d3232dc1cb721558fad9)

**Features**

* **cli:** Application version pinning [5ebd13b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5ebd13bc12562bf3f54bdcfb306a785b0452cfce)
## Next.js v0.8.4 [#nextjs-v084]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.4) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.3...nextjs-v0.8.4)

**Bug Fixes**

* **nextjs:** guard against empty session exchange codes [555e655](https://github.com/PhoenixSolutionsGroup/omnibase/commit/555e655a1afdb8bd015f8c8908dd29354cba4565)
## Shadcn v0.8.2 [#shadcn-v082]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.2) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.1...shadcn-v0.8.2)

**Bug Fixes**

* **shadcn:** trim identifier before password login [d928ae6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d928ae628db527ff20d698ec1c7f9ebdbae1f253)
## Auth v0.4.2 [#auth-v042]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.4.2) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.4.1...auth-v0.4.2)

**Bug Fixes**

* **auth:** trim whitespace on allowed return urls env [87530a2](https://github.com/PhoenixSolutionsGroup/omnibase/commit/87530a20db5b2ca38530b5ef4eac56159ed8b007)
## CLI v0.9.0 [#cli-v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.9.0) · 2026-08-25 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.8.1...cli-v0.9.0)

**Features**

* **cli:** drive local and cloud config from omnibase.toml [0b19bc4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0b19bc4c1f0c2188cfc6f9ba31b7f9eefdbda7aa)
## API v0.20.3 [#api-v0203]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.3) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.2...api-v0.20.3)

**Bug Fixes**

* retry migrations on connection failures (for scale-to-zero) [4b4e80b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4b4e80bed67a3fef233616f57c5260932315b67b)
## API v0.20.2 [#api-v0202]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.2) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.1...api-v0.20.2)

**Bug Fixes**

* ensure /tmp dir in Dockerfile [926434f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/926434f9a78630bde5317a3ca16b9c2d7e991860)
## API v0.20.1 [#api-v0201]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.20.0...api-v0.20.1)

**Bug Fixes**

* add ApiServiceKey environment variable [9e0d81a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9e0d81a25f85365978ab54801c4ef11f82410d42)
* Add Service Key to docker-compose and tests [f98fdd5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f98fdd5e5b6242c4c4041cb29ea890785ad8259c)
* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)
## CLI v0.8.1 [#cli-v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.8.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.8.0...cli-v0.8.1)

No user-facing changes.
## CLI v0.8.0 [#cli-v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.8.0) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.7.0...cli-v0.8.0)

**Bug Fixes**

* Add Service Key to docker-compose and tests [f98fdd5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f98fdd5e5b6242c4c4041cb29ea890785ad8259c)
* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)

**Features**

* **cli:** enhance worker deployment options [c655f25](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c655f25ca2c34b8b0b8c415637e83a2af603b900)
## Next.js v0.8.3 [#nextjs-v083]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.3) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.2...nextjs-v0.8.3)

**Bug Fixes**

* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)
## Shadcn v0.8.1 [#shadcn-v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.0...shadcn-v0.8.1)

**Bug Fixes**

* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)
## API v0.20.0 [#api-v0200]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.20.0) · 2026-07-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.19.1...api-v0.20.0)

**Bug Fixes**

* **api:** parse_permission caser data race under concurrent load [daa5c10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/daa5c101b9e1806dc203e3b90924efe5d0a352e9)
* **api:** perf tests missing required tenant type field [6aa8f13](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6aa8f1329a9bb29b7a723d64fff9e3e882e07982)
* **release:** pass API_VERSION through prepare + drop deleted spec asset refs [88c4426](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88c44261bae76095616304651fe6798c6c386b39)

**Features**

* **api:** add handlers/ctx helpers and slim responses [4128c98](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4128c98fdf7e0db7fc7fd5255a8757b71d61db75)
* **api:** add services/auth (kratos identity + metadata) [003bea5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/003bea578dfa62346126cfb25320c8ec02896246)
* **api:** add services/email (SMTP send with template) [88a8a87](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88a8a877423e81e8bb1b02f8bdda9932815616c1)
* **api:** add services/permissions and rbac [ac05573](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ac055734ee209fba8cc27b5cdbbe37c9d1fc81e6)
* **api:** add services/tenants (JWT, active tenant, cleanup) [ec74e4e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ec74e4e01bf8dc28d9b064baeefe4afdca689c56)
* **api:** add sqlc queries and generated repository [b2ac570](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b2ac570f169e60dc3ed16d334f37365d2f31b52d)
* **api:** collapse stripe_config pyramid into services/stripe_config [641c888](https://github.com/PhoenixSolutionsGroup/omnibase/commit/641c888ef1287d95638dfaf745c26b7b385f2b10)
* **api:** port db/payments/permissions/stripe sub-packages to huma [c75fbf3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c75fbf3e8cc4d53956ac510d34ac23f5c084eb08)
* **api:** port email + storage sub-packages to huma [3a4a2e7](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3a4a2e79a428d12fe8d047a0ad960823c0d8563a)
* **api:** port full auth sub-package to huma [a139cb5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a139cb52bd2b341e63942a2b376dd5f72655b909)
* **api:** port tenants/ sub-package to huma [121ea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/121ea9de25d960da7682eb67d3938be9439060f6)
* **api:** port whoami to huma + introduce AuthCtx resolver [8dcf4bf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8dcf4bf27cfbab8a8cab0b5e7a0c144c14b1a130)
* **api:** wire SDK gen from huma spec + split tenants tag + API_VERSION env [bd7fcdc](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bd7fcdc0e5eb7e7591aff834950ea383490063d2)
* Prisma Schema + Down Migrations + definePolicy RLS Compiler [2120c4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2120c4a1842bdf50efc17e741a5f638c3b633903)
## CLI v0.7.0 [#cli-v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.7.0) · 2026-07-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.6.0...cli-v0.7.0)

**Bug Fixes**

* **cli:** drop legacy data envelope, SDK responses are unwrapped [0783815](https://github.com/PhoenixSolutionsGroup/omnibase/commit/07838150f160759aee49db273f79296ef45260da)

**Features**

* **api:** wire SDK gen from huma spec + split tenants tag + API_VERSION env [bd7fcdc](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bd7fcdc0e5eb7e7591aff834950ea383490063d2)
* Prisma Schema + Down Migrations + definePolicy RLS Compiler [2120c4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2120c4a1842bdf50efc17e741a5f638c3b633903)
## API v0.19.1 [#api-v0191]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.19.1) · 2026-06-03 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.19.0...api-v0.19.1)

**Bug Fixes**

* make /health/ready checks accurate and concurrent [0973b2d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0973b2db81f6c01ab23d6fdd3ff214d101464c8e)
## API v0.19.0 [#api-v0190]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.19.0) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.18.1...api-v0.19.0)

**Bug Fixes**

* **api:** add CORS_ALLOWED_ORIGINS to compose and drop typegen from readiness [2357c97](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2357c978237430b545eb116e23eab9c9989a67a0)
* **api:** handle FK violations, SELinux mounts, and contract test gaps [7686e20](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7686e2052d7cd275076a18844d3df88c52da39e6)
* **api:** require explicit CORS origin whitelist [9cecce6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9cecce6a4c1065a560689e6e272ab30ece121d94)
* **api:** restrict X-Stripe-Customer-Id header to service key auth [64a46bf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64a46bfeb5802ef541b2e88aad8e2221085ad00f)
* **api:** return 400 for Stripe client errors in RecordUsage [2b500c5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b500c578a461750cdd72e7c4de90326ec488733)
* **api:** use constant-time comparison for service key validation [ad7e949](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ad7e949c1daf6ba06d9f3610fb2e38f8645bd331)
* retry db connections [5bbfbcf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5bbfbcfe88f85daa9f8d24e19256998557edb7c4)

**Features**

* **api:** add make-public endpoint and object ID to OpenAPI spec [ba95243](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ba9524319ac03062a16770db8db1c7494c0b67a6)
* **api:** replace PostgREST storage with Keto per-object permissions [25f3b90](https://github.com/PhoenixSolutionsGroup/omnibase/commit/25f3b90fb832b06a0d1bd0968b771396d2b25a6b)
* mcp server [52f2a74](https://github.com/PhoenixSolutionsGroup/omnibase/commit/52f2a741476cefaf6f00be9ed892020056fb8216)
## CLI v0.6.0 [#cli-v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.6.0) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.5.0...cli-v0.6.0)

**Bug Fixes**

* **api:** add CORS_ALLOWED_ORIGINS to compose and drop typegen from readiness [2357c97](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2357c978237430b545eb116e23eab9c9989a67a0)
* **api:** handle FK violations, SELinux mounts, and contract test gaps [7686e20](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7686e2052d7cd275076a18844d3df88c52da39e6)

**Features**

* **db:** add ReBAC RLS helpers and replace path-based storage policies [51f9463](https://github.com/PhoenixSolutionsGroup/omnibase/commit/51f9463d999d7010eb08af9fc239a822d2cd2f5f)
* mcp server [52f2a74](https://github.com/PhoenixSolutionsGroup/omnibase/commit/52f2a741476cefaf6f00be9ed892020056fb8216)
* **permissions:** add StorageObject OPL namespace for per-object access control [4bf0ed6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4bf0ed67be6218d21237ea5f4d31a0327ced6ce4)
## Auth v0.4.1 [#auth-v041]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.4.1) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.4.0...auth-v0.4.1)

**Bug Fixes**

* **auth:** add --dev flag for HTTP website URLs [6c429f3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6c429f3a80c4d6b6c5f26c269ab6f52b48b06def)
## Permissions v0.4.0 [#permissions-v040]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.4.0) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.3.0...permissions-v0.4.0)

**Features**

* **permissions:** add StorageObject OPL namespace for per-object access control [4bf0ed6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4bf0ed67be6218d21237ea5f4d31a0327ced6ce4)
## API v0.18.1 [#api-v0181]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.18.1) · 2026-02-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.18.0...api-v0.18.1)

**Bug Fixes**

* **api:** update webhook registration to use managed hosting registration ID [d6f29d1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d6f29d1ba33a05bccb7a637267c12a51a7391c7d)
## API v0.18.0 [#api-v0180]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.18.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.17.0...api-v0.18.0)

**Bug Fixes**

* **api:** ensure roles array is never null in API response [f359f0c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f359f0cd90eae9de5f46303581b93e8a467ee2da)
* **api:** use JSDoc [@role](https://github.com/role) annotations for role template creation [8c06504](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8c065041a6f75f73eb235fa5e490be0deaff9610)

**Features**

* **api:** add JSDoc metadata parsing for permission relations [6ad5a80](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ad5a8083f21672a02f76c9091c0b82f2f585921)
## CLI v0.5.0 [#cli-v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.5.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.4.1...cli-v0.5.0)

**Features**

* **api:** add JSDoc metadata parsing for permission relations [6ad5a80](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ad5a8083f21672a02f76c9091c0b82f2f585921)
## Shadcn v0.8.0 [#shadcn-v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.2...shadcn-v0.8.0)

**Features**

* **shadcn:** add PermissionsSelectorTree component [e749bf0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e749bf0e5ef3e3a5c3313887d11c3947bf977db4)
## CLI v0.4.1 [#cli-v041]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.4.1) · 2026-02-03 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.4.0...cli-v0.4.1)

**Bug Fixes**

* **cli:** use package.json version instead of hardcoded 1.0.0 [skip tests] [84b8d84](https://github.com/PhoenixSolutionsGroup/omnibase/commit/84b8d841b8a8e3764b3a3c70c0a318d8d631cdcc)
## API v0.17.0 [#api-v0170]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.17.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.16.0...api-v0.17.0)

**Features**

* **release:** auto-sync docker image versions to CLI on release [505ed28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/505ed28851e452b70f6a698d331e11134d05dd08)
## API v0.16.0 [#api-v0160]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.16.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.15.0...api-v0.16.0)

**Bug Fixes**

* **api:** use Kratos API for tenant users instead of direct DB join [e11b2af](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e11b2af9be69e0f58c01786bad50f0ccebe47152)

**Features**

* **api:** add storage service to health check [47e7047](https://github.com/PhoenixSolutionsGroup/omnibase/commit/47e704748188ca112867afbcf8825cccf8d4f116)
## CLI v0.4.0 [#cli-v040]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.4.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.2...cli-v0.4.0)

**Bug Fixes**

* **cli:** update docker image versions to latest releases [6caa097](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6caa0978fdff9d7bb90c52610edeb879c4096cc1)
## CLI v0.3.2 [#cli-v032]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.2) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.1...cli-v0.3.2)

**Bug Fixes**

* **docker:** update argon2 hasher configuration [68c3049](https://github.com/PhoenixSolutionsGroup/omnibase/commit/68c3049d316aa2daace2d03f97216adaa057740b)
## Auth v0.4.0 [#auth-v040]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.4.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.3.2...auth-v0.4.0)

**Features**

* **release:** auto-sync docker image versions to CLI on release [505ed28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/505ed28851e452b70f6a698d331e11134d05dd08)
## Auth v0.3.2 [#auth-v032]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.3.2) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.3.1...auth-v0.3.2)

**Bug Fixes**

* **docker:** update argon2 hasher configuration [68c3049](https://github.com/PhoenixSolutionsGroup/omnibase/commit/68c3049d316aa2daace2d03f97216adaa057740b)
## Permissions v0.3.0 [#permissions-v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.3.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.2.1...permissions-v0.3.0)

**Features**

* **release:** auto-sync docker image versions to CLI on release [505ed28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/505ed28851e452b70f6a698d331e11134d05dd08)
## CLI v0.3.1 [#cli-v031]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.1) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.0...cli-v0.3.1)

**Bug Fixes**

* **cli:** add argon2 hasher defaults for auth service [9f577b9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9f577b9fb17c3301e880a9b276187ce81d2c071f)
## CLI v0.3.0 [#cli-v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.0) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.2...cli-v0.3.0)

**Features**

* **cli:** replace MinIO with RustFS for local object storage [2c93d4c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2c93d4c7ae8f5ae760d26d17f4dd780a58c1d15b)
## Next.js v0.8.2 [#nextjs-v082]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.2) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.1...nextjs-v0.8.2)

**Bug Fixes**

* **nextjs:** add JWT expiration checking in PostgREST middleware [bb5795d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb5795df4ac2048d9f4bac479d10d704a731227b)
## Auth v0.3.1 [#auth-v031]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.3.1) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.3.0...auth-v0.3.1)

**Bug Fixes**

* **docker:** quote argon2 hasher env vars in auth template [fc98bf8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/fc98bf8c73b402106cd86c49a81df41be58309d1)
## API v0.15.0 [#api-v0150]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.15.0) · 2026-01-18 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.14.0...api-v0.15.0)

**Features**

* **api:** add tenant type support (organization/individual) [9ba2615](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9ba261518275a382a13afc8baf0c231e4395f6e2)
## CLI v0.2.2 [#cli-v022]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.2) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.1...cli-v0.2.2)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)
## CLI v0.2.1 [#cli-v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.0...cli-v0.2.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)
## Next.js v0.8.1 [#nextjs-v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.0...nextjs-v0.8.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)
* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)
* **sdk/nextjs:** use @ory/client-fetch types for flow compatibility [a7411b3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a7411b3d9aa15bd1496c4bfdd53796687082fc57)
## React v0.3.6 [#react-v036]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.6) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.5...react-v0.3.6)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)
## React v0.3.5 [#react-v035]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.5) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.4...react-v0.3.5)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)
## Shadcn v0.7.2 [#shadcn-v072]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.2) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.1...shadcn-v0.7.2)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)
## Shadcn v0.7.1 [#shadcn-v071]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.0...shadcn-v0.7.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)
## API v0.14.0 [#api-v0140]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.14.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.13.0...api-v0.14.0)

**Features**

* **api:** add Cloud Run identity token auth for Ory services [5daaf2e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5daaf2e13e2aab1731f3f9137b75272301c8ce69)
* **api:** add price calculation endpoint for usage cost estimation [c63b46f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c63b46ffac54424815e963585f8bfaf4d43d331e)
* **api:** add price cost calculation endpoint [2831d6c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2831d6c223629dfc06a18a11a6be37783f915d6d)
## CLI v0.2.0 [#cli-v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.1.0...cli-v0.2.0)

**Bug Fixes**

* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **cli:** add postgres healthcheck and wait for healthy state [0b443d6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0b443d65e2d7b0c9c016ff3e566cfe75347cff57)
* **cli:** add test mode and refactor docker compose to base + override pattern [713b302](https://github.com/PhoenixSolutionsGroup/omnibase/commit/713b3021f0f60d3b589afc38c12f0bc154674cdd)
* **cli:** show docker compose output during execution [e910727](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e91072798cec9eaaf65814023af1db6c7caa068f)
* **docker:** add API_PUBLIC_URL for browser-facing auth redirects [4657787](https://github.com/PhoenixSolutionsGroup/omnibase/commit/465778737b79697ec240c3c575c3a9cc19530aee)
* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **api:** add database typegen endpoint [4346e04](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4346e04bcc16a3a9543275081e9b54bb2fc98c57)
* **api:** add enterprise pricing support [839ef19](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839ef19056587801c47de72501c52888879967d1)
* **api:** add stripe coupons and promotion codes support [9876ddf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9876ddfe15f7eff02a1ca68e5b797b39a0c4242b)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **docker:** add workers service and require email verification [d85cf48](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d85cf484ab0a616ede8ecdafd68994ff825c9ecd)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## Next.js v0.8.0 [#nextjs-v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.7.0...nextjs-v0.8.0)

**Bug Fixes**

* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)

**Features**

* **sdk/nextjs:** add error flow support and verification redirect [6440955](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64409557d5c41468a6aba3918268116da8d0eb7e)
## React v0.3.4 [#react-v034]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.4) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.3...react-v0.3.4)

**Bug Fixes**

* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
## Shadcn v0.7.0 [#shadcn-v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.6.2...shadcn-v0.7.0)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **sdk/shadcn:** add create tenant option and error form component [4a4724b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4a4724bef846f57bf617800dba682f007876bc51)
## Auth v0.3.0 [#auth-v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.3.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.2.2...auth-v0.3.0)

**Bug Fixes**

* **docker:** add API_PUBLIC_URL for browser-facing auth redirects [4657787](https://github.com/PhoenixSolutionsGroup/omnibase/commit/465778737b79697ec240c3c575c3a9cc19530aee)

**Features**

* **docker:** add workers service and require email verification [d85cf48](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d85cf484ab0a616ede8ecdafd68994ff825c9ecd)
## API v0.13.0 [#api-v0130]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.13.0) · 2026-01-13 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.6...api-v0.13.0)

**Bug Fixes**

* **api:** add pattern validation to typegen schemas parameter [378418b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/378418ba1aad76fbf63e5f1608ff20b95d12f5bd)
* **api:** handle missing products gracefully in archive operation [d2cb08b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2cb08bf008140e0b6e7934692fbc24b79bd81f3)
* **api:** include all stripe IDs in config response [20fdf21](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20fdf213968d187b24b4e0b01edaf3aef7b3bc4e)
* **api:** rewrite Location and Set-Cookie headers in auth proxy [6f81cdf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6f81cdf773a2f25b23aaedc832958da83e9f3217)

**Features**

* **api:** add comprehensive health ready endpoint [c01cf28](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c01cf282b74d6ddfc8ad9d211a6489d1c320c7d9)
* **api:** add database typegen endpoint [4346e04](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4346e04bcc16a3a9543275081e9b54bb2fc98c57)
* **api:** add enterprise pricing support [839ef19](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839ef19056587801c47de72501c52888879967d1)
* **api:** add postgrest and typegen to health ready check [2540408](https://github.com/PhoenixSolutionsGroup/omnibase/commit/254040818387ee71516421efa4c304a7247194da)
* **api:** add stripe coupons and promotion codes support [9876ddf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9876ddfe15f7eff02a1ca68e5b797b39a0c4242b)
## Auth v0.2.2 [#auth-v022]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.2.2) · 2026-01-13 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.2.1...auth-v0.2.2)

**Bug Fixes**

* **api:** rewrite Location and Set-Cookie headers in auth proxy [6f81cdf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6f81cdf773a2f25b23aaedc832958da83e9f3217)
## Permissions v0.2.1 [#permissions-v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.2.1) · 2026-01-13 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.2.0...permissions-v0.2.1)

**Bug Fixes**

* **release:** add package.json for Go projects [829ab1c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/829ab1c26705b28cf970dce475ed942aa152c83d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
## API v0.12.6 [#api-v0126]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.6) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.5...api-v0.12.6)

**Bug Fixes**

* **ci:** update git-user-id to phoenixsolutionsgroup from PhoenixSolutionsGroup for go package [a2f7c3e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a2f7c3e148f91b16ffa8cf15b703137af8f9fb1f)
## API v0.12.5 [#api-v0125]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.5) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.4...api-v0.12.5)

**Bug Fixes**

* **release:** stage SDK files explicitly in prepare script [c7cdc4d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c7cdc4d2475b8f255c592ed0826ba3108304a1b2)
## API v0.12.4 [#api-v0124]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.4) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.3...api-v0.12.4)

**Bug Fixes**

* **ci:** api redeploy [add8bee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/add8bee2728d92a6669d9fd416acdd5b3f785cc5)
## API v0.12.3 [#api-v0123]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.3) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.2...api-v0.12.3)

**Bug Fixes**

* **cli:** add test mode and refactor docker compose to base + override pattern [713b302](https://github.com/PhoenixSolutionsGroup/omnibase/commit/713b3021f0f60d3b589afc38c12f0bc154674cdd)
## API v0.12.2 [#api-v0122]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.2) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.1...api-v0.12.2)

**Bug Fixes**

* **release:** include generated SDK files in release commit [41e87f5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/41e87f570c313eb674054da73e57a0273020ed05)
## API v0.12.1 [#api-v0121]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.1) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.12.0...api-v0.12.1)

**Bug Fixes**

* **release:** add package.json for Go projects [829ab1c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/829ab1c26705b28cf970dce475ed942aa152c83d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
## API v0.12.0 [#api-v0120]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.12.0) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.11.0...api-v0.12.0)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **api:** add tenant lookup endpoints [64d9850](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64d98500ba1a583d7bd40d8509d00c88ac50bbe6)
## Auth v0.2.1 [#auth-v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.2.1) · 2026-01-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.2.0...auth-v0.2.1)

**Bug Fixes**

* **release:** add package.json for Go projects [829ab1c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/829ab1c26705b28cf970dce475ed942aa152c83d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
## Next.js v0.7.0 [#nextjs-v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.7.0) · 2026-01-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.6.5...nextjs-v0.7.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## API v0.11.0 [#api-v0110]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/api-v0.11.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/api-v0.10.2...api-v0.11.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## React v0.3.3 [#react-v033]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.3) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.2...react-v0.3.3)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
## React v0.3.2 [#react-v032]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.2) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.1...react-v0.3.2)

**Bug Fixes**

* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
## React v0.3.1 [#react-v031]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.1) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.0...react-v0.3.1)

**Bug Fixes**

* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)
## React v0.3.0 [#react-v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.2.2...react-v0.3.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## Auth v0.2.0 [#auth-v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/auth-v0.2.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/auth-v0.1.4...auth-v0.2.0)

**Bug Fixes**

* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## Permissions v0.2.0 [#permissions-v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/permissions-v0.2.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/permissions-v0.1.1...permissions-v0.2.0)

**Bug Fixes**

* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)
## CLI v0.2.0 [#cli-v020-1]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fcli%400.2.0) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/cli@0.1.0...@omnibase/cli@0.2.0)

**Features**

* **payments:** add webhook endpoint management to Stripe configuration [ca36464](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ca36464567a79f6605eac4116fbaa1050c5620b4)
## Next.js v0.6.5 [#nextjs-v065]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.5) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.4...@omnibase/nextjs@0.6.5)

**Bug Fixes**

* remove api_url from FlowRouterProps interface [af58e1f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/af58e1f6c004db0e7e3550360472b8ccd21dba0c)
## Next.js v0.6.4 [#nextjs-v064]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.4) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.3...@omnibase/nextjs@0.6.4)

**Bug Fixes**

* env var issues [bdfe006](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bdfe006ab5823f1b5595301dea2c049c55c51553)
## Next.js v0.6.3 [#nextjs-v063]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.3) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.2...@omnibase/nextjs@0.6.3)

**Note:** Version bump only for package @omnibase/nextjs
## React v0.2.2 [#react-v022]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Freact%400.2.2) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/react@0.2.0...@omnibase/react@0.2.2)

**Bug Fixes**

* **react:** update Session type import to use @ory/client [233673c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/233673c9dd41811bddd9ea106214652fdc7be74e)
## Shadcn v0.6.2 [#shadcn-v062]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.2) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.6.0...@omnibase/shadcn@0.6.2)

**Note:** Version bump only for package @omnibase/shadcn
## CLI v0.1.0 [#cli-v010]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fcli%400.1.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/cli@0.0.1...@omnibase/cli@0.1.0)

**Code Refactoring**

* **permissions:** replace system roles with tenant-scoped role templates [f149cbd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f149cbde6adc175ceff5ae892a2da413af7763bd)

* refactor(cli)!: redesign command structure with unified logging and interactive UX [a72b998](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a72b998a59842fd13a071bb22af911931f28f762)
* I'll analyze the staged changes to generate an appropriate conventional commit message. [9cca97b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9cca97bae348343f88203137938b128dc388bd78)

**Features**

* **cli:** add auth, db, migration, and workers commands [1e3f796](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e3f796bff284c1f1d449feb837077db8189180f)
* **cli:** add cloud authentication and improve CLI output formatting [e8f95f3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e8f95f33bb75caaa37ef1f966705d8d20568885f)
* **cli:** added worker base code in templates so `omnibase init` has it [53e7622](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53e7622fb54f3bbc080180f45c71104561c564e1)
* **cli:** created service config for better DX [077f309](https://github.com/PhoenixSolutionsGroup/omnibase/commit/077f309cb97873ff305ae74cf1b8f14f066a2cea)
* **cli:** updated permissions logic to include a base set of `roles` for a permissions set. [6ea6981](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ea6981d27b63c9dc50e993e0d0cb0b2e65c97ed)

**BREAKING CHANGES**

* Command structure changed - `auth login` moved to `cloud login`, `workers deploy` moved to `cloud workers deploy`. Environment variables renamed: API_URL → OMNIBASE_API_URL, OMNIBASE_API_KEY → OMNIBASE_SERVICE_KEY. Commands now show interactive environment picker instead of requiring --env flag.
* **permissions:** All roles must now belong to a tenant. System roles
are cloned from templates during tenant creation instead of shared
across tenants.
* default environment changed from "dev" to "local"
## Next.js v0.6.2 [#nextjs-v062]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.2) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.0...@omnibase/nextjs@0.6.2)

**Bug Fixes**

* workspace dep [873ec22](https://github.com/PhoenixSolutionsGroup/omnibase/commit/873ec22664a213e0853fc3b80482c3f1c7a64012)
## Next.js v0.6.0 [#nextjs-v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.5.0...@omnibase/nextjs@0.6.0)

**Code Refactoring**

* **nextjs:** derive auth URL from api_url and remove server action exports [cd4b975](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cd4b97570d861ea2cfa4a4c60118a0d30ba1f212)

**BREAKING CHANGES**

* **nextjs:** The /auth/permissions and /auth/tenants exports have been removed. Auth flow functions (getLoginFlow, getRegistrationFlow, etc.) now require an api_url parameter. Migration: pass process.env.NEXT_PUBLIC_OMNIBASE_API_URL as api_url to all auth flow functions.
## React v0.2.1 [#react-v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Freact%400.2.1) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/react@0.2.0...@omnibase/react@0.2.1)

**Bug Fixes**

* **react:** update Session type import to use @ory/client [233673c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/233673c9dd41811bddd9ea106214652fdc7be74e)
## Shadcn v0.6.1 [#shadcn-v061]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.1) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.6.0...@omnibase/shadcn@0.6.1)

**Note:** Version bump only for package @omnibase/shadcn
## Shadcn v0.6.0 [#shadcn-v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.5.9...@omnibase/shadcn@0.6.0)

**Features**

* **shadcn:** add permissions selector component and refactor role creator [e3c3e9a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e3c3e9a1eef2aca9368368dedc578c9c4aa4fb9a)
## CLI v0.0.1 [#cli-v001]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/packages/cli/CHANGELOG.md)

**Patch Changes**

- 91f64a0: Updated `omnibase stripe upload` -\> `omnibase stripe push` for consistency
## Next.js v0.5.2 [#nextjs-v052]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/nextjs/CHANGELOG.md)

**Patch Changes**

- Updated auth url to get derived from api_url
## Next.js v0.5.0 [#nextjs-v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/nextjs/CHANGELOG.md)

**Minor Changes**

- 2971db8: Added API's to update user roles in tenant
- 065f048: Added Protected Route utility function to enforce auth sessions

**Patch Changes**

- daf020a: Fixed edge case where middleware would fail for new users before creating a tenant
- Updated dependencies [2971db8]
  - @omnibase/core-js@0.6.0
## React v0.2.0 [#react-v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/react/CHANGELOG.md)

**Minor Changes**

- 065f048: Added Protected Route component to enforce auth sessions

**Patch Changes**

- Updated dependencies [2971db8]
  - @omnibase/core-js@0.6.0
## Shadcn v0.5.10 [#shadcn-v0510]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Fixed workspace dep issue
## Shadcn v0.5.9 [#shadcn-v059]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Updated role creation and added Permissions selector component
## Shadcn v0.5.8 [#shadcn-v058]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Fixed Workspace Dep Issue
## Shadcn v0.5.7 [#shadcn-v057]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Updated role-creator for better UX
## Shadcn v0.4.3 [#shadcn-v043]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- 5b645b7: Added `login_url` to RegistrationForm and `register_url` to LoginForm to easily switch between
</ChangelogFilter>

# CLI Changelog (/cli)

**Latest: v0.13.0**

[Read the CLI v0.13.0 docs](/cli/0.13.0)

All CLI releases are listed below, newest first. Each version links to its docs, or to its GitHub release when the docs for that version are no longer published. See the [changelog for every package](/changelog).

## v0.13.0 [#v0130]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.13.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.12.0...cli-v0.13.0)

**Bug Fixes**

* **api:** renumber email migrations after main [d7934ff](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d7934ff3adfb58b66d4214437611334042700585)
* better error message when local isn't running [acd5667](https://github.com/PhoenixSolutionsGroup/omnibase/commit/acd56677ce9737e0749f5c9084fc13fa398774ff)
* **cli:** merge coupons and promotion codes from config files [af2b76f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/af2b76fe98211b16b01e3a31dc5a76d0286cf3bf)
* **cli:** reject unresolved webhook URLs consistently [f202967](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f202967e1bb02a992300ef00c5a96967c7a199fd)
* **deployments:** remove deployments name defaulting to 'default' [c580a32](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c580a3237fab66dabad0fb3f8da14692bc3a2769)
* **deployments:** use \<slug\>.omnibase-workers.app instead of \<slug\>.workers.omnibase.tech [15fe9ac](https://github.com/PhoenixSolutionsGroup/omnibase/commit/15fe9ac1b1ae42436e2bd40e77ba9b5c4e35842d)
* no console logs until omnibase starts [0e58920](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0e5892093f7e56640a8d2a3706eefa02fa161fd6)
* **payments:** add manage_billing permission [f85e692](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f85e6922f57d831dfbebde5025bd7bd97494b686)
* restrict invite roles and URLs to prevent owner escalation [e74d7e5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e74d7e5db0ccb7af4fd725747fc01522cf064864)
* **sdk:** stop tracking core-js dist and build packages before dependents [6d04e5e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6d04e5e459c905a711e6aa1ae971ea1f6360bf1e)
* update cli to use new provision args [1adec91](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1adec910d9d6e2fad4ec7b013dc2b966b257dcb5)

**Features**

* AGENTS.md file [7199fc0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7199fc0fe57d887fe6c6106bccc59cb77f1e6bb2)
* **api:** add tenant, system, and email history schema [b3bab23](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b3bab239bab383d697a39c07fcccb7e86d1a7c09)
* **api:** validate required config at startup [cfcd89f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cfcd89f55ca8a8a4aae978980138608e3655b90f)
* **cli:** add docs commands backed by static llms routes [956c7b3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/956c7b3876a02282b4b832003585b42c94b34328)
* **cli:** add stripe status command [e7a6b60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e7a6b60f30db4649467b03a54fb97c546e82affb)
* **cli:** pin service versions in omnibase init and drop docker-compose sync [985c217](https://github.com/PhoenixSolutionsGroup/omnibase/commit/985c217b47108762402eb82bc1b9eba9317b7906), closes [#154](https://github.com/PhoenixSolutionsGroup/omnibase/issues/154)
* **cli:** print a service and deployment URL summary after start [2705ad4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2705ad473167d249702ffb515f83907224d07673)
* **cli:** run start in the foreground, add -d for detached mode [f7c892a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f7c892acfc9ea96b1051af2238b73145775dde94)
* **email:** record delivery history and rate limit sends per tenant [e894528](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e894528e1404d8d6451861943787865f4130b221)
* **permissions:** add email send and template management permissions [2f2cd52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2f2cd528291ed4e61f0cd71a10230e40ec65e962)
* **permissions:** API owns required namespaces and validates projects [1e94d44](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e94d44e4c1837ffb2e1043594e65df1f05fd192)
* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)
* **stripe-config:** scope archive-all to managed resources [1367403](https://github.com/PhoenixSolutionsGroup/omnibase/commit/136740362813e551bfdc90902db2671951f84541)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* support metadata on stripe products and prices [f4cf420](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f4cf420869cdb78411fe384d9c9bc473a22880d1)

## v0.12.0 [#v0120]

[Docs](/cli/0.12.0) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.11.0...cli-v0.12.0)

**Bug Fixes**

* **cli:** restart permissions [64b799e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64b799eec257c243a0bd6e5e14757d67b47f0b09)
* **db:** make RLS helpers SECURITY DEFINER and narrow anon_user grants [471ae36](https://github.com/PhoenixSolutionsGroup/omnibase/commit/471ae36a6419a7d2280fc2f6655d01ad1bbcf79d)
* **db:** move pg_trgm to the auth schema [5e3f0fa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5e3f0fa36222751c85a8e0955d156d4a25ed33f9)
* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)
* upload database migrations as files [78fb155](https://github.com/PhoenixSolutionsGroup/omnibase/commit/78fb1552cd9642f0d8e225d6dc4f20f3607fa32d)
* upload permissions archive as a file [d3dbf52](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d3dbf5274b0cc1b5765994de597524531ffa7623)

**Features**

* add preview branch CLI commands [fbd41ca](https://github.com/PhoenixSolutionsGroup/omnibase/commit/fbd41ca089656d6aa6b3f2e0ff2b2852777924dd)
* **api:** add app-key user mode [4f39053](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4f390532f6ecbe84b86745ed1fac690abf6a43c1)
* **cli:** emit table GRANT/REVOKE from RLS policy codegen [aad95ce](https://github.com/PhoenixSolutionsGroup/omnibase/commit/aad95ce790608c5ab110bc95a2d08d3460410872)

## v0.11.0 [#v0110]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.11.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.10.0...cli-v0.11.0)

**Bug Fixes**

* **cli:** don't fall back to .env.local for branch env resolution [8f867af](https://github.com/PhoenixSolutionsGroup/omnibase/commit/8f867afd39b2dcd5cb0f4c07661af77b3f8db854)
* **cli:** resolve bundle entry file [948ee57](https://github.com/PhoenixSolutionsGroup/omnibase/commit/948ee571217a7d0fcb579ae99099ae736a90613b)

**Features**

* add domain to workers [f296668](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f2966681a7ab4eb4f9d3692b2414d15e39f83cb8)
* **cli:** inject branch env into worker builds, vars and env push [ae3c1e2](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ae3c1e23827a6ba2637918d96ede3ca953fb3d62)
* **cli:** load per-branch env files for config resolution [d82ad45](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d82ad45681c0252e5b2dcb285a348fa4c6ffe66a)
* **cli:** resolve branch env for omnibase start dev servers [714f683](https://github.com/PhoenixSolutionsGroup/omnibase/commit/714f6836f16bfe3c3f526c84f9e2d7936a147786)

## v0.10.0 [#v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.10.0) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.9.0...cli-v0.10.0)

**Bug Fixes**

* **cli:** skip empty allowed return urls entries [7f51ff9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7f51ff9d3e25eb62c774d3232dc1cb721558fad9)

**Features**

* **cli:** Application version pinning [5ebd13b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5ebd13bc12562bf3f54bdcfb306a785b0452cfce)

## v0.9.0 [#v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.9.0) · 2026-08-25 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.8.1...cli-v0.9.0)

**Features**

* **cli:** drive local and cloud config from omnibase.toml [0b19bc4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0b19bc4c1f0c2188cfc6f9ba31b7f9eefdbda7aa)

## v0.8.1 [#v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.8.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.8.0...cli-v0.8.1)

No user-facing changes.

## v0.8.0 [#v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.8.0) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.7.0...cli-v0.8.0)

**Bug Fixes**

* Add Service Key to docker-compose and tests [f98fdd5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f98fdd5e5b6242c4c4041cb29ea890785ad8259c)
* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)

**Features**

* **cli:** enhance worker deployment options [c655f25](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c655f25ca2c34b8b0b8c415637e83a2af603b900)

## v0.7.0 [#v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.7.0) · 2026-07-07 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.6.0...cli-v0.7.0)

**Bug Fixes**

* **cli:** drop legacy data envelope, SDK responses are unwrapped [0783815](https://github.com/PhoenixSolutionsGroup/omnibase/commit/07838150f160759aee49db273f79296ef45260da)

**Features**

* **api:** wire SDK gen from huma spec + split tenants tag + API_VERSION env [bd7fcdc](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bd7fcdc0e5eb7e7591aff834950ea383490063d2)
* Prisma Schema + Down Migrations + definePolicy RLS Compiler [2120c4a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2120c4a1842bdf50efc17e741a5f638c3b633903)

## v0.6.0 [#v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.6.0) · 2026-05-30 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.5.0...cli-v0.6.0)

**Bug Fixes**

* **api:** add CORS_ALLOWED_ORIGINS to compose and drop typegen from readiness [2357c97](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2357c978237430b545eb116e23eab9c9989a67a0)
* **api:** handle FK violations, SELinux mounts, and contract test gaps [7686e20](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7686e2052d7cd275076a18844d3df88c52da39e6)

**Features**

* **db:** add ReBAC RLS helpers and replace path-based storage policies [51f9463](https://github.com/PhoenixSolutionsGroup/omnibase/commit/51f9463d999d7010eb08af9fc239a822d2cd2f5f)
* mcp server [52f2a74](https://github.com/PhoenixSolutionsGroup/omnibase/commit/52f2a741476cefaf6f00be9ed892020056fb8216)
* **permissions:** add StorageObject OPL namespace for per-object access control [4bf0ed6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4bf0ed67be6218d21237ea5f4d31a0327ced6ce4)

## v0.5.0 [#v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.5.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.4.1...cli-v0.5.0)

**Features**

* **api:** add JSDoc metadata parsing for permission relations [6ad5a80](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ad5a8083f21672a02f76c9091c0b82f2f585921)

## v0.4.1 [#v041]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.4.1) · 2026-02-03 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.4.0...cli-v0.4.1)

**Bug Fixes**

* **cli:** use package.json version instead of hardcoded 1.0.0 [skip tests] [84b8d84](https://github.com/PhoenixSolutionsGroup/omnibase/commit/84b8d841b8a8e3764b3a3c70c0a318d8d631cdcc)

## v0.4.0 [#v040]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.4.0) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.2...cli-v0.4.0)

**Bug Fixes**

* **cli:** update docker image versions to latest releases [6caa097](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6caa0978fdff9d7bb90c52610edeb879c4096cc1)

## v0.3.2 [#v032]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.2) · 2026-01-22 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.1...cli-v0.3.2)

**Bug Fixes**

* **docker:** update argon2 hasher configuration [68c3049](https://github.com/PhoenixSolutionsGroup/omnibase/commit/68c3049d316aa2daace2d03f97216adaa057740b)

## v0.3.1 [#v031]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.1) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.3.0...cli-v0.3.1)

**Bug Fixes**

* **cli:** add argon2 hasher defaults for auth service [9f577b9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9f577b9fb17c3301e880a9b276187ce81d2c071f)

## v0.3.0 [#v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.3.0) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.2...cli-v0.3.0)

**Features**

* **cli:** replace MinIO with RustFS for local object storage [2c93d4c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2c93d4c7ae8f5ae760d26d17f4dd780a58c1d15b)

## v0.2.2 [#v022]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.2) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.1...cli-v0.2.2)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)

## v0.2.1 [#v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.2.0...cli-v0.2.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)

## v0.2.0 [#v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/cli-v0.2.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/cli-v0.1.0...cli-v0.2.0)

**Bug Fixes**

* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **cli:** add postgres healthcheck and wait for healthy state [0b443d6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0b443d65e2d7b0c9c016ff3e566cfe75347cff57)
* **cli:** add test mode and refactor docker compose to base + override pattern [713b302](https://github.com/PhoenixSolutionsGroup/omnibase/commit/713b3021f0f60d3b589afc38c12f0bc154674cdd)
* **cli:** show docker compose output during execution [e910727](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e91072798cec9eaaf65814023af1db6c7caa068f)
* **docker:** add API_PUBLIC_URL for browser-facing auth redirects [4657787](https://github.com/PhoenixSolutionsGroup/omnibase/commit/465778737b79697ec240c3c575c3a9cc19530aee)
* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **api:** add database typegen endpoint [4346e04](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4346e04bcc16a3a9543275081e9b54bb2fc98c57)
* **api:** add enterprise pricing support [839ef19](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839ef19056587801c47de72501c52888879967d1)
* **api:** add stripe coupons and promotion codes support [9876ddf](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9876ddfe15f7eff02a1ca68e5b797b39a0c4242b)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **docker:** add workers service and require email verification [d85cf48](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d85cf484ab0a616ede8ecdafd68994ff825c9ecd)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)

## v0.2.0 [#v020-1]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fcli%400.2.0) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/cli@0.1.0...@omnibase/cli@0.2.0)

**Features**

* **payments:** add webhook endpoint management to Stripe configuration [ca36464](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ca36464567a79f6605eac4116fbaa1050c5620b4)

## v0.1.0 [#v010]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fcli%400.1.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/cli@0.0.1...@omnibase/cli@0.1.0)

**Code Refactoring**

* **permissions:** replace system roles with tenant-scoped role templates [f149cbd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f149cbde6adc175ceff5ae892a2da413af7763bd)

* refactor(cli)!: redesign command structure with unified logging and interactive UX [a72b998](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a72b998a59842fd13a071bb22af911931f28f762)
* I'll analyze the staged changes to generate an appropriate conventional commit message. [9cca97b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9cca97bae348343f88203137938b128dc388bd78)

**Features**

* **cli:** add auth, db, migration, and workers commands [1e3f796](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1e3f796bff284c1f1d449feb837077db8189180f)
* **cli:** add cloud authentication and improve CLI output formatting [e8f95f3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e8f95f33bb75caaa37ef1f966705d8d20568885f)
* **cli:** added worker base code in templates so `omnibase init` has it [53e7622](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53e7622fb54f3bbc080180f45c71104561c564e1)
* **cli:** created service config for better DX [077f309](https://github.com/PhoenixSolutionsGroup/omnibase/commit/077f309cb97873ff305ae74cf1b8f14f066a2cea)
* **cli:** updated permissions logic to include a base set of `roles` for a permissions set. [6ea6981](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ea6981d27b63c9dc50e993e0d0cb0b2e65c97ed)

**BREAKING CHANGES**

* Command structure changed - `auth login` moved to `cloud login`, `workers deploy` moved to `cloud workers deploy`. Environment variables renamed: API_URL → OMNIBASE_API_URL, OMNIBASE_API_KEY → OMNIBASE_SERVICE_KEY. Commands now show interactive environment picker instead of requiring --env flag.
* **permissions:** All roles must now belong to a tenant. System roles
are cloned from templates during tenant creation instead of shared
across tenants.
* default environment changed from "dev" to "local"

## v0.0.1 [#v001]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/packages/cli/CHANGELOG.md)

**Patch Changes**

- 91f64a0: Updated `omnibase stripe upload` -\> `omnibase stripe push` for consistency

# Permissions Overview (/concepts/permissions)

Omnibase uses a **relationship-based access control (ReBAC)** system. Instead of rigid roles or complex policies, permissions are modeled as **relations between objects** in a graph.

## The Core Idea [#the-core-idea]

Every **namespace** is an **object type**. Objects relate to each other through named **relations**. A permission check asks one question:

> *Does subject **S** have relation **R** on object **O**?*

```
(User, user_abc, can_invite_user, Tenant, tenant_xyz)
```

These relations form a graph that you can traverse. A user can act on a tenant directly, or on all projects within a tenant through chained relations.

## Built-in Defaults [#built-in-defaults]

Omnibase ships with these object types out of the box:

| Object | Purpose |
|--------|---------|
| `User` | End user — acts as a subject in permission checks |
| `Tenant` | Organizational container — members, owners, permissions |
| `StorageObject` | A file in object storage |

## Why Relations, Not Roles [#why-relations-not-roles]

Traditional RBAC gives users flat roles with fixed permission sets. ReBAC gives you:

- **Fine-grained control** — grant a permission on a specific resource, not "all resources"
- **Inheritance through traversal** — grant at the tenant level and cascade to all resources
- **Multiple subject types** — both Users and API keys can hold permissions
- **Per-resource ownership** — each object has its own access rules

## Permissions Sub-Pages [#permissions-sub-pages]

<Component>
<Component title="Objects & Namespaces" href="/concepts/permissions/objects-and-namespaces">
What objects are, built-in defaults, defining custom objects, JSDoc annotations, and subject types
</Component>

<Component title="Relations & Traversal" href="/concepts/permissions/relations-traversal">
How relations connect objects, the traverse() method, chained permission checks, and common patterns
</Component>

<Component title="OmniGit Example" href="/concepts/permissions/omni-git">
Complete walkthrough with custom objects, two agent scoping patterns, grant and check flows
</Component>
</Component>

## Quick Example [#quick-example]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Check if a user can invite others to a tenant
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Tenant',
    object: tenantId,
    relation: 'can_invite_user',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Tenant",
    Object:    tenantId,
    Relation:  "can_invite_user",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    userId,
    },
}).Execute()
```
</Tab>
</Tabs>

## Related [#related]

- [Defining Permissions Guide](/docs/guides/rbac/permissions) — How to write permission namespace files
- [Managing Roles Guide](/docs/guides/rbac/roles) — Create roles, assign users

# Objects & Namespaces (/concepts/permissions/objects-and-namespaces)

In the Omnibase permission system, every **namespace** is an **object type** — a distinct kind of thing that can own, be acted upon, or be the subject of a permission check.

## Built-in Objects [#built-in-objects]

Omnibase ships with these object types by default. They are defined in your project's `omnibase/permissions/` directory.

### User [#user]

Users who authenticate via sessions. `User` is the primary **subject type** — the "who" in a permission check. It has no relations defined on it; it exists only to be the target of relations on other objects.

```typescript
// omnibase/permissions/tenants.ts
export class User implements Namespace {}
```

### Tenant [#tenant]

The organizational container. Each tenant has its own members, roles, and data isolation. Tenant permissions are auto-scoped from the user's active session.

```typescript
export class Tenant implements Namespace {
  related: {
    /** @group Tenant Administration */
    can_delete_tenant: User[];

    /** @group User Management */
    can_invite_user: User[];

    /** @group User Management */
    can_update_user_role: User[];

    /** @group User Management */
    can_remove_user: User[];

    /** @group User Management */
    can_view_users: User[];

    /** @group Roles & Permissions */
    can_create_roles: User[];

    /** @group Roles & Permissions */
    can_update_roles: User[];

    /** @group Roles & Permissions */
    can_delete_roles: User[];
  };

  permits = {
    invite_user: (ctx): boolean =>
      this.related.can_invite_user.includes(ctx.subject),
    delete_tenant: (ctx): boolean =>
      this.related.can_delete_tenant.includes(ctx.subject),
    // ... etc
  };
}
```

### StorageObject [#storageobject]

A file uploaded to object storage. Has its own owner-based permissions with read, delete, and make_public relations.

```typescript
// omnibase/permissions/storage.ts
export class StorageObject implements Namespace {
  related: {
    /** @hidden */
    owner: User[];
    can_read: User[];
    can_delete: User[];
    can_make_public: User[];
    /** @hidden */
    tenant: Tenant[];
  };

  permits = {
    read: (ctx): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_read.includes(ctx.subject),
    delete: (ctx): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_delete.includes(ctx.subject),
    make_public: (ctx): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_make_public.includes(ctx.subject),
  };
}
```

## Defining Custom Objects [#defining-custom-objects]

Create a new namespace class to define a custom object type. The class must implement `Namespace` and can define `related` relations and a `permits` block.

```typescript
// omnibase/permissions/agents.ts
import { Context, Namespace } from "./types";

export class Agent implements Namespace {}

// omnibase/permissions/codebases.ts
import { Agent, Context, Namespace, Tenant, User } from "./types";

export class Codebase implements Namespace {
  related: {
    /** @hidden */
    tenant: Tenant[];

    /** @group Codebase Access */
    can_edit: (User | Agent)[];

    /** @group Codebase Access */
    can_push: (User | Agent)[];

    /** @group Codebase Access */
    can_view: (User | Agent)[];
  };

  permits = {
    edit: (ctx): boolean =>
      this.related.can_edit.includes(ctx.subject),
    push: (ctx): boolean =>
      this.related.can_push.includes(ctx.subject),
    view: (ctx): boolean =>
      this.related.can_view.includes(ctx.subject),
  };
}
```

<Component type="info">
See the full [OmniGit Example](/concepts/permissions/omni-git) for a complete walkthrough with two agent scoping patterns.
</Component>

## JSDoc Annotations [#jsdoc-annotations]

Every relation in a `related` block can carry JSDoc annotations. These provide metadata for the UI and role system — they are parsed by the API and consumed by frontend components.

| Annotation | Purpose | Example |
|------------|---------|---------|
| `@group` | Primary UI grouping | `@group User Management` |
| `@subGroup` | Secondary grouping within a group | `@subGroup Role Assignment` |
| `@displayName` | Human-readable label | `@displayName Invite Users` |
| `@role` | Suggested default role(s) | `@role owner` |
| `@hidden` | Hide from UI (internal relations) | `@hidden` |

```typescript
/**
 * @group User Management
 * @subGroup Role Assignment
 * @displayName Update User Roles
 * @role owner
 * @role admin
 */
can_update_user_role: User[];
```

The `@role` annotation serves as a suggestion when creating roles in the UI. The `@hidden` annotation is essential for relations used only for permission traversal (like `tenant: Tenant[]` or `owner: User[]`) — they should never appear in a role-editing UI.

## Next [#next]

Relations are how objects connect — [Relations & Traversal](/concepts/permissions/relations-traversal) explains how to chain permissions through intermediate objects.

# OmniGit Example (/concepts/permissions/omni-git)

This example walks through a complete permission setup for **OmniGit** — a code hosting platform where both users and AI agents interact with codebases.

## Scenario [#scenario]

OmniGit has four object types:

| Object | Type | Purpose |
|--------|------|---------|
| `User` | Built-in subject | Developers |
| `Tenant` | Built-in container | An organization owning repositories |
| `Agent` | Custom subject | LLM-powered AI agent |
| `Codebase` | Custom resource | A git repository |

There are two ways to scope an agent:

1. **Codebase Scoped Agent** — permissions granted directly on a specific codebase. The agent can only act on that repo.
2. **Tenant Wide Agent** — permissions granted on the tenant, cascading to all codebases through `traverse()`. The agent can act on every repo in the org.

## Relations Graph [#relations-graph]

```
        ┌──────────┐
        │  User    │
        └────┬─────┘
             │ can_edit (direct)
             │
             ▼
┌──────────────────────┐      tenant       ┌──────────┐
│      Codebase        │──────────────────▶│  Tenant  │
│  (git repository)    │                   │  (org)   │
└──────────────────────┘                   └──────────┘
        ▲    ▲                                   ▲
        │    │                                   │
        │    │ can_push (tenant-wide)            │ can_edit (tenant-wide)
        │    └───────────────────────────────────┤
        │                                        │
  can_push (scoped)                              │ can_edit (tenant-wide)
        │                                        │
  ┌────┴─────┐                            ┌──────┴──────┐
  │  Agent   │                            │    Agent    │
  │ (scoped) │                            │ (tenant-wide)│
  └──────────┘                            └─────────────┘
```

## Definitions [#definitions]

### Agent [#agent]

```typescript title="omnibase/permissions/agents.ts"
import { Context, Namespace } from "./types";

export class Agent implements Namespace {}
```

The Agent namespace is empty — it exists only as a subject type, the same way `User` does. It has no relations of its own; it is the target of relations on other objects.

### Codebase [#codebase]

```typescript title="omnibase/permissions/codebases.ts"
import { Agent, Context, Namespace, Tenant, User } from "./types";

export class Codebase implements Namespace {
  related: {
    /** @hidden — link to owning org for tenant-wide traversal */
    tenant: Tenant[];

    /** @hidden — codebase owner inherits permissions */
    owner: User[];

    /**
     * @group Codebase Access
     * @displayName Edit Code
     * @role owner
     * @role developer
     */
    can_edit: (User | Agent)[];

    /**
     * @group Codebase Access
     * @displayName Push Changes
     * @role owner
     * @role developer
     */
    can_push: (User | Agent)[];

    /**
     * @group Codebase Access
     * @displayName View Code
     * @role owner
     * @role developer
     * @role viewer
     */
    can_view: (User | Agent)[];

    /**
     * @group Codebase Access
     * @displayName Delete Codebase
     * @role owner
     */
    can_delete: (User | Agent)[];
  };

  permits = {
    edit: (ctx: Context): boolean =>
      this.related.can_edit.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_edit.includes(ctx.subject)
      ),

    push: (ctx: Context): boolean =>
      this.related.can_push.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_push.includes(ctx.subject)
      ),

    view: (ctx: Context): boolean =>
      this.related.can_view.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_view.includes(ctx.subject)
      ),

    delete: (ctx: Context): boolean =>
      this.related.can_delete.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_delete.includes(ctx.subject)
      ),
  };
}
```

The `permits` block checks three paths for every action:
1. **Direct** — was the permission granted on this specific codebase?
2. **Owner** — does the subject own this codebase?
3. **Tenant** — was the permission granted at the tenant level?

<Component type="info">
The `owner.includes()` check works because the `owner` relation stores `User` subjects directly. If the subject matches one of the owners, the check passes — no traversal needed.
</Component>

## Agent Scoping Patterns [#agent-scoping-patterns]

### Codebase Scoped Agent [#codebase-scoped-agent]

A codebase-scoped agent gets permissions directly on a specific codebase. It can only act on repos it has been explicitly granted access to.

```
Agent ──can_push──▶ Codebase#cb-123
```

**Grant:**

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'can_push',
    subjectId: 'agent-pr-reviewer',
    subjectNamespace: 'Agent',
  },
});

await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'can_view',
    subjectId: 'agent-pr-reviewer',
    subjectNamespace: 'Agent',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "can_push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-pr-reviewer",
    },
}).Execute()

_, _, err = client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "can_view",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-pr-reviewer",
    },
}).Execute()
```
</Tab>
</Tabs>

**Check:**

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Can agent-pr-reviewer push to cb-123?
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'push',
    subjectId: 'agent-pr-reviewer',
    subjectNamespace: 'Agent',
  },
});
// data.allowed → true
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-pr-reviewer",
    },
}).Execute()
// result.Data.Allowed → true
```
</Tab>
</Tabs>

**Evaluation path:**
1. Is `agent-pr-reviewer` in `can_push` of `Codebase#cb-123`? → **Yes** (direct grant) → ALLOWED

```typescript
// Can agent-pr-reviewer push to cb-456? (different repo, no grant)
// data.allowed → false
```

**Evaluation path:**
1. Is `agent-pr-reviewer` in `can_push` of `Codebase#cb-456`? → No
2. Follow `owner` → no match
3. Follow `tenant` → agent has no tenant-level grant → DENIED

### Tenant Wide Agent [#tenant-wide-agent]

A tenant-wide agent gets permissions on the tenant itself. Because `permits.push` includes `tenant.traverse()`, the agent can push to every codebase under that tenant.

```
Agent ──can_push──▶ Tenant#org-abc ────tenant───▶ Codebase#cb-123
                                                    Codebase#cb-456
                                                    Codebase#cb-789
```

**Grant:**

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Tenant',
    object: 'org-abc',
    relation: 'can_push',
    subjectId: 'agent-ci-bot',
    subjectNamespace: 'Agent',
  },
});

await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Tenant',
    object: 'org-abc',
    relation: 'can_view',
    subjectId: 'agent-ci-bot',
    subjectNamespace: 'Agent',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Tenant",
    Object:    "org-abc",
    Relation:  "can_push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-ci-bot",
    },
}).Execute()

_, _, err = client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Tenant",
    Object:    "org-abc",
    Relation:  "can_view",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-ci-bot",
    },
}).Execute()
```
</Tab>
</Tabs>

Now `agent-ci-bot` can push to and view every codebase in `Tenant#org-abc`.

**Check:**

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Can agent-ci-bot push to cb-123 (a repo in org-abc)?
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'push',
    subjectId: 'agent-ci-bot',
    subjectNamespace: 'Agent',
  },
});
// data.allowed → true
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-ci-bot",
    },
}).Execute()
// result.Data.Allowed → true
```
</Tab>
</Tabs>

**Evaluation path:**
1. Is `agent-ci-bot` in `can_push` of `Codebase#cb-123`? → No (no direct grant)
2. Follow `owner` → no match
3. Follow `tenant` → the codebase belongs to `Tenant#org-abc`
4. Is `agent-ci-bot` in `can_push` of `Tenant#org-abc`? → **Yes** (tenant-wide grant) → ALLOWED

```typescript
// Same check for cb-456:
// data.allowed → true (same tenant, same traversal)
```

### Comparison [#comparison]

| Aspect | Codebase Scoped Agent | Tenant Wide Agent |
|--------|----------------------|-------------------|
| Grant target | Specific codebase | Tenant |
| Scope | Single repo | All repos in the org |
| Grant calls | One per codebase | One for the whole org |
| Use case | Dedicated PR reviewer per repo | CI bot that needs access to everything |
| Traversal used | Direct relation only | `tenant.traverse()` fallback |

## Practical Workflow [#practical-workflow]

### Creating a Codebase [#creating-a-codebase]

When a user creates a new codebase, the backend sets up ownership:

<Tabs groupId="lang" items={["Go","TypeScript"]}>
<Tab value="Go">
```go
// On codebase creation, set the owner
keto.CreateRelationTuple(ctx, KetoRelationTuple{
  Namespace: "Codebase",
  Object:    codebaseID,
  Relation:  "owner",
  Subject:   fmt.Sprintf("User:%s", userID),
})

// Link to the tenant for traversal
keto.CreateRelationTuple(ctx, KetoRelationTuple{
  Namespace: "Codebase",
  Object:    codebaseID,
  Relation:  "tenant",
  Subject:   fmt.Sprintf("Tenant:%s", tenantID),
})
```
</Tab>

<Tab value="TypeScript">
```typescript
// On codebase creation, set the owner
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: codebaseId,
    relation: 'owner',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});

// Link to the tenant for traversal
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: codebaseId,
    relation: 'tenant',
    subjectId: tenantId,
    subjectNamespace: 'Tenant',
  },
});
```
</Tab>
</Tabs>

The `tenant` relation is what enables tenant-wide agents — it creates the edge that `traverse()` follows.

### Adding a Scoped Agent [#adding-a-scoped-agent]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Deploy a PR-review agent scoped to a single repo
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'can_view',
    subjectId: 'agent-pr-review',
    subjectNamespace: 'Agent',
  },
});
```
</Tab>

<Tab value="Go">
```go
// Deploy a PR-review agent scoped to a single repo
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "can_view",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-pr-review",
    },
}).Execute()
```
</Tab>
</Tabs>

### Adding a Tenant-Wide Agent [#adding-a-tenant-wide-agent]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Deploy a CI bot that works across all repos
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Tenant',
    object: 'org-abc',
    relation: 'can_push',
    subjectId: 'agent-ci-bot',
    subjectNamespace: 'Agent',
  },
});
```
</Tab>

<Tab value="Go">
```go
// Deploy a CI bot that works across all repos
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Tenant",
    Object:    "org-abc",
    Relation:  "can_push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-ci-bot",
    },
}).Execute()
```
</Tab>
</Tabs>

### Checking in Middleware [#checking-in-middleware]

Use the standard permission check pattern in your backend handlers. The subject namespace is resolved automatically from the auth context:

<Tabs groupId="lang" items={["Go","TypeScript"]}>
<Tab value="Go">
```go
// Handler that needs push permission
func PushToCodebase(c *gin.Context) {
  codebaseID := c.Param("codebase_id")

  if err := keto.CheckPermission(c, "Codebase", codebaseID, "push"); err != nil {
    c.JSON(403, gin.H{"error": "forbidden"})
    return
  }

  // Agent or User has push — proceed
}
```
</Tab>

<Tab value="TypeScript">
```typescript
// Handler that needs push permission
async function pushToCodebase(req, res) {
  const codebaseId = req.params.codebase_id;

  const { data } = await permissionsApi.checkPermission({
    checkPermissionRequest: {
      namespace: 'Codebase',
      object: codebaseId,
      relation: 'push',
      subjectId: req.userId,
      subjectNamespace: 'User',
    },
  });

  if (!data.data.allowed) {
    return res.status(403).json({ error: 'forbidden' });
  }

  // Agent or User has push — proceed
}
```
</Tab>
</Tabs>

The Keto engine evaluates the OPL `permits.push` logic, which includes all three traversal paths. Whether the permission was granted directly, through ownership, or through the tenant — the check resolves the same way.

# Relations & Traversal (/concepts/permissions/relations-traversal)

Objects don't exist in isolation — they relate to each other. A **relation** is a directed edge from one object to another. Relations form a graph, and permission checks can *traverse* this graph to resolve access.

## What Is a Relation? [#what-is-a-relation]

A relation connects a subject to an object for a specific action. It is stored as a tuple:

```
(Namespace, ObjectID, Relation, SubjectNamespace, SubjectID)
```

For example:

```
(Tenant, tenant_xyz, can_invite_user, User, user_abc)
```

This means: "User `user_abc` can invite users to Tenant `tenant_xyz`."

## Simple Relations: Direct Permission [#simple-relations-direct-permission]

The simplest form — a subject has a permission directly on an object.

```
User ──can_invite_user──▶ Tenant
User ──can_edit─────────▶ Codebase
Agent──can_push─────────▶ Codebase
```

This is a flat check: does the subject have the relation on this specific object?

<Tabs groupId="lang" items={["Go","TypeScript"]}>
<Tab value="Go">
```go
// Check if user can invite on the tenant
checkPermission(ctx, "Tenant", tenantId, "can_invite_user")

// Check if agent can push to a codebase
checkPermission(ctx, "Codebase", codebaseId, "push")
```
</Tab>

<Tab value="TypeScript">
```typescript
// Check if user can invite on the tenant
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Tenant',
    object: tenantId,
    relation: 'can_invite_user',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});

// Check if agent can push to a codebase
const { data: pushCheck } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Codebase',
    object: codebaseId,
    relation: 'push',
    subjectId: agentId,
    subjectNamespace: 'Agent',
  },
});
```
</Tab>
</Tabs>

No indirection. The `permits` block for this is a direct `includes` check:

```typescript
permits = {
  invite_user: (ctx): boolean =>
    this.related.can_invite_user.includes(ctx.subject),
};
```

## Chained Relations: The `traverse()` Method [#chained-relations-the-traverse-method]

Objects often relate to other objects. A `Codebase` belongs to a `Tenant`. A `Project` has a `parent_project`. These relations create chains, and you can follow them with `traverse()`.

When you include a relation like `tenant: Tenant[]` in a `related` block, and that relation is marked `@hidden`, it exists purely for traversal. In the `permits` block, `traverse()` follows that edge and checks the permission on the related object:

```typescript
export class Codebase implements Namespace {
  related: {
    /** @hidden — link to owning tenant for traversal */
    tenant: Tenant[];

    can_edit: (User | Agent)[];
  };

  permits = {
    edit: (ctx): boolean =>
      // Check direct permission on codebase
      this.related.can_edit.includes(ctx.subject) ||
      // Fall back: does the subject have can_edit on the owning tenant?
      this.related.tenant.traverse((t) =>
        t.related.can_edit.includes(ctx.subject)
      ),
  };
}
```

This creates a two-step check:

```
Subject ──can_edit──▶ Codebase
                        └──tenant──▶ Tenant
                                      └──can_edit──▶ (checked here as fallback)
```

### How Traversal Works [#how-traversal-works]

1. Check if the subject has `can_edit` **directly** on `Codebase#cb-123`
2. If **no**, follow the `tenant` relation to find the owning Tenant
3. Check if the subject has `can_edit` on that Tenant instead
4. If either check passes → ALLOWED

The `||` operator chains multiple fallbacks. You can traverse through multiple relations:

```typescript
permits = {
  edit: (ctx): boolean =>
    this.related.can_edit.includes(ctx.subject) ||
    this.related.owner.includes(ctx.subject) ||
    this.related.tenant.traverse((t) =>
      t.related.can_edit.includes(ctx.subject)
    ),
};
```

## Common Traversal Patterns [#common-traversal-patterns]

### Tenant → Resource [#tenant--resource]

Resources belong to a tenant. Granting a permission at the tenant level cascades to all resources under it.

```
User ──can_push──▶ Codebase
                    └──tenant──▶ Tenant → can_push (fallback)
```

A user with `can_push` on the tenant can push to every codebase in that tenant — no need to grant on each codebase individually.

### Owner → Resource [#owner--resource]

The owner of a resource inherits permissions through a direct `includes` check on the `owner` relation.

```
User ──can_delete──▶ Document
                      └──owner──▶ User matched via includes()
```

Setting a User as the `owner` of a Document gives them all permissions that check `this.related.owner.includes(ctx.subject)` in the permits block.

### Parent → Child [#parent--child]

Nested resources inherit from parents through multiple hops.

```
User ──can_write──▶ SubProject
                     └──parent_project──▶ Project → can_write (checked here)
```

## Practical Implications [#practical-implications]

| Grant Level | Effect |
|-------------|--------|
| Direct on resource | Only that specific resource |
| On the parent/tenant | All child resources inherit (if traversal is configured) |
| Via ownership | The owner inherits all owner-traversed permissions |

This means you design your permission strategy by choosing which level to grant at:

- **Per-resource** — grant `can_push` on `Codebase#cb-123` to Agent
- **Tenant-wide** — grant `can_push` on `Tenant#tenant-xyz` to User (covers all codebases)
- **Ownership** — set User as `owner` of `Codebase#cb-123` (covers all owner-traversed permissions)

## Next [#next]

See a complete example with two agent scoping patterns in the [OmniGit Example](/concepts/permissions/omni-git)

# Stripe Sync (/concepts/stripe-sync)

Omnibase's "Stripe as Code" approach stores billing configuration in PostgreSQL and syncs it to Stripe. This page explains the mechanism.

## The Problem [#the-problem]

Stripe has limitations for configuration management:

1. **Immutable history** — Products/prices with payments can't be deleted
2. **No version control** — No way to track changes over time
3. **No rollback** — Can't revert to a previous configuration
4. **Environment drift** — Hard to keep dev/staging/prod in sync

## The Solution [#the-solution]

Omnibase introduces a database-backed configuration layer:

```
┌─────────────────────────────────────────────────────────┐
│                  YOUR APPLICATION                        │
├─────────────────────────────────────────────────────────┤
│  stripe/                                                 │
│  ├── products.config.json                               │
│  ├── enterprise.config.json                             │
│  └── metered.config.json                                │
└─────────────────────────────────────────────────────────┘
                           │
                           │ omnibase stripe push
                           ▼
┌─────────────────────────────────────────────────────────┐
│                  OMNIBASE API                            │
├─────────────────────────────────────────────────────────┤
│  1. Validate configuration                              │
│  2. Compute diff with current state                     │
│  3. Apply changes to Stripe                             │
│  4. Store version in PostgreSQL                         │
└─────────────────────────────────────────────────────────┘
                           │
              ┌────────────┴────────────┐
              ▼                         ▼
┌─────────────────────┐    ┌─────────────────────┐
│     POSTGRESQL      │    │       STRIPE        │
├─────────────────────┤    ├─────────────────────┤
│  stripe_configs     │    │  Products           │
│  ├── id             │    │  Prices             │
│  ├── version        │    │  Meters             │
│  ├── config (JSONB) │    │  Coupons            │
│  ├── created_at     │    │  Webhooks           │
│  └── changes        │    │                     │
└─────────────────────┘    └─────────────────────┘
```

## Config ID vs Stripe ID [#config-id-vs-stripe-id]

Omnibase maintains a mapping between your config IDs and Stripe IDs:

```
Config ID          →    Stripe ID
───────────────────────────────────
pro_plan           →    prod_ABC123xyz
pro_monthly        →    price_DEF456abc
pro_yearly         →    price_GHI789def
```

This means:
- Your code always uses stable config IDs
- Stripe IDs can change (e.g., when recreating resources)
- Environment portability (same config, different Stripe accounts)

## The Diff Algorithm [#the-diff-algorithm]

When you push a configuration, Omnibase:

1. **Fetches current state** — Gets the latest config from PostgreSQL
2. **Computes diff** — Determines what changed
3. **Plans operations** — Decides create/update/archive for each resource
4. **Applies to Stripe** — Makes API calls to Stripe
5. **Records version** — Stores the new config with changes

### Example Diff [#example-diff]

```json
{
  "products": {
    "created": [{ "productId": "enterprise", "productName": "Enterprise" }],
    "updated": [{ "productId": "pro", "productName": "Professional" }],
    "archived": []
  },
  "prices": {
    "created": [{ "priceId": "enterprise_monthly", "productId": "enterprise" }],
    "updated": [],
    "archived": [{ "priceId": "old_price", "productId": "pro" }]
  }
}
```

## Archiving vs Deleting [#archiving-vs-deleting]

Stripe doesn't allow deleting resources with history. Omnibase handles this by:

1. **Archiving** — Marks the resource as inactive in Stripe
2. **Removing from config** — Excludes from future syncs
3. **Preserving history** — Maintains audit trail

```
Active Price                    Archived Price
────────────────────────────────────────────────
visible in API: yes    →       visible: no
usable for new subs: yes  →    usable: no
existing subs: work     →      existing: still work
```

## Version History [#version-history]

Every configuration change creates a new version:

```sql
SELECT id, version, created_at FROM stripe_configs ORDER BY created_at DESC;

-- id        │ version │ created_at
-- ──────────┼─────────┼─────────────────────
-- uuid-5    │ 2.1.0   │ 2024-01-15 10:30:00
-- uuid-4    │ 2.0.0   │ 2024-01-10 14:20:00
-- uuid-3    │ 1.2.0   │ 2024-01-05 09:15:00
-- uuid-2    │ 1.1.0   │ 2024-01-02 16:45:00
-- uuid-1    │ 1.0.0   │ 2024-01-01 12:00:00
```

View history via CLI:

```bash
omnibase stripe history
```

## Free Tier Support [#free-tier-support]

Stripe doesn't allow $0 prices. Omnibase handles this:

1. **Stores free prices in PostgreSQL** — Full config including $0 prices
2. **Skips Stripe sync for free prices** — Doesn't create in Stripe
3. **Handles checkout specially** — Free tier bypasses Stripe checkout

```json
{
  "id": "free_plan",
  "name": "Free",
  "prices": [{
    "id": "free_monthly",
    "amount": 0,  // Omnibase handles this
    "currency": "usd",
    "interval": "month"
  }]
}
```

## Pulling Existing Config [#pulling-existing-config]

Import from an existing Stripe account:

```bash
omnibase stripe pull
```

This:
1. Fetches all products, prices, meters from Stripe
2. Generates config IDs based on Stripe metadata or names
3. Creates a local configuration file
4. You can then customize and push

## Multi-File Configs [#multi-file-configs]

Omnibase merges all `*.config.json` files in `omnibase/stripe/`:

```
omnibase/stripe/
├── core.config.json      # Base products
├── enterprise.config.json # Enterprise tier
└── addons.config.json    # Add-on products
```

All files are merged before pushing, allowing modular organization.

## Related Topics [#related-topics]

- [Stripe Configuration Guide](/guides/stripe-config) — How to configure
- [API Reference: Stripe](/api/stripe) — Stripe API endpoints

# Tenants (/concepts/tenants)

Tenants are the core organizational unit in Omnibase. This page explains the mental model behind multi-tenancy and how data isolation works.

## What is a Tenant? [#what-is-a-tenant]

A **tenant** is an isolated container for users and data. Think of it as:

- A **company** in a B2B SaaS
- A **workspace** in a collaboration tool
- An **organization** in a developer platform

Each tenant has:
- Its own data, isolated via Row-Level Security
- A Stripe customer for billing
- Members with role-based permissions
- Independent configuration

## Tenant Lifecycle [#tenant-lifecycle]

```
┌─────────────────────────────────────────────────────────┐
│                    TENANT CREATION                       │
├─────────────────────────────────────────────────────────┤
│  1. User calls createTenant()                           │
│  2. Omnibase creates tenant record                      │
│  3. Stripe customer created automatically               │
│  4. Creating user assigned as owner                     │
│  5. Keto relationship created: user → owner → tenant    │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                    TENANT ACTIVE                         │
├─────────────────────────────────────────────────────────┤
│  • Members can be invited                               │
│  • Data is isolated via RLS                             │
│  • Subscriptions can be added                           │
│  • Billing goes to tenant's Stripe customer             │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                    TENANT DELETION                       │
├─────────────────────────────────────────────────────────┤
│  1. Owner calls deleteTenant()                          │
│  2. All memberships removed                             │
│  3. Stripe subscriptions cancelled                      │
│  4. Data marked for deletion                            │
│  5. Keto relationships cleaned up                       │
└─────────────────────────────────────────────────────────┘
```

## Active Tenant Context [#active-tenant-context]

Users can belong to multiple tenants. The **active tenant** determines:

1. **Data visibility** — RLS policies filter by `auth.active_tenant_id()`
2. **Billing context** — Which Stripe customer is used
3. **Permission scope** — Which tenant's roles apply

### How Active Tenant Works [#how-active-tenant-works]

```
┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│   Request    │───▶│  JWT/Cookie  │───▶│  RLS Policy  │
│              │    │  tenant_id   │    │  Filters     │
└──────────────┘    └──────────────┘    └──────────────┘
```

When a user authenticates:
1. Their active tenant is stored in the session
2. API requests include tenant context
3. Database queries are automatically filtered

### Switching Tenants [#switching-tenants]

```typescript
// User has access to multiple tenants
const tenants = await tenantsApi.listTenants();
// [{ tenant: { id: 'acme', name: 'Acme Corp' } },
//  { tenant: { id: 'globex', name: 'Globex Inc' } }]

// Switch to a different tenant
await tenantsApi.switchActiveTenant({
  switchTenantRequest: { tenantId: 'globex' }
});

// Now all queries are scoped to Globex
```

## Data Isolation with RLS [#data-isolation-with-rls]

PostgreSQL Row-Level Security ensures tenants can't access each other's data:

```sql
-- The auth.active_tenant_id() function returns the current tenant
CREATE POLICY tenant_isolation ON projects
  USING (tenant_id = auth.active_tenant_id());
```

### How It Works [#how-it-works]

1. User makes API request with session cookie
2. API extracts tenant_id from JWT
3. `SET LOCAL` sets the tenant context for the transaction
4. All queries automatically filter by tenant

```sql
-- Behind the scenes, this query:
SELECT * FROM projects;

-- Becomes:
SELECT * FROM projects WHERE tenant_id = 'current-tenant-id';
```

## Tenant Members [#tenant-members]

Each tenant has members with roles:

| Role | Access Level |
|------|--------------|
| `owner` | Full control, can delete tenant |
| `admin` | Manage members, view billing |
| `member` | Standard access |

### Member Hierarchy [#member-hierarchy]

```
Tenant: Acme Corp
├── alice@acme.com (owner)
├── bob@acme.com (admin)
├── carol@acme.com (member)
└── dave@acme.com (member)
```

## Single-Tenant Applications [#single-tenant-applications]

Omnibase works for single-tenant apps too:

1. Create one tenant at signup
2. All users belong to that tenant
3. Skip tenant switching UI
4. RLS still provides security benefits

## Related Topics [#related-topics]

- [Multi-Tenancy Guide](/guides/multi-tenancy) — Implementation guide
- [RBAC Guide](/guides/rbac) — Role configuration
- [Permissions Concepts](/concepts/permissions) — How permissions work

# Backend API Keys (/guides/authentication/api-keys)

Server-side callers use one key. The request header selects how that key is interpreted.

| Header | Mode | User context | Checks |
|--------|------|--------------|--------|
| `X-Service-Key` | Admin | optional, trusted | skipped |
| `X-App-Key` | App | required (`X-User-Id`, `X-Tenant-Id`) | run as that user |
| Cookie / `X-Session-Token` | Session | from the Kratos session | run as that user |

The admin key and app key are the **same value** (`API_SERVICE_KEY`). Do not create a second secret.

## Admin mode [#admin-mode]

Use `X-Service-Key` for infrastructure, CI, migrations, Stripe admin, archive-all, and cleanup jobs. This mode is trusted: it does not require tenant headers, and any `X-User-Id`/`X-Tenant-Id` you send are taken at face value.

```ts
import { Configuration } from '@omnibase/core-js';

const admin = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: {
    'X-Service-Key': process.env.OMNIBASE_SERVICE_KEY!,
  },
});
```

Admin-only routes — database migrations, `stripe/admin/*`, `archive-all`, and permission namespaces — reject app mode.

## App mode [#app-mode]

Use `X-App-Key` from a customer backend that calls Omnibase on behalf of a signed-in user. The value is the same key, but the request must identify the user and tenant:

- `X-User-Id` — required; missing or invalid returns `401`.
- `X-Tenant-Id` — required; missing, invalid, or not an active membership returns `403`.

The API acts as that user in that tenant and runs the route's authorization as that user.

```ts
const forUser = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: {
    'X-App-Key': process.env.OMNIBASE_SERVICE_KEY!,
    'X-User-Id': user.id,
    'X-Tenant-Id': tenant.id,
  },
});
```

<Component type="warn">
Neither key belongs in a browser. Call Omnibase from your server, then forward only the data the browser needs.
</Component>

## Precedence [#precedence]

If a request sends both `X-Service-Key` and `X-App-Key`, admin mode wins. Send exactly one.

# Authentication Flows (/guides/authentication/flows)

Omnibase Auth provides pre-built flows for all common authentication scenarios. This guide covers how to implement each flow using the `FlowRouter` and shadcn components.

## FlowRouter Overview [#flowrouter-overview]

The `FlowRouter` is a server component that handles dynamic authentication routing. It fetches flow data and renders the appropriate form based on the URL.

### URL Structure [#url-structure]

```
/auth/login          → LoginForm
/auth/registration   → RegistrationForm
/auth/recovery       → RecoveryForm
/auth/verification   → VerificationForm
/auth/settings       → SettingsForm
/auth/error          → ErrorForm
/auth/onboarding     → TenantCreator (custom)
```

### Basic Setup [#basic-setup]

Create a catch-all route at `app/auth/[...flow]/page.tsx`:

```tsx title="app/auth/[...flow]/page.tsx"
import { FlowRouter } from '@omnibase/nextjs/auth';
import {
  LoginForm,
  RegistrationForm,
  RecoveryForm,
  VerificationForm,
  SettingsForm,
  ErrorForm,
} from '@omnibase/shadcn';

export default function AuthPage({
  params,
  searchParams,
}: {
  params: Promise<{ flow: string[] }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  return (
    <FlowRouter
      params={params}
      searchParams={searchParams}
      url="/auth"
      returnTo="/"
      flowMap={{
        login: (flow) => (
          <LoginForm flow={flow} register_url="/auth/registration" />
        ),
        registration: (flow) => (
          <RegistrationForm flow={flow} login_url="/auth/login" />
        ),
        recovery: (flow) => <RecoveryForm flow={flow} />,
        verification: (flow) => <VerificationForm flow={flow} />,
        settings: (flow) => <SettingsForm flow={flow} />,
        error: (error) => <ErrorForm error={error} login_url="/auth/login" />,
      }}
      onNotFound={<div>Page not found</div>}
    />
  );
}
```

---

## Login Flow [#login-flow]

The login flow authenticates existing users with email/password or OAuth.

### LoginForm Component [#loginform-component]

```tsx
<LoginForm
  flow={flow}
  register_url="/auth/registration"
  Header={<h1>Welcome Back</h1>}
/>
```

### Features [#features]

- Email/password authentication
- OAuth social login buttons (Google, GitHub, etc.)
- "Forgot password?" link to recovery
- "Don't have an account?" link to registration
- CSRF protection built-in
- Automatic verification redirect if email unverified

### Login Flow Diagram [#login-flow-diagram]

```
┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  /auth/login    │────▶│  Submit Form    │────▶│  Session Cookie │
│  (no flow param)│     │  (email + pass) │     │  Set & Redirect │
└─────────────────┘     └─────────────────┘     └─────────────────┘
         │                      │
         ▼                      ▼
┌─────────────────┐     ┌─────────────────┐
│  Creates new    │     │  Invalid?       │
│  login flow     │     │  Show errors    │
└─────────────────┘     └─────────────────┘
```

---

## Registration Flow [#registration-flow]

The registration flow creates new user accounts.

### RegistrationForm Component [#registrationform-component]

```tsx
<RegistrationForm
  flow={flow}
  login_url="/auth/login"
  Header={<h1>Create Account</h1>}
/>
```

### Features [#features-1]

- Email, password, and name fields
- OAuth registration buttons
- Password strength validation
- Duplicate email detection
- Automatic email verification trigger

### Identity Traits [#identity-traits]

By default, Omnibase collects these user traits:

```json
{
  "email": "user@example.com",
  "name": {
    "first": "John",
    "last": "Doe"
  }
}
```

---

## Recovery Flow [#recovery-flow]

The recovery flow handles password reset via email.

### RecoveryForm Component [#recoveryform-component]

```tsx
<RecoveryForm
  flow={flow}
  Header={<h1>Reset Password</h1>}
/>
```

### Recovery Flow Steps [#recovery-flow-steps]

<Component>
<Component>
### Request Recovery [#request-recovery]

User enters their email address and submits the form.
</Component>

<Component>
### Email Sent [#email-sent]

Omnibase Auth sends a recovery link to the email address.
</Component>

<Component>
### Click Link [#click-link]

User clicks the link in their email, which includes a recovery code.
</Component>

<Component>
### Set New Password [#set-new-password]

User enters a new password to complete recovery.
</Component>
</Component>

---

## Verification Flow [#verification-flow]

The verification flow confirms email addresses.

### VerificationForm Component [#verificationform-component]

```tsx
<VerificationForm
  flow={flow}
  autoRedirect={true}
  Header={<h1>Verify Email</h1>}
/>
```

### Features [#features-2]

- 6-digit PIN input for verification code
- Auto-submit when code is complete
- Automatic redirect after verification
- Resend code functionality

<Component type="info">
Verification is triggered automatically after registration if email verification is enabled in your configuration.
</Component>

---

## Settings Flow [#settings-flow]

The settings flow allows users to manage their account.

### SettingsForm Component [#settingsform-component]

```tsx
<SettingsForm flow={flow} />
```

### Available Settings Sections [#available-settings-sections]

| Section | Description |
|---------|-------------|
| **Profile** | Update name and other identity traits |
| **Password** | Change account password |
| **TOTP** | Set up authenticator app (Google Authenticator) |
| **WebAuthn** | Register security keys |
| **Passkeys** | Configure passkey authentication |
| **Backup Codes** | Generate recovery codes |

### Linking to Settings [#linking-to-settings]

```tsx
// Protected settings page
import { protectedRoute } from '@omnibase/nextjs/auth';

export default async function SettingsPage() {
  await protectedRoute('/auth/login');

  return (
    <div>
      <h1>Account Settings</h1>
      <a href="/auth/settings">Manage your account</a>
    </div>
  );
}
```

---

## Error Flow [#error-flow]

The error flow displays authentication errors gracefully.

### ErrorForm Component [#errorform-component]

```tsx
<ErrorForm
  error={error}
  login_url="/auth/login"
  Header={<h1>Something went wrong</h1>}
/>
```

### Common Error Scenarios [#common-error-scenarios]

- CSRF token mismatch
- Expired flow (user took too long)
- OAuth callback errors
- Rate limiting
- Invalid verification code

---

## Onboarding Flow (Custom) [#onboarding-flow-custom]

After authentication, users often need to create or join an organization. Use the `TenantCreator` component:

```tsx title="FlowRouter onboarding handler"
import { protectedRoute } from '@omnibase/nextjs/auth';
import { TenantCreator } from '@omnibase/shadcn';
import { V1TenantsApi } from '@omnibase/core-js';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';

// Inside FlowRouter flowMap:
onboarding: async () => {
  const session = await protectedRoute('/auth/login');
  const { token } = await searchParams;

  return (
    <TenantCreator
      config={{
        createForm: {
          billingEmail: {
            defaultValue: session.identity?.traits.email,
          },
          organizationName: {
            defaultValue: `${session.identity?.traits.name.first}'s Organization`,
          },
        },
        joinForm: {
          token: { defaultValue: token },
        },
      }}
      formActions={{
        createOrganizationAction: async (formData: FormData) => {
          'use server';
          const name = formData.get('organizationName') as string;
          const billingEmail = formData.get('billingEmail') as string;

          const client = new V1TenantsApi(getConfig());
          const { data } = await client.createTenant({
            createTenantRequest: { name, billingEmail },
            xUserId: session.identity?.id!,
          });

          const c = await cookies();
          c.set('omnibase_postgrest_jwt', data.token!);
          redirect('/');
        },
        joinOrganizationAction: async (formData: FormData) => {
          'use server';
          const token = formData.get('token') as string;

          const client = new V1TenantsApi(getConfig());
          const { data } = await client.acceptInvite({
            acceptInviteRequest: { token },
          });

          const c = await cookies();
          c.set('omnibase_postgrest_jwt', data.token!);
          redirect('/');
        },
      }}
    />
  );
}
```

### TenantCreator Features [#tenantcreator-features]

- Toggle between "Create" and "Join" modes
- Auto-fills user's email as billing email
- Handles invite token from URL parameters
- Server actions for form submission

---

## Flow Retrieval Functions [#flow-retrieval-functions]

For custom implementations, you can fetch flows directly. Pass the `searchParams` from your page props:

<Tabs items={["getLoginFlow","getRegistrationFlow","getRecoveryFlow","getVerificationFlow","getSettingsFlow"]}>
<Tab value="getLoginFlow">
```tsx title="app/auth/login/page.tsx"
import { getLoginFlow } from '@omnibase/nextjs/auth';

export default async function LoginPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const flow = await getLoginFlow({
    url: '/auth/login',
    searchParams,
  });

  if (!flow) {
    return <div>Unable to load login form</div>;
  }

  return <CustomLoginForm flow={flow} />;
}
```
</Tab>

<Tab value="getRegistrationFlow">
```tsx title="app/auth/registration/page.tsx"
import { getRegistrationFlow } from '@omnibase/nextjs/auth';

export default async function RegistrationPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const flow = await getRegistrationFlow({
    url: '/auth/registration',
    searchParams,
  });

  if (!flow) {
    return <div>Unable to load registration form</div>;
  }

  return <CustomRegistrationForm flow={flow} />;
}
```
</Tab>

<Tab value="getRecoveryFlow">
```tsx title="app/auth/recovery/page.tsx"
import { getRecoveryFlow } from '@omnibase/nextjs/auth';

export default async function RecoveryPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const flow = await getRecoveryFlow({
    url: '/auth/recovery',
    searchParams,
  });

  if (!flow) {
    return <div>Unable to load recovery form</div>;
  }

  return <CustomRecoveryForm flow={flow} />;
}
```
</Tab>

<Tab value="getVerificationFlow">
```tsx title="app/auth/verification/page.tsx"
import { getVerificationFlow } from '@omnibase/nextjs/auth';

export default async function VerificationPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const flow = await getVerificationFlow({
    url: '/auth/verification',
    searchParams,
  });

  if (!flow) {
    return <div>Unable to load verification form</div>;
  }

  return <CustomVerificationForm flow={flow} />;
}
```
</Tab>

<Tab value="getSettingsFlow">
```tsx title="app/auth/settings/page.tsx"
import { getSettingsFlow, protectedRoute } from '@omnibase/nextjs/auth';

export default async function SettingsPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  await protectedRoute('/auth/login');

  const flow = await getSettingsFlow({
    url: '/auth/settings',
    searchParams,
  });

  if (!flow) {
    return <div>Unable to load settings form</div>;
  }

  return <CustomSettingsForm flow={flow} />;
}
```
</Tab>
</Tabs>

---

## Custom Form Styling [#custom-form-styling]

All shadcn components use Tailwind CSS and can be customized:

### Via CSS Variables [#via-css-variables]

```css title="globals.css"
:root {
  --primary: 222.2 47.4% 11.2%;
  --primary-foreground: 210 40% 98%;
  --card: 0 0% 100%;
  --card-foreground: 222.2 47.4% 11.2%;
  /* ... other shadcn variables */
}
```

### Via Component Props [#via-component-props]

```tsx
<LoginForm
  flow={flow}
  Header={
    <div className="text-center">
      <img src="/logo.svg" alt="Logo" className="mx-auto h-12 w-12" />
      <h1 className="mt-4 text-2xl font-bold">Welcome to MyApp</h1>
    </div>
  }
/>
```

### Building Custom Forms [#building-custom-forms]

For full control, build your own forms using the flow data:

```tsx
function CustomLoginForm({ flow }: { flow: LoginFlow }) {
  return (
    <form action={flow.ui.action} method={flow.ui.method}>
      {flow.ui.nodes.map((node, i) => {
        if (node.attributes.node_type === 'input') {
          const attrs = node.attributes as UiNodeInputAttributes;
          return (
            <input
              key={i}
              name={attrs.name}
              type={attrs.type}
              defaultValue={attrs.value}
              required={attrs.required}
            />
          );
        }
        return null;
      })}
      <button type="submit">Sign In</button>
    </form>
  );
}
```

---

## Common Patterns [#common-patterns]

<Accordions type="single">
<Accordion title="Redirect after login">
Use the `return_to` query parameter:

```tsx
// Link to login with return URL
<a href={`/auth/login?return_to=${encodeURIComponent('/dashboard')}`}>
  Sign In
</a>
```

The `FlowRouter` automatically handles the redirect after successful authentication.
</Accordion>

<Accordion title="Pre-fill email from invite">
Pass the email as a query parameter:

```tsx
// Invite link
const inviteUrl = `/auth/registration?email=${encodeURIComponent(inviteeEmail)}`;
```
</Accordion>

<Accordion title="Require email verification">
This is configured in your Omnibase Auth settings. When enabled:

1. User registers and receives verification email
2. Login attempts redirect to verification if email unverified
3. After verification, user is redirected to their original destination
</Accordion>

<Accordion title="Handle OAuth errors">
OAuth errors are automatically routed to the `error` flow:

```tsx
error: (error) => (
  <ErrorForm
    error={error}
    login_url="/auth/login"
    Header={<h1>Authentication Failed</h1>}
  />
)
```
</Accordion>
</Accordions>

---

## Related [#related]

- [Session Management](/guides/authentication/sessions) - How sessions work
- [Middleware](/guides/authentication/middleware) - Protecting routes
- [Multi-Tenancy](/guides/multi-tenancy) - Tenant onboarding after auth

# Authentication Overview (/guides/authentication)

Omnibase Auth provides a complete authentication system with support for email/password login, social OAuth providers, multi-factor authentication, and secure session management.

## Key Features [#key-features]

<Component>
<Component title="Session Management" href="/docs/guides/authentication/sessions">
Server-side session handling with automatic cookie management
</Component>

<Component title="Authentication Flows" href="/docs/guides/authentication/flows">
Pre-built forms for login, registration, recovery, and verification
</Component>

<Component title="Route Protection" href="/docs/guides/authentication/middleware">
Middleware for protecting routes and managing tenant context
</Component>

<Component title="Account Settings" href="/docs/guides/authentication/flows#settings-flow">
User profile management, password changes, and MFA setup
</Component>
</Component>

## Supported Authentication Methods [#supported-authentication-methods]

| Method | Description |
|--------|-------------|
| **Email/Password** | Traditional username and password authentication |
| **Social OAuth** | Google, GitHub, and other OAuth providers |
| **Magic Links** | Passwordless email-based login |
| **TOTP** | Time-based one-time passwords (Google Authenticator) |
| **WebAuthn** | Security keys and biometric authentication |
| **Passkeys** | Modern passwordless authentication |

## Quick Start [#quick-start]

Here's how to add authentication to a Next.js application in three steps:

<Component>
<Component>
### Install the SDKs [#install-the-sdks]

```bash
bun add @omnibase/nextjs @omnibase/shadcn
```
</Component>

<Component>
### Create the Auth Route [#create-the-auth-route]

Create a catch-all route at `app/auth/[...flow]/page.tsx`:

```tsx
import { FlowRouter } from '@omnibase/nextjs/auth';
import {
  LoginForm,
  RegistrationForm,
  RecoveryForm,
  VerificationForm,
  SettingsForm,
  ErrorForm,
} from '@omnibase/shadcn';

export default function AuthPage({ params, searchParams }: any) {
  return (
    <div className="mt-[20vh]">
      <FlowRouter
        params={params}
        searchParams={searchParams}
        url="/auth"
        returnTo="/"
        flowMap={{
          login: (flow) => (
            <LoginForm flow={flow} register_url="/auth/registration" />
          ),
          registration: (flow) => (
            <RegistrationForm flow={flow} login_url="/auth/login" />
          ),
          recovery: (flow) => <RecoveryForm flow={flow} />,
          verification: (flow) => <VerificationForm flow={flow} />,
          settings: (flow) => <SettingsForm flow={flow} />,
          error: (error) => <ErrorForm error={error} login_url="/auth/login" />,
        }}
        onNotFound={<div>Page not found</div>}
      />
    </div>
  );
}
```
</Component>

<Component>
### Add the Session Provider [#add-the-session-provider]

Wrap your app with the `SessionProvider` in `app/layout.tsx`:

```tsx
import { SessionProvider } from '@omnibase/nextjs/auth';

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  );
}
```
</Component>
</Component>

## Middleware Setup [#middleware-setup]

Create a `middleware.ts` file in your project root to handle authentication and tenant checking:

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

export const middleware = createOmnibaseMiddleware(
  process.env.OMNIBASE_API_URL!,
  {
    tenant_check: true,
    tenant_check_paths: ['/'],
    tenant_check_redirect_url: '/auth/onboarding',
  }
);

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)'],
};
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `tenant_check` | `boolean` | `true` | Enable tenant membership validation |
| `tenant_check_paths` | `string[]` | `["/"]` | Paths that require tenant membership (supports wildcards like `/api/*`) |
| `tenant_check_redirect_url` | `string` | `"/auth/onboarding"` | URL to redirect users without a tenant |

<Component type="info">
See the [Middleware Guide](/guides/authentication/middleware) for detailed configuration options and patterns.
</Component>

## Project Structure [#project-structure]

A typical Next.js project with Omnibase Auth looks like this:

<Files>
<Folder name="app" defaultOpen>
<Folder name="auth">
<File name="[...flow]/page.tsx" />
</Folder>

<Folder name="api">
<Folder name="auth">
<File name="logout/route.ts" />
</Folder>
</Folder>

<File name="layout.tsx" />

<File name="page.tsx" />
</Folder>

<File name="middleware.ts" />
</Files>

## Authentication Flow [#authentication-flow]

```
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   Browser   │────▶│  Omnibase    │────▶│   Session   │
│   Request   │     │  Auth        │     │   Cookie    │
└─────────────┘     └──────────────┘     └─────────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │   Identity   │
                    │   Store      │
                    └──────────────┘
```

1. User submits credentials via a form (login, registration, etc.)
2. Omnibase Auth validates the credentials and creates a session
3. A secure HTTP-only cookie is set in the browser
4. Subsequent requests include the cookie for authentication

## SDK Options [#sdk-options]

Omnibase provides SDKs for different use cases:

<Tabs items={["Next.js","React","Core API"]}>
<Tab value="Next.js">
**Best for:** Server-side rendering, App Router, full-stack applications

```tsx
import {
  SessionProvider,
  getServerSession,
  protectedRoute,
  FlowRouter
} from '@omnibase/nextjs/auth';
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';
```

Features:
- Server Components support
- Automatic session hydration
- Built-in middleware for route protection
- Seamless cookie handling
</Tab>

<Tab value="React">
**Best for:** Client-side applications, SPAs, custom backends

```tsx
import {
  AuthClientProvider,
  useSession,
  useAuth
} from '@omnibase/react';
```

Features:
- React Context for session state
- `useSession` hook for accessing user data
- Client-side session management
- Works with any React framework
</Tab>

<Tab value="Core API">
**Best for:** Custom implementations, non-React frameworks, server-to-server

```typescript
import { Configuration, V1AuthApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: { 'X-Service-Key': process.env.SERVICE_KEY },
});

const authApi = new V1AuthApi(config);
```

Features:
- Direct API access
- Server-to-server authentication
- Programmatic user creation
- Full control over authentication flow
</Tab>
</Tabs>

## UI Components [#ui-components]

The `@omnibase/shadcn` package provides pre-built, customizable authentication forms:

| Component | Purpose |
|-----------|---------|
| `LoginForm` | Email/password login with optional OAuth |
| `RegistrationForm` | New user signup with identity traits |
| `RecoveryForm` | Password reset via email |
| `VerificationForm` | Email verification with 6-digit code |
| `SettingsForm` | Profile management, password change, MFA |
| `ErrorForm` | Display authentication errors gracefully |
| `TenantCreator` | Onboarding flow for creating/joining organizations |

<Component type="info">
All components are built with shadcn/ui and can be customized via CSS variables or by modifying the source.
</Component>

## Server-Side User Creation [#server-side-user-creation]

For backend operations (admin scripts, migrations, webhooks), create users directly via the API:

```typescript
import { Configuration, V1AuthApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: { 'X-Service-Key': process.env.OMNIBASE_SERVICE_KEY },
});

const authApi = new V1AuthApi(config);

// Create a new user programmatically
const { data } = await authApi.createUser({
  createUserRequest: {
    email: 'user@example.com',
    password: 'secure-password-123',
    name: { first: 'John', last: 'Doe' },
  },
});

console.log('Created user:', data.data.id);
```

## What's Next? [#whats-next]

<Component>
<Component title="Sessions" href="/docs/guides/authentication/sessions">
Deep dive into session management and providers
</Component>

<Component title="Authentication Flows" href="/docs/guides/authentication/flows">
Implement login, registration, and recovery flows
</Component>

<Component title="Middleware" href="/docs/guides/authentication/middleware">
Protect routes and manage tenant context
</Component>

<Component title="Backend API Keys" href="/docs/guides/authentication/api-keys">
Admin and app modes for server-side callers
</Component>
</Component>

# Authentication Middleware (/guides/authentication/middleware)

Omnibase provides Next.js middleware that handles authentication validation, tenant membership checking, and PostgREST JWT management automatically.

## Overview [#overview]

The middleware runs on every request and performs:

1. **Session validation** - Verifies the user is authenticated
2. **Tenant checking** - Ensures authenticated users belong to a tenant
3. **JWT management** - Sets up database access tokens

```
┌─────────────┐     ┌──────────────────┐     ┌─────────────────┐
│   Request   │────▶│   Middleware     │────▶│   Your App      │
│             │     │   - Auth check   │     │                 │
│             │     │   - Tenant check │     │                 │
│             │     │   - JWT setup    │     │                 │
└─────────────┘     └──────────────────┘     └─────────────────┘
        │                    │
        │                    ▼
        │           ┌──────────────────┐
        │           │   Redirect to    │
        │           │   /auth/login or │
        └──────────▶│   /auth/onboard  │
                    └──────────────────┘
```

## Basic Setup [#basic-setup]

Create a `middleware.ts` file in your project root:

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

const OMNIBASE_API_URL = process.env.OMNIBASE_API_URL!;

export const middleware = createOmnibaseMiddleware(OMNIBASE_API_URL);

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)'],
};
```

<Component type="info">
The matcher excludes static files and images from middleware processing for better performance.
</Component>

## Configuration Options [#configuration-options]

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `tenant_check` | `boolean` | `true` | Enable tenant membership validation |
| `tenant_check_paths` | `string[]` | `["/"]` | Paths that require tenant membership |
| `tenant_check_redirect_url` | `string` | `"/auth/onboarding"` | URL to redirect users without a tenant |

### Full Configuration Example [#full-configuration-example]

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

export const middleware = createOmnibaseMiddleware(
  process.env.OMNIBASE_API_URL!,
  {
    tenant_check: true,
    tenant_check_paths: ['/', '/dashboard', '/settings'],
    tenant_check_redirect_url: '/auth/onboarding',
  }
);

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|api/|auth/).*)'],
};
```

## Middleware Behavior [#middleware-behavior]

### Path Matching [#path-matching]

The middleware supports three matching patterns:

| Pattern | Behavior |
|---------|----------|
| `/dashboard` | Exact match and all subpaths (`/dashboard/settings`) |
| `/api/*` | Wildcard matches all paths starting with `/api/` |
| `/` | Matches the root and all subpaths |

### Authentication Flow [#authentication-flow]

<Component>
<Component>
### Session Check [#session-check]

Middleware retrieves the current session using `getServerSession()`.

- **Has session**: Continue to tenant check
- **No session**: Pass through (public routes) or handle via page-level protection
</Component>

<Component>
### Tenant Check [#tenant-check]

If `tenant_check` is enabled and the path matches `tenant_check_paths`:

- **Has tenant**: Continue to JWT check
- **No tenant**: Redirect to `tenant_check_redirect_url`
</Component>

<Component>
### PostgREST JWT [#postgrest-jwt]

Ensures the `omnibase_postgrest_jwt` cookie is set for database access:

- **Has JWT**: Continue
- **No JWT**: Fetch new JWT from API and set cookie
</Component>

<Component>
### Pass to App [#pass-to-app]

Request continues to your Next.js application with all cookies merged.
</Component>
</Component>

## Common Patterns [#common-patterns]

### Protect Everything Except Auth Routes [#protect-everything-except-auth-routes]

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

export const middleware = createOmnibaseMiddleware(
  process.env.OMNIBASE_API_URL!,
  {
    tenant_check: true,
    tenant_check_paths: ['/'],
    tenant_check_redirect_url: '/auth/onboarding',
  }
);

export const config = {
  // Exclude auth routes, static files, and API routes
  matcher: ['/((?!_next/static|_next/image|favicon.ico|auth/|api/).*)'],
};
```

### Disable Tenant Checking [#disable-tenant-checking]

For single-tenant applications or when handling tenants manually:

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

export const middleware = createOmnibaseMiddleware(
  process.env.OMNIBASE_API_URL!,
  {
    tenant_check: false,
  }
);
```

### Protect Specific Paths Only [#protect-specific-paths-only]

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

export const middleware = createOmnibaseMiddleware(
  process.env.OMNIBASE_API_URL!,
  {
    tenant_check: true,
    tenant_check_paths: ['/dashboard', '/settings', '/billing'],
    tenant_check_redirect_url: '/setup',
  }
);
```

## Combining with Page-Level Protection [#combining-with-page-level-protection]

Middleware handles the high-level routing, but you should also use `protectedRoute()` for additional security:

```tsx title="app/dashboard/page.tsx"
import { protectedRoute } from '@omnibase/nextjs/auth';

export default async function DashboardPage() {
  // Double-check authentication at the page level
  const session = await protectedRoute('/auth/login');

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome, {session.identity.traits.email}</p>
    </div>
  );
}
```

<Component type="info">
Page-level protection (`protectedRoute`) provides defense in depth and handles edge cases where middleware might be bypassed.
</Component>

## Real-World Example [#real-world-example]

Here's the complete middleware setup from the Omnibase dashboard:

```typescript title="middleware.ts"
import { createOmnibaseMiddleware } from '@omnibase/nextjs/middleware';

const OMNIBASE_API_URL = process.env.OMNIBASE_API_URL!;

export const middleware = createOmnibaseMiddleware(OMNIBASE_API_URL, {
  tenant_check: true,
  tenant_check_paths: ['/'],
  tenant_check_redirect_url: '/auth/onboarding',
});

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

This configuration:
- Validates sessions on all routes
- Requires tenant membership for the entire app
- Redirects new users to `/auth/onboarding` to create or join an organization
- Handles PostgREST JWT tokens automatically

## How It Works Internally [#how-it-works-internally]

### Tenant Check Middleware [#tenant-check-middleware]

```typescript
// Simplified version of internal implementation
function tenantCheckMiddleware(req, session, config) {
  // Skip if tenant check disabled
  if (!config.tenant_check) return NextResponse.next();

  // Skip non-matching paths
  if (!matchesPath(req.url, config.tenant_check_paths)) {
    return NextResponse.next();
  }

  // Skip if no session (handled elsewhere)
  if (!session) return NextResponse.next();

  // Check if user has active tenant
  const hasTenant = session.identity?.metadata_public?.active_tenant_id;

  if (!hasTenant) {
    return NextResponse.redirect(config.tenant_check_redirect_url);
  }

  return NextResponse.next();
}
```

### PostgREST JWT Middleware [#postgrest-jwt-middleware]

```typescript
// Simplified version of internal implementation
async function postgrestJWTCheckMiddleware(req, session, apiUrl) {
  // Skip if no session
  if (!session) return NextResponse.next();

  // Check for existing JWT
  const existingJWT = req.cookies.get('omnibase_postgrest_jwt');
  if (existingJWT) return NextResponse.next();

  // Fetch new JWT from API
  const response = await fetch(`${apiUrl}/api/v1/tenants/jwt`, {
    headers: { Cookie: req.headers.get('cookie') },
  });

  const { data } = await response.json();

  // Set JWT cookie
  const nextResponse = NextResponse.next();
  nextResponse.cookies.set('omnibase_postgrest_jwt', data.token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
  });

  return nextResponse;
}
```

## Troubleshooting [#troubleshooting]

### Infinite Redirect Loop [#infinite-redirect-loop]

**Symptom**: Browser shows "too many redirects" error.

**Cause**: Auth routes are being processed by tenant check middleware.

**Fix**: Exclude auth routes from the middleware matcher:

```typescript
export const config = {
  matcher: ['/((?!auth/).*)'],
};
```

### JWT Cookie Not Set [#jwt-cookie-not-set]

**Symptom**: Database queries fail with permission errors.

**Cause**: PostgREST JWT middleware couldn't fetch the token.

**Fix**: Ensure `OMNIBASE_API_URL` is correctly set and accessible from the middleware.

### Tenant Check Not Working [#tenant-check-not-working]

**Symptom**: Users without tenants can access protected routes.

**Cause**: Path not matching `tenant_check_paths`.

**Fix**: Use wildcards or ensure exact path matches:

```typescript
tenant_check_paths: ['/dashboard', '/dashboard/*', '/settings/*']
```

## Performance Considerations [#performance-considerations]

1. **Minimize matched paths** - Use specific matchers to avoid running middleware on static files
2. **Cache session data** - The middleware caches session checks within a request
3. **Exclude public routes** - Don't run middleware on truly public pages

```typescript
// Optimized matcher
export const config = {
  matcher: [
    // Only match app routes that need protection
    '/dashboard/:path*',
    '/settings/:path*',
    '/billing/:path*',
    '/',
  ],
};
```

## Related [#related]

- [Session Management](/guides/authentication/sessions) - How sessions work
- [Authentication Flows](/guides/authentication/flows) - Login, registration, and more
- [Multi-Tenancy Guide](/guides/multi-tenancy) - Working with tenants

# Session Management (/guides/authentication/sessions)

Sessions in Omnibase track authenticated users across requests. This guide covers how to set up session providers, retrieve session data, and protect routes.

## Session Architecture [#session-architecture]

```
┌─────────────────────────────────────────────────────────────────┐
│                         Browser                                  │
├─────────────────────────────────────────────────────────────────┤
│  Cookie: ory_kratos_session=<session_token>                     │
│  Cookie: omnibase_postgrest_jwt=<tenant_jwt>                    │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Omnibase API                                │
├─────────────────────────────────────────────────────────────────┤
│  1. Validates session cookie                                     │
│  2. Extracts user identity                                       │
│  3. Determines active tenant                                     │
│  4. Sets database context for RLS                                │
└─────────────────────────────────────────────────────────────────┘
```

## Session Provider (Next.js) [#session-provider-nextjs]

The `SessionProvider` is an async server component that fetches the session and provides it to the component tree.

### Setup [#setup]

Add the provider to your root layout:

```tsx title="app/layout.tsx"
import { SessionProvider } from '@omnibase/nextjs/auth';

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  );
}
```

<Component type="info">
`SessionProvider` is a server component. It fetches the session on the server and hydrates the client with the session data.
</Component>

## Getting Session Data [#getting-session-data]

### Server Components (Recommended) [#server-components-recommended]

Use `getServerSession()` in server components for optimal performance:

```tsx title="app/dashboard/page.tsx"
import { getServerSession } from '@omnibase/nextjs/auth';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const session = await getServerSession();

  if (!session || !session.active) {
    redirect('/auth/login');
  }

  return (
    <div>
      <h1>Welcome, {session.identity.traits.email}!</h1>
      <p>User ID: {session.identity.id}</p>
      <p>Session expires: {new Date(session.expires_at).toLocaleString()}</p>
    </div>
  );
}
```

### Protected Route Helper [#protected-route-helper]

For pages that always require authentication, use `protectedRoute()`:

```tsx title="app/settings/page.tsx"
import { protectedRoute } from '@omnibase/nextjs/auth';

export default async function SettingsPage() {
  // Automatically redirects to /auth/login if not authenticated
  const session = await protectedRoute('/auth/login');

  return (
    <div>
      <h1>Settings for {session.identity.traits.name.first}</h1>
      {/* Settings form */}
    </div>
  );
}
```

### Client Components (React) [#client-components-react]

For client-side session access in React applications:

<Tabs items={["React SDK","Next.js (via context)"]}>
<Tab value="React SDK">
```tsx title="components/UserProfile.tsx"
'use client';

import { useSession } from '@omnibase/react';

export function UserProfile() {
  const { session, loading } = useSession();

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!session || !session.active) {
    return <div>Please log in to continue</div>;
  }

  return (
    <div>
      <img src={session.identity.traits.picture} alt="Profile" />
      <h2>{session.identity.traits.email}</h2>
      <p>Member since: {new Date(session.identity.created_at).toLocaleDateString()}</p>
    </div>
  );
}
```
</Tab>

<Tab value="Next.js (via context)">
When using `SessionProvider`, you can access session data via the Ory Elements session hook:

```tsx title="components/UserMenu.tsx"
'use client';

import { useSession } from '@ory/elements-react/client';

export function UserMenu() {
  const session = useSession();

  if (!session) {
    return <a href="/auth/login">Sign In</a>;
  }

  return (
    <div>
      <span>{session.identity?.traits?.email}</span>
      <a href="/api/auth/logout">Sign Out</a>
    </div>
  );
}
```
</Tab>
</Tabs>

## Implementing Logout [#implementing-logout]

### API Route Method (Recommended) [#api-route-method-recommended]

Create an API route that handles the logout flow:

```typescript title="app/api/auth/logout/route.ts"
import { getLogoutFlow } from '@omnibase/nextjs/auth';

export async function POST() {
  const flow = await getLogoutFlow({
    returnTo: '/auth/login',
  });

  if (!flow) {
    return new Response('Not logged in', { status: 401 });
  }

  return await flow.action();
}
```

Then call it from a form or button:

```tsx title="components/LogoutButton.tsx"
export function LogoutButton() {
  return (
    <form action="/api/auth/logout" method="POST">
      <button type="submit">Sign Out</button>
    </form>
  );
}
```

### Client-Side Method (React) [#client-side-method-react]

For React applications without Next.js:

```tsx title="components/LogoutButton.tsx"
'use client';

import { useAuth } from '@omnibase/react';

export function LogoutButton() {
  const auth = useAuth();

  const handleLogout = async () => {
    const { data } = await auth.createBrowserLogoutFlow();
    window.location.href = data.logout_url;
  };

  return <button onClick={handleLogout}>Sign Out</button>;
}
```

## Session Cookies [#session-cookies]

Omnibase uses these cookies for authentication:

| Cookie | Purpose |
|--------|---------|
| `ory_kratos_session` | Main session token from Omnibase Auth |
| `ory_kratos_continuity` | Flow continuity for multi-step auth flows |
| `omnibase_postgrest_jwt` | JWT for database access with tenant context |

<Component type="warn">
All cookies are HTTP-only and secure. Never attempt to read or modify them via JavaScript.
</Component>

## Session with Tenant Context [#session-with-tenant-context]

When a user has an active tenant, the session includes tenant information:

```tsx title="app/dashboard/page.tsx"
import { getServerSession } from '@omnibase/nextjs/auth';
import { Configuration, V1AuthApi } from '@omnibase/core-js';

export default async function DashboardPage() {
  const session = await getServerSession();

  if (!session?.active) {
    redirect('/auth/login');
  }

  // Get the active tenant for this user
  const config = new Configuration({
    basePath: process.env.OMNIBASE_API_URL,
  });
  const authApi = new V1AuthApi(config);

  const { data: activeTenant } = await authApi.getActiveTenant();

  return (
    <div>
      <h1>Dashboard</h1>
      {activeTenant.data?.tenant ? (
        <p>Organization: {activeTenant.data.tenant.name}</p>
      ) : (
        <a href="/auth/onboarding">Create or join an organization</a>
      )}
    </div>
  );
}
```

## Session Validation Flow [#session-validation-flow]

<Component>
<Component>
### Request Arrives [#request-arrives]

Browser sends request with session cookie to your Next.js app.
</Component>

<Component>
### Middleware Validates [#middleware-validates]

`createOmnibaseMiddleware` checks the session and tenant membership.
</Component>

<Component>
### Session Retrieved [#session-retrieved]

`getServerSession()` or `protectedRoute()` fetches full session data.
</Component>

<Component>
### Component Renders [#component-renders]

Your page/component receives the authenticated user's session.
</Component>
</Component>

## Error Handling [#error-handling]

Handle session errors gracefully:

```tsx
import { getServerSession } from '@omnibase/nextjs/auth';

export default async function ProfilePage() {
  try {
    const session = await getServerSession();

    if (!session) {
      // No session - user is not logged in
      return <LoginPrompt />;
    }

    if (!session.active) {
      // Session expired
      return <SessionExpiredMessage />;
    }

    return <ProfileContent session={session} />;
  } catch (error) {
    // Auth service unavailable
    console.error('Failed to fetch session:', error);
    return <ServiceUnavailableMessage />;
  }
}
```

## Best Practices [#best-practices]

1. **Prefer server-side session checks** - Use `getServerSession()` in server components for security and performance.

2. **Use `protectedRoute()` for authenticated-only pages** - It handles redirects automatically.

3. **Don't store sensitive data in session traits** - Traits are visible to the client.

4. **Handle loading states** - Always show loading UI while `useSession()` is fetching.

5. **Implement proper logout** - Clear all auth cookies and redirect to login.

## Related [#related]

- [Authentication Flows](/guides/authentication/flows) - Implement login, registration, and recovery
- [Middleware](/guides/authentication/middleware) - Protect routes with middleware
- [Multi-Tenancy](/guides/multi-tenancy) - How sessions work with tenants

# Project Configuration (/guides/configuration)

Your project's behavior is defined by a single config file in the `omnibase/` directory — `omnibase.toml` — plus a set of gitignored environment files. The same file drives local development (`omnibase start`), the CLI, and managed hosting deploys.

`omnibase init` scaffolds a commented `omnibase/omnibase.toml` with every section below. TOML is the default, but `.jsonc`, `.json`, `.yaml`, and `.yml` are also supported.

## Full Example [#full-example]

```toml
# omnibase/omnibase.toml
project_id = "69df45c1-2580-4781-915f-b6ecdc792683"

# Apps to run locally and deploy. Each is a directory with a wrangler
# config and a `bun run dev` script.
[[deployments]]
name = "dashboard"
path = "../apps/dashboard"

[[deployments]]
name = "api"
path = "../apps/api"
port = 8788

[auth]
website_url = "{WEBSITE_URL}"
allowed_return_urls = ["{ALLOWED_RETURN_URLS}"]
cookie_secret = "{COOKIE_SECRET}"
log_level = "info"

  [[auth.oidc]]
  provider = "google"
  client_id = "{GOOGLE_CLIENT_ID}"
  client_secret = "{GOOGLE_CLIENT_SECRET}"

# Local-only settings. Never pushed to the cloud.
# [local]

# Version pins for the OmniBase control-plane images.
# Omitted services use "latest". Must be exact published tags.
[versions]
auth = "0.4.1"
api = "0.20.3"
perm = "0.4.0"
```

## Sections [#sections]

### `project_id` [#project_id]

Your Omnibase Cloud project ID, created when you set up managed hosting. Not needed for purely local development.

### `[[deployments]]` [#deployments]

The apps you're building. Each entry points at a directory containing a Cloudflare Wrangler app (a `wrangler.toml`/`wrangler.jsonc` plus a `bun run dev` script) — the same app you'd deploy to the edge.

- **`name`** — a label used in CLI output and cloud deploy naming
- **`path`** — directory relative to `omnibase/`
- **`port`** — local dev port; defaults to `8787 + deployment index`

`omnibase start` spawns `bun run dev` in every deployment directory and passes each the resolved environment (see below). If no deployments are configured, it falls back to a bundled sample `omnibase/workers/`.

### `[auth]` [#auth]

Controls the authentication service (Ory Kratos):

- **`website_url`** — your app's URL; used to build auth flow redirects
- **`allowed_return_urls`** — URLs Kratos will redirect back to after a flow
- **`cookie_secret`** — secret used to sign session cookies
- **`log_level`** — Kratos log level (`trace`, `debug`, `info`, `warn`, `error`)

#### `[[auth.oidc]]` [#authoidc]

Enables social login. One block per provider:

- **`provider`** — the provider key (e.g. `google`)
- **`client_id`** / **`client_secret`** — OAuth app credentials

The CLI maps these to `OIDC_<PROVIDER>_ENABLED`, `<PROVIDER>_CLIENT_ID`, and `<PROVIDER>_CLIENT_SECRET` env vars for the auth container.

### `[local]` [#local]

Local-development-only settings that are **never sent to the cloud**. Any key placed here stays on your machine; dev secrets and Stripe keys for local dev live in `omnibase/.env.local` (see [Environment Files](#environment-files)).

### `[env]` [#env]

Extra `KEY=VALUE` pairs applied to the local control-plane containers (merged into the same env the auth/API images receive).

### `[versions]` [#versions]

Pins the Docker image tags for the control plane. Valid keys are `auth`, `api`, and `perm`. Values must be exact published tags (checked against Docker Hub before applying); omitted services use `latest`.

`omnibase init` writes this block with the latest published versions, so a new project stays on those versions until you change them. The CLI version does not decide which service versions run: upgrade a service by editing its tag here, or remove the key to follow `latest`.

## Environment Files [#environment-files]

Secrets and per-environment values live in gitignored files next to the config:

```
omnibase/
├── omnibase.toml      # structure, committed
├── .env.local         # local secrets & defaults, gitignored
└── .env.<branch>      # per-environment overrides, gitignored
```

For example `omnibase/.env.local` for local dev, `omnibase/.env.staging` for staging, or `omnibase/.env.<branch_name>` for a cloud branch. Select one with `omnibase --env <name>`.

<Component type="info">
Values resolve per key, first non-empty wins:

`process.env` → `omnibase/.env.<branch>` (from `--env` or the interactive picker) → the literal `{VAR}` left in place.
</Component>

`{VAR}` references in `omnibase.toml` are interpolated from these sources. Unresolved references are left literal and the CLI warns. Secrets belong in `.env.*` files or `wrangler secret` — never in `[[deployments]]` wrangler `[vars]`, which are visible in the deployed worker.

## What Goes to the Cloud [#what-goes-to-the-cloud]

When you run `omnibase cloud env push`, everything is sent **except** `project_id`, `[[deployments]]`, and `[local]` — those stay local. Managed hosting applies the sections it understands (`[auth]`, `[versions]`, `[env]`, etc.) and reports the rest.

# Environment Variables & Secrets (/guides/deployments/environment-variables)

Deployments get variables from your `omnibase/.env.*` files. There are two distinct moments variables are used, and it's important to know which is which:

1. **Build time** — when the worker is compiled, variables are injected into the build process.
2. **Runtime** — when the worker runs, variables in the wrangler config `[vars]` are baked into the deployed worker.

## Resolution Order [#resolution-order]

Wherever a value is needed, it resolves per key, first non-empty wins:

`process.env` → `omnibase/.env.<env>` (selected with `--env`) → the literal `{VAR}` left in place

## Build-Time Variable Injection [#build-time-variable-injection]

`omnibase cloud workers deploy` runs `bunx wrangler deploy --dry-run --outdir .bundle` in each deployment directory with the resolved variables exported into the build process. Whatever your `build.command` reads from the environment is available while it runs.

This matters for anything that **inlines** values at build time — bundled client assets, generated config, static pages. Put those keys in the env file for the branch you're deploying:

```bash
# omnibase/.env.main
PUBLIC_API_URL=https://api.my-app.com
PUBLIC_WEBSITE_URL=https://my-app.com
```

Then deploy:

```bash
omnibase cloud workers deploy --env main
```

The values are present when the build runs, so they end up baked into the output bundle.

## Runtime Variables and `{VAR}` Interpolation [#runtime-variables-and-var-interpolation]

Runtime values live in the `[vars]` section of your deployment's wrangler config. Omnibase interpolates `{VAR}` references at package time, replacing each placeholder with the resolved value from `omnibase/.env.<env>`.

```jsonc
// apps/api/wrangler.jsonc
{
  "vars": {
    "PUBLIC_WEBSITE_URL": "{PUBLIC_WEBSITE_URL}",
    "OMNIBASE_API_URL": "{OMNIBASE_API_URL}"
  }
}
```

With `PUBLIC_WEBSITE_URL=https://my-app.com` in `omnibase/.env.main`, deploying `--env main` packages the worker with `PUBLIC_WEBSITE_URL` set to `https://my-app.com`.

This works the same in every wrangler format:

<Tabs items={["wrangler.jsonc","wrangler.toml","wrangler.json"]}>
<Tab value="wrangler.jsonc">
```jsonc
{
  "vars": {
    "OMNIBASE_API_URL": "{OMNIBASE_API_URL}"
  }
}
```
</Tab>

<Tab value="wrangler.toml">
```toml
[vars]
OMNIBASE_API_URL = "{OMNIBASE_API_URL}"
```
</Tab>

<Tab value="wrangler.json">
```json
{
  "vars": {
    "OMNIBASE_API_URL": "{OMNIBASE_API_URL}"
  }
}
```
</Tab>
</Tabs>

<Component type="info">
Unresolved `{VAR}` references are left literal and the CLI warns, so a typo'd key shows up at deploy time rather than silently failing later.
</Component>

## Secrets [#secrets]

Never put secrets in `[vars]`. Values in `[vars]` are visible in the deployed worker (they're embedded in the worker's environment). For API keys, signing secrets, and tokens use either:

- **`wrangler secret`** — stored as a Worker secret at deploy time
- **The managed-hosting secrets API** — secrets injected into the branch environment

`omnibase/.env.*` files are gitignored, so local secrets like Stripe keys stay off-disk-committed, but anything needed at runtime in the deployed worker should still go through `wrangler secret`.

# Deployments (/guides/deployments)

A **deployment** is any app you're building that runs on Cloudflare Workers. It doesn't matter what framework or language it uses — Hono, a Vite frontend, a Go or Rust Worker, Next.js via OpenNext, or anything else that can be deployed with `wrangler`. Omnibase treats every deployment the same way: it runs the app locally during development and ships it to the edge on deploy.

Deployments are declared in `omnibase/omnibase.toml` under `[[deployments]]`, each pointing at a directory with a `wrangler.toml`, `wrangler.jsonc`, or `wrangler.json`.

## What Can Be a Deployment? [#what-can-be-a-deployment]

Anything `wrangler` can deploy:

- **Hono / plain Workers** — a `src/index.ts` entrypoint
- **Frontend frameworks** — Next.js via OpenNext, Vite, Remix, and the like, compiled to a worker bundle
- **Compiled languages** — Go, Rust, Python, and anything else targeting the Workers runtime
- **Any other wrangler app** — as long as it has a wrangler config and produces a worker bundle

## Declaring Deployments [#declaring-deployments]

```toml
# omnibase/omnibase.toml
[[deployments]]
name = "dashboard"
path = "../apps/dashboard"

[[deployments]]
name = "api"
path = "../apps/api"
port = 8788
```

- **`name`** — a label used in CLI output and cloud deploy naming
- **`path`** — directory relative to `omnibase/`; must contain a wrangler config and a `bun run dev` script
- **`port`** — local dev port, defaults to `8787 + deployment index`

<Component type="info">
The Omnibase repo itself is a real example — `public/omnibase.toml` declares three deployments (`dashboard`, `docs`, `website`) pointing at `public/apps/*`, each with its own `wrangler.jsonc`.
</Component>

## Run Locally [#run-locally]

```bash
omnibase start
```

This starts the control plane (API, auth, permissions, Postgres, storage, email) with Docker Compose, then spawns `bun run dev` in every deployment directory on `http://localhost:<port>` (default `8787` for the first). Each dev server receives the same resolved environment it would get in the cloud.

## Deploy [#deploy]

```bash
omnibase cloud workers deploy
```

This builds, packages, and uploads one or more deployments to managed hosting:

1. Resolve the target environment — the one you selected interactively or passed with `--env`.
2. Load the resolved variables for that branch from `omnibase/.env.<env>` (falling back through the normal resolution order).
3. Run `bunx wrangler deploy --dry-run --outdir .bundle` in each deployment directory with those variables exported.
4. Package the output into a self-contained bundle and upload it; managed hosting deploys it to the edge and returns the live URL.

Each deployment declares a `build.command` in its wrangler config. `wrangler deploy --dry-run` runs that command before bundling, so `cloud workers deploy` builds the app as part of the deploy — there's no separate build step to run first. The command is whatever your framework or language uses (`bun run build`, `vite build`, `opennextjs-cloudflare build`, …).

Pick a deployment with `--name`, deploy them all with `--all`, or choose one interactively:

```bash
omnibase cloud workers deploy --env main
omnibase cloud workers deploy --env main --name dashboard
omnibase cloud workers deploy --env main --all
```

<Component>
<Component href="/cli/cloud/workers/deploy" title="Deploy Reference">
Full flags and the end-to-end build and upload flow
</Component>

<Component href="/guides/deployments/environment-variables" title="Environment Variables">
Build-time injection, `{VAR}` interpolation, and where secrets live
</Component>
</Component>

## The Build Hook [#the-build-hook]

`cloud workers deploy` builds your app through the wrangler config's `build.command`:

```jsonc
// apps/api/wrangler.jsonc
{
  "main": "dist/worker.js",
  "name": "my-api",
  "compatibility_date": "2026-09-21",
  "build": {
    "command": "bun run build"
  },
  "assets": {
    "directory": "dist/assets",
    "binding": "ASSETS"
  },
  "vars": {
    "PUBLIC_WEBSITE_URL": "{PUBLIC_WEBSITE_URL}",
    "OMNIBASE_API_URL": "{OMNIBASE_API_URL}"
  }
}
```

`build.command` is the only build entrypoint Omnibase needs — point it at whatever produces your worker bundle (and `assets` directory, if any). `cloud workers deploy` runs it before packaging, so the deployed artifact is always freshly built. Values like `{PUBLIC_WEBSITE_URL}` are placeholders filled from `omnibase/.env.<env>` at deploy time — see [Environment Variables](/guides/deployments/environment-variables).

## Workers [#workers]

For Hono-based edge functions, cron jobs, and queues on top of the sample worker, see the [Workers guide](/guides/workers).

# MCP Server (/guides/mcp-server)

The Omnibase MCP server lets AI coding assistants (Claude Code, Cursor, Windsurf, etc.) search and read Omnibase documentation directly. Documentation is bundled with the server and versioned alongside the API — no network requests needed.

## Install [#install]

```bash
npm install -g @omnibase/mcp-server
```

## Configure [#configure]

Add to your AI tool's MCP configuration:

### Claude Code [#claude-code]

```bash
claude mcp add omnibase-docs -- omnibase-mcp-server
```

### Claude Desktop / Cursor / Windsurf [#claude-desktop--cursor--windsurf]

Add to your MCP settings file:

```json
{
  "mcpServers": {
    "omnibase-docs": {
      "command": "omnibase-mcp-server"
    }
  }
}
```

## What it does [#what-it-does]

Once configured, your AI assistant can:

- **Search documentation** — find relevant guides, API references, and examples by keyword
- **Read full pages** — pull complete documentation content into the conversation
- **List all docs** — browse available documentation pages

The server version is pinned to the API version, so the docs your AI reads always match the API you're running.

## Available tools [#available-tools]

| Tool | Description |
|------|-------------|
| `omnibase_list_docs` | List all available documentation pages |
| `omnibase_search_docs` | Search documentation by keyword |
| `omnibase_get_doc` | Read the full content of a specific page |

# Multi-Tenancy Overview (/guides/multi-tenancy)

Omnibase provides a complete multi-tenant architecture with organization management, team invitations, role-based access control, and automatic data isolation via PostgreSQL Row-Level Security.

## Key Features [#key-features]

<Component>
<Component title="Tenant Management" href="/docs/guides/multi-tenancy/tenants">
Create organizations, switch contexts, and manage tenant lifecycle
</Component>

<Component title="Team Invitations" href="/docs/guides/multi-tenancy/invitations">
Invite users, manage memberships, and onboard team members
</Component>

<Component title="RBAC" href="/docs/guides/multi-tenancy/rbac">
Configure roles, permissions, and fine-grained access control
</Component>

<Component title="Data Isolation" href="/docs/guides/multi-tenancy/isolation">
Row-Level Security, JWT tokens, and tenant-scoped queries
</Component>
</Component>

## Architecture [#architecture]

Omnibase implements a **Row-Level Security (RLS) based multi-tenancy model** with three layers:

```
┌─────────────────────────────────────────────────────────────────┐
│                        USER REQUEST                              │
│         (Cookie/Session Token + Active Tenant Context)          │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     AUTHENTICATION LAYER                         │
│              Omnibase Auth (Identity + Sessions)                │
│         ┌─────────────────────────────────────────┐             │
│         │ JWT Claims: { user_id, tenant_id, role }│             │
│         └─────────────────────────────────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    AUTHORIZATION LAYER                           │
│                Omnibase Permissions (ReBAC)                     │
│         ┌─────────────────────────────────────────┐             │
│         │  Relation Tuples:                       │             │
│         │  (Tenant, acme-corp, owner, user:alice) │             │
│         └─────────────────────────────────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      DATA LAYER                                  │
│             PostgreSQL with Row-Level Security                  │
│         ┌─────────────────────────────────────────┐             │
│         │  WHERE tenant_id = auth.active_tenant() │             │
│         └─────────────────────────────────────────┘             │
└─────────────────────────────────────────────────────────────────┘
```

## What is a Tenant? [#what-is-a-tenant]

A **tenant** represents an organization, workspace, or account that groups users together. Each tenant has:

- **Isolated data** via PostgreSQL Row-Level Security (RLS)
- **A dedicated Stripe customer** for billing
- **Role-based access control (RBAC)** for members
- **Invitation system** for onboarding users
- **Custom roles** with fine-grained permissions

## Quick Start [#quick-start]

<Component>
<Component>
### Install the SDK [#install-the-sdk]

```bash
bun add @omnibase/core-js
```
</Component>

<Component>
### Create a Tenant [#create-a-tenant]

```typescript
import { Configuration, V1TenantsApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
});

const tenantsApi = new V1TenantsApi(config);

const { data } = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'Acme Corporation',
    billingEmail: 'billing@acme.com',
  },
});

console.log('Tenant ID:', data.data.tenant.id);
```
</Component>

<Component>
### Invite Team Members [#invite-team-members]

```typescript
await tenantsApi.createInvite({
  createTenantUserInviteRequest: {
    email: 'teammate@example.com',
    role: 'member',
    inviteUrl: 'https://app.example.com/auth/onboarding',
  },
});
```
</Component>
</Component>

## Tenant Types [#tenant-types]

| Type | Description | Use Case |
|------|-------------|----------|
| `organization` | Multi-user tenant with team features | B2B SaaS, team workspaces |
| `individual` | Single-user tenant | Personal accounts, solo users |

## SDK Options [#sdk-options]

<Tabs items={["Next.js","React","Core API"]}>
<Tab value="Next.js">
**Best for:** Server-side rendering, App Router, full-stack applications

```tsx
// Server Action for tenant switching
'use server';
import { V1TenantsApi } from '@omnibase/core-js';
import { revalidatePath } from 'next/cache';

export async function switchTenant(formData: FormData) {
  const tenantId = formData.get('tenant_id') as string;
  const tenantsApi = new V1TenantsApi(config);

  await tenantsApi.switchActiveTenant({
    switchTenantRequest: { tenantId },
  });

  revalidatePath('/');
}
```
</Tab>

<Tab value="React">
**Best for:** Client-side applications, SPAs

```tsx
import { useCallback } from 'react';
import { V1TenantsApi } from '@omnibase/core-js';

function TenantSwitcher({ tenants }) {
  const switchTenant = useCallback(async (tenantId: string) => {
    const api = new V1TenantsApi(config);
    await api.switchActiveTenant({
      switchTenantRequest: { tenantId },
    });
    window.location.reload();
  }, []);

  return (
    <select onChange={(e) => switchTenant(e.target.value)}>
      {tenants.map((t) => (
        <option key={t.id} value={t.id}>{t.name}</option>
      ))}
    </select>
  );
}
```
</Tab>

<Tab value="Core API">
**Best for:** Server-to-server, custom implementations

```typescript
import { Configuration, V1TenantsApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: { 'X-Service-Key': process.env.OMNIBASE_SERVICE_KEY },
});

const tenantsApi = new V1TenantsApi(config);

// Create tenant for a user
const { data } = await tenantsApi.createTenant(
  {
    createTenantRequest: { name: 'New Org' },
  },
  { headers: { 'X-User-Id': userId } }
);
```
</Tab>
</Tabs>

## Common Patterns [#common-patterns]

### Personal Workspace Pattern [#personal-workspace-pattern]

For apps where each user has their own isolated workspace:

1. Create one tenant per user at signup
2. Each user owns their own tenant with their own Stripe account
3. Skip tenant switching UI (unless they create additional workspaces)
4. RLS isolates each user's data automatically

### Personal + Team Workspaces [#personal--team-workspaces]

Support both individual and team contexts:

```typescript
// Personal workspace
const personal = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'My Workspace',
    type: 'individual',
  },
});

// Team workspace
const team = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'Acme Team',
    type: 'organization',
  },
});
```

## What's Next? [#whats-next]

<Component>
<Component title="Tenant Lifecycle" href="/docs/guides/multi-tenancy/tenants">
Create, switch, and delete tenants
</Component>

<Component title="Team Invitations" href="/docs/guides/multi-tenancy/invitations">
Invite users and manage memberships
</Component>

<Component title="RBAC" href="/docs/guides/multi-tenancy/rbac">
Configure roles, permissions, and access control
</Component>

<Component title="Data Isolation" href="/docs/guides/multi-tenancy/isolation">
Understand RLS and tenant scoping
</Component>
</Component>

# Team Invitations (/guides/multi-tenancy/invitations)

Omnibase provides a complete invitation workflow for onboarding team members to your organization.

## UI Components [#ui-components]

Omnibase provides pre-built shadcn components for team management in `@omnibase/shadcn`:

<Accordions>
<Accordion title="UserInvite Component">
Invite users with email validation and role selector.

```tsx
import { UserInvite } from '@omnibase/shadcn';

<UserInvite
  roles={['admin', 'member', 'viewer']}
  onInvite={async (inviteData) => {
    await tenantsApi.createInvite({
      createTenantUserInviteRequest: {
        email: inviteData.createTenantUserInviteRequest.email,
        role: inviteData.createTenantUserInviteRequest.role,
        inviteUrl: 'https://app.example.com/auth/onboarding',
      },
    });
  }}
/>
```

**Props:**
- `roles` — Array of available role names for selection
- `onInvite` — Callback with `CreateInviteRequest` when form submits
</Accordion>

<Accordion title="UserViewer Component">
Display team members with role management and removal.

```tsx
import { UserViewer } from '@omnibase/shadcn';

<UserViewer
  users={tenantUsers}
  availableRoles={['owner', 'admin', 'member']}
  canEditUsers={hasPermission('tenant#update_user_role')}
  onRoleUpdate={async (userId, newRole) => {
    await tenantsApi.updateTenantUserRole({
      updateTenantUserRoleRequest: { userId, role: newRole },
    });
  }}
  onRemoveUser={async (userId) => {
    await tenantsApi.removeTenantUser({
      removeTenantUserRequest: { userId },
    });
  }}
/>
```

**Props:**
- `users` — Array of `TenantUserResponse` from `listTenantUsers()`
- `availableRoles` — Role names for the dropdown
- `canEditUsers` — Whether to show edit controls
- `onRoleUpdate` — Callback for role changes
- `onRemoveUser` — Callback for user removal
</Accordion>

<Accordion title="TenantCreator Component">
Create new organizations or join via invite token. Auto-detects invite tokens from URL.

```tsx
import { TenantCreator } from '@omnibase/shadcn';

<TenantCreator
  config={{
    defaultMode: 'create',
    createOrganizationText: 'Create Organization',
    joinOrganizationText: 'Join Organization',
  }}
  formActions={{
    createOrganizationAction: async (formData) => {
      await tenantsApi.createTenant({
        createTenantRequest: {
          name: formData.get('organizationName') as string,
          billingEmail: formData.get('billingEmail') as string,
        },
      });
    },
    joinOrganizationAction: async (formData) => {
      await tenantsApi.acceptInvite({
        acceptInviteRequest: {
          token: formData.get('token') as string,
        },
      });
    },
  }}
/>
```

**Props:**
- `config.defaultMode` — `'create'` or `'join'`
- `config.createForm` — Customize labels and placeholders
- `config.joinForm` — Customize invite token input
- `formActions.createOrganizationAction` — Handle organization creation
- `formActions.joinOrganizationAction` — Handle invite acceptance

The component auto-fills invite tokens from `?invite_token=` URL parameter.
</Accordion>
</Accordions>

## Invitation Flow [#invitation-flow]

```
┌───────────┐     ┌───────────┐     ┌───────────┐     ┌───────────┐
│  Inviter  │────▶│  Create   │────▶│   Send    │────▶│  Invitee  │
│  (Admin)  │     │  Invite   │     │   Email   │     │  Accepts  │
└───────────┘     └───────────┘     └───────────┘     └───────────┘
                       │                                    │
                       │                                    │
                       ▼                                    ▼
              ┌───────────────┐                   ┌───────────────┐
              │ Token Created │                   │ User Added to │
              │ (7 day expiry)│                   │ Tenant + Role │
              └───────────────┘                   └───────────────┘
```

---

## Creating Invitations [#creating-invitations]

Users with the `tenant#invite_user` permission can invite new members.

### Basic Invitation [#basic-invitation]

```typescript
import { Configuration, V1TenantsApi } from '@omnibase/core-js';

const tenantsApi = new V1TenantsApi(config);

const { data: invite } = await tenantsApi.createInvite({
  createTenantUserInviteRequest: {
    email: 'newuser@example.com',
    role: 'member',
    inviteUrl: 'https://app.example.com/auth/onboarding',
  },
});

console.log('Token:', invite.data.token);
console.log('Expires:', invite.data.expires_at);
```

### Automatic Email Delivery [#automatic-email-delivery]

Omnibase automatically sends an invitation email to the invitee when you create an invite. The email includes:

- The organization name
- The assigned role
- A link to accept the invitation (using the `inviteUrl` you provide)

<Component type="info">
Make sure your Omnibase instance has email configured. The invite URL you provide will have the token appended as a query parameter: `{inviteUrl}?token={token}`
</Component>

The invitation email template can be customized. See the [Email Templates](/guides/email-templates) guide for details.

---

## Accepting Invitations [#accepting-invitations]

The invited user must be authenticated before accepting. Their email must match the invitation email.

### Accept an Invitation [#accept-an-invitation]

```typescript
const { data } = await tenantsApi.acceptInvite({
  acceptInviteRequest: {
    token: inviteToken,
  },
});

// User is now a member of the tenant
console.log('Joined tenant:', data.data.tenant.name);
console.log('Assigned role:', data.data.role);
console.log('JWT Token:', data.data.token);
```

### What Happens on Acceptance [#what-happens-on-acceptance]

<Component>
<Component>
### Token Validation [#token-validation]
Omnibase verifies the token is valid, not expired, and not already used.
</Component>

<Component>
### Email Verification [#email-verification]
The authenticated user's email must match the invitation email.
</Component>

<Component>
### Membership Creation [#membership-creation]
A `tenant_user` record is created linking the user to the tenant with the assigned role.
</Component>

<Component>
### Permission Assignment [#permission-assignment]
Permission relationships are created based on the role's permissions.
</Component>

<Component>
### Invite Marked Used [#invite-marked-used]
The invitation is marked as used and cannot be reused.
</Component>

<Component>
### Tenant Activation [#tenant-activation]
The new tenant becomes the user's active tenant, and a JWT token is returned.
</Component>
</Component>

<Component type="warn">
The invitee's email must exactly match the authenticated user's email. Invitations expire after 7 days and can only be used once.
</Component>

### Invitation Acceptance UI [#invitation-acceptance-ui]

Here's how to handle invitation acceptance in a Next.js app:

```tsx
// app/auth/onboarding/page.tsx
import { V1TenantsApi, Configuration } from '@omnibase/core-js';
import { redirect } from 'next/navigation';

export default async function OnboardingPage({
  searchParams,
}: {
  searchParams: { token?: string };
}) {
  const { token } = searchParams;

  if (token) {
    // User is accepting an invitation
    return <AcceptInviteForm token={token} />;
  }

  // User is creating a new organization
  return <CreateTenantForm />;
}

async function AcceptInviteForm({ token }: { token: string }) {
  async function acceptInvite() {
    'use server';

    const config = new Configuration({
      basePath: process.env.OMNIBASE_API_URL,
    });
    const tenantsApi = new V1TenantsApi(config);

    await tenantsApi.acceptInvite({
      acceptInviteRequest: { token },
    });

    redirect('/');
  }

  return (
    <form action={acceptInvite}>
      <h1>Accept Invitation</h1>
      <p>Click below to join the organization.</p>
      <button type="submit">Accept & Join</button>
    </form>
  );
}
```

---

## Managing Members [#managing-members]

### List Tenant Members [#list-tenant-members]

```typescript
const { data: members } = await tenantsApi.listTenantUsers();

for (const member of members.data) {
  console.log(`${member.email}: ${member.role}`);
  console.log(`  User ID: ${member.user_id}`);
  console.log(`  Joined: ${member.joined_at}`);
}
```

---

## Updating Member Roles [#updating-member-roles]

Users with the `tenant#update_user_role` permission can change member roles.

```typescript
await tenantsApi.updateTenantUserRole({
  updateTenantUserRoleRequest: {
    userId: targetUserId,
    role: 'admin',
  },
});
```

<Component type="info">
Changing a user's role immediately updates their permissions. The change takes effect on their next request.
</Component>

### Role Update Flow [#role-update-flow]

1. Verify the caller has `tenant#update_user_role` permission
2. Remove user from their current role's `user_ids` array
3. Delete old permission relationships for this tenant
4. Add user to new role's `user_ids` array
5. Create new permission relationships based on the new role

---

## Removing Members [#removing-members]

Users with the `tenant#remove_user` permission can remove members.

```typescript
await tenantsApi.removeTenantUser({
  removeTenantUserRequest: {
    userId: targetUserId,
  },
});
```

### What Happens on Removal [#what-happens-on-removal]

1. The `tenant_user` record is deleted
2. All permission relationships for this user in this tenant are removed
3. If this was their active tenant, another tenant becomes active
4. If they have no tenants left, their identity metadata is updated

<Component type="warn">
Owners cannot be removed from a tenant. The tenant must be deleted instead, or ownership must be transferred first.
</Component>

---

## Permission Requirements [#permission-requirements]

| Action | Required Permission |
|--------|---------------------|
| Create invitation | `tenant#invite_user` |
| Accept invitation | (Authenticated + matching email) |
| List members | `tenant#view_users` |
| Update member role | `tenant#update_user_role` |
| Remove member | `tenant#remove_user` |

### Built-in Role Permissions [#built-in-role-permissions]

| Role | invite_user | view_users | update_user_role | remove_user |
|------|-------------|------------|------------------|-------------|
| Owner | Yes | Yes | Yes | Yes |
| Admin | Yes | Yes | Yes | Yes |
| Member | No | No | No | No |

---

## Error Handling [#error-handling]

### Common Errors [#common-errors]

<Tabs items={["Invite Creation","Invite Acceptance"]}>
<Tab value="Invite Creation">
| Error | Cause | Solution |
|-------|-------|----------|
| `403 Forbidden` | User lacks `invite_user` permission | Ensure user is owner/admin or has custom role with permission |
| `400 Bad Request` | Invalid email format | Validate email before sending |
| `409 Conflict` | User already a member | Check membership before inviting |
</Tab>

<Tab value="Invite Acceptance">
| Error | Cause | Solution |
|-------|-------|----------|
| `404 Not Found` | Invalid or expired token | Request a new invitation |
| `400 Bad Request` | Email mismatch | User must authenticate with the invited email |
| `409 Conflict` | Invitation already used | Request a new invitation |
| `410 Gone` | Invitation expired | Request a new invitation |
</Tab>
</Tabs>

### Example Error Handling [#example-error-handling]

```typescript
try {
  await tenantsApi.acceptInvite({
    acceptInviteRequest: { token },
  });
} catch (error) {
  if (error.response?.status === 404) {
    console.error('Invalid or expired invitation');
  } else if (error.response?.status === 400) {
    console.error('Email does not match invitation');
  } else if (error.response?.status === 410) {
    console.error('Invitation has expired');
  } else {
    console.error('Failed to accept invitation:', error);
  }
}
```

---

## Related Guides [#related-guides]

- [Tenant Lifecycle](/guides/multi-tenancy/tenants) — Create and manage tenants
- [RBAC](/guides/multi-tenancy/rbac) — Configure roles and permissions
- [Role Configuration](/guides/multi-tenancy/rbac/roles) — Configure who can invite
- [Data Isolation](/guides/multi-tenancy/isolation) — How member data is scoped

# Data Isolation (/guides/multi-tenancy/isolation)

Omnibase uses PostgreSQL Row-Level Security (RLS) to enforce tenant isolation at the database level. This ensures that tenants can never access each other's data, even if application code has bugs.

## How It Works [#how-it-works]

```
┌──────────────┐    ┌──────────────┐    ┌──────────────┐
│   Request    │───▶│  JWT Token   │───▶│  RLS Policy  │
│              │    │  tenant_id   │    │   Filters    │
└──────────────┘    └──────────────┘    └──────────────┘
```

1. User makes API request with session cookie
2. API extracts `tenant_id` from JWT claims
3. JWT is passed to PostgREST
4. PostgreSQL RLS policies filter all queries by tenant

---

## JWT Token Structure [#jwt-token-structure]

Omnibase generates JWT tokens with tenant context:

```json
{
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "tenant_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "user_role": "owner",
  "role": "anon_user",
  "iat": 1699900000,
  "exp": 1699986400
}
```

---

## RLS Helper Functions [#rls-helper-functions]

Omnibase provides SQL helper functions for use in RLS policies:

```sql
-- Get current user ID (from JWT)
SELECT auth.user_id();
-- Returns: '550e8400-e29b-41d4-a716-446655440000'

-- Get active tenant ID (from JWT)
SELECT auth.active_tenant_id();
-- Returns: '7c9e6679-7425-40de-944b-e07fc1f90ae7'

-- Get user's role in active tenant (DB lookup)
SELECT auth.active_user_role();
-- Returns: 'owner'

-- Get all tenant IDs user belongs to
SELECT auth.user_tenant_ids();
-- Returns: ARRAY['tenant-1', 'tenant-2']

-- Check if user has a Keto relation on an object
SELECT auth.has_relation('Tenant', 'tenant-uuid', 'delete_tenant');
-- Returns: true/false

-- Check if user has ANY of the specified relations
SELECT auth.has_any_relation('StorageObject', 'object-uuid', ARRAY['owner', 'can_read']);
-- Returns: true/false
```

`active_tenant_id()` and `user_id()` read from JWT claims. `active_user_role()` queries `permissions.roles` directly and `has_relation()` / `has_any_relation()` query Keto relation tuples, so permission changes take effect immediately without requiring a new JWT.

### Implementation [#implementation]

```sql
CREATE OR REPLACE FUNCTION auth.user_id()
RETURNS text AS $$
  SELECT current_setting('request.jwt.claims', true)::json->>'user_id'
$$ LANGUAGE sql STABLE;

CREATE OR REPLACE FUNCTION auth.active_tenant_id()
RETURNS text AS $$
  SELECT current_setting('request.jwt.claims', true)::json->>'tenant_id'
$$ LANGUAGE sql STABLE;

-- Queries permissions.roles directly (not from JWT)
CREATE OR REPLACE FUNCTION auth.active_user_role()
RETURNS text AS $$
BEGIN
    RETURN (
        SELECT role_name FROM permissions.roles
        WHERE tenant_id = auth.active_tenant_id()::uuid
          AND auth.user_id()::uuid = ANY(user_ids)
        LIMIT 1
    );
END;
$$ LANGUAGE plpgsql STABLE;
```

---

## Creating Tenant-Scoped Tables [#creating-tenant-scoped-tables]

### Basic Pattern [#basic-pattern]

```sql
-- Create a tenant-scoped table
CREATE TABLE projects (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  description TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Enable RLS
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

-- Create isolation policy
CREATE POLICY tenant_isolation ON projects
  FOR ALL
  USING (tenant_id = auth.active_tenant_id()::uuid)
  WITH CHECK (tenant_id = auth.active_tenant_id()::uuid);

-- Grant access to the anon_user role
GRANT SELECT, INSERT, UPDATE, DELETE ON projects TO anon_user;
```

### Policy Breakdown [#policy-breakdown]

| Clause | Purpose |
|--------|---------|
| `FOR ALL` | Applies to SELECT, INSERT, UPDATE, DELETE |
| `USING` | Filter condition for SELECT, UPDATE, DELETE |
| `WITH CHECK` | Validation for INSERT, UPDATE |

### Separate Policies Pattern [#separate-policies-pattern]

For more granular control:

```sql
-- Read policy
CREATE POLICY projects_select ON projects
  FOR SELECT
  USING (tenant_id = auth.active_tenant_id()::uuid);

-- Insert policy (ensures tenant_id is set correctly)
CREATE POLICY projects_insert ON projects
  FOR INSERT
  WITH CHECK (tenant_id = auth.active_tenant_id()::uuid);

-- Update policy
CREATE POLICY projects_update ON projects
  FOR UPDATE
  USING (tenant_id = auth.active_tenant_id()::uuid)
  WITH CHECK (tenant_id = auth.active_tenant_id()::uuid);

-- Delete policy
CREATE POLICY projects_delete ON projects
  FOR DELETE
  USING (tenant_id = auth.active_tenant_id()::uuid);
```

---

## Querying with RLS [#querying-with-rls]

### Automatic Filtering [#automatic-filtering]

```typescript
// Using PostgREST client
const { data: projects } = await db
  .from('projects')
  .select('*')
  .eq('status', 'active');

// Only returns projects where tenant_id = current user's active tenant
// The WHERE tenant_id = '...' is added automatically by RLS
```

### Behind the Scenes [#behind-the-scenes]

```sql
-- Your query:
SELECT * FROM projects WHERE status = 'active';

-- What PostgreSQL actually executes:
SELECT * FROM projects
WHERE status = 'active'
  AND tenant_id = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
```

<Component type="info">
RLS policies are enforced at the database level. Even direct SQL queries through PostgREST are filtered. There's no way for application code to bypass this protection.
</Component>

---

## Database Roles [#database-roles]

Omnibase uses two PostgreSQL roles:

### anon_user [#anon_user]

- Used for all user requests via PostgREST
- RLS policies are enforced
- Limited permissions per table

### super_user [#super_user]

- Used for administrative operations
- Bypasses RLS policies
- Used by Omnibase API internally

```sql
-- Create roles
CREATE ROLE anon_user NOLOGIN;
CREATE ROLE super_user NOLOGIN;

-- anon_user has RLS enforced
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO anon_user;

-- super_user bypasses RLS
ALTER ROLE super_user SET row_security TO off;
```

---

## Database Schema [#database-schema]

### Core Tables [#core-tables]

<Files>
<Folder name="auth" defaultOpen>
<File name="tenants" />

<File name="tenant_users" />

<File name="tenant_settings" />

<File name="tenant_invites" />

<File name="identities" />
</Folder>

<Folder name="permissions">
<File name="roles" />

<File name="role_templates" />
</Folder>

<Folder name="storage">
<File name="objects" />
</Folder>
</Files>

### Schema Reference [#schema-reference]

<Accordions type="multiple">
<Accordion title="auth.tenants">
```sql
CREATE TABLE auth.tenants (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  stripe_customer_id TEXT,
  enterprise_template TEXT,
  enterprise_id TEXT,
  type TEXT NOT NULL DEFAULT 'organization',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);
```
</Accordion>

<Accordion title="auth.tenant_users">
```sql
CREATE TABLE auth.tenant_users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  user_id UUID NOT NULL REFERENCES auth.identities(id) ON DELETE CASCADE,
  role TEXT NOT NULL DEFAULT 'member',
  is_active BOOLEAN NOT NULL DEFAULT false,
  joined_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(tenant_id, user_id)
);
```

The `is_active` column tracks which tenant is currently active for each user. Only one tenant can be active per user at a time.
</Accordion>

<Accordion title="auth.tenant_invites">
```sql
CREATE TABLE auth.tenant_invites (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  email TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'member',
  token TEXT NOT NULL UNIQUE,
  inviter_id UUID NOT NULL,
  expires_at TIMESTAMPTZ NOT NULL,
  used_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW()
);
```
</Accordion>

<Accordion title="permissions.roles">
```sql
CREATE TABLE permissions.roles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  role_name TEXT NOT NULL,
  permissions TEXT[] NOT NULL DEFAULT '{}',
  template_id UUID REFERENCES permissions.role_templates(id),
  user_ids UUID[] NOT NULL DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(tenant_id, role_name)
);
```
</Accordion>

<Accordion title="storage.objects">
```sql
CREATE TABLE storage.objects (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  bucket_name TEXT NOT NULL,
  path TEXT NOT NULL,
  tenant_id UUID REFERENCES auth.tenants(id) ON DELETE CASCADE,
  user_id UUID NOT NULL,
  metadata JSONB,
  is_public BOOLEAN NOT NULL DEFAULT FALSE,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(bucket_name, path)
);
```

Per-object permissions (read, delete, make-public) are enforced via Keto relation tuples on the `StorageObject` namespace, not RLS policies. See [Storage](/guides/storage) for details.
</Accordion>
</Accordions>

---

## Cross-Tenant Queries [#cross-tenant-queries]

### Never Allowed via PostgREST [#never-allowed-via-postgrest]

User requests through PostgREST can never access other tenants' data:

```typescript
// Even if you somehow know another tenant's ID,
// RLS will filter it out
const { data } = await db
  .from('projects')
  .select('*')
  .eq('tenant_id', 'other-tenant-id');

// Returns: [] (empty array)
```

### Service-Level Access [#service-level-access]

For administrative operations, use service key authentication:

```typescript
import { Configuration, V1TenantsApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: {
    'X-Service-Key': process.env.OMNIBASE_SERVICE_KEY,
    'X-Tenant-Id': targetTenantId,  // Explicit tenant context
  },
});
```

---

## Cascade Deletes [#cascade-deletes]

When a tenant is deleted, all related data is automatically cleaned up via foreign key cascades:

```sql
-- When auth.tenants row is deleted:
-- ├── auth.tenant_users (CASCADE)
-- ├── auth.tenant_settings (CASCADE)
-- ├── auth.tenant_invites (CASCADE)
-- ├── permissions.roles (CASCADE)
-- ├── storage.objects (CASCADE)
-- └── All custom tables with tenant_id FK (CASCADE)
```

<Component type="warn">
Always use `ON DELETE CASCADE` for the `tenant_id` foreign key to ensure proper cleanup when tenants are deleted.
</Component>

---

## Multi-Tenant Indexes [#multi-tenant-indexes]

For optimal query performance, include `tenant_id` in indexes:

```sql
-- Bad: Index without tenant_id
CREATE INDEX idx_projects_status ON projects(status);

-- Good: Composite index with tenant_id first
CREATE INDEX idx_projects_tenant_status ON projects(tenant_id, status);

-- For unique constraints, include tenant_id
CREATE UNIQUE INDEX idx_projects_tenant_name
  ON projects(tenant_id, name);
```

### Why Tenant-First Indexes? [#why-tenant-first-indexes]

RLS adds `tenant_id = ?` to every query. Having `tenant_id` as the leading column in indexes allows PostgreSQL to efficiently filter rows before applying other conditions.

---

## Testing Data Isolation [#testing-data-isolation]

### k6 Integration Tests [#k6-integration-tests]

Omnibase includes tests that verify tenant isolation:

```typescript
// Create two separate users in separate tenants
const user1 = await createUser({ email: 'user1@test.com' });
const tenant1 = await createTenant({ name: 'Tenant 1' });

const user2 = await createUser({ email: 'user2@test.com' });
const tenant2 = await createTenant({ name: 'Tenant 2' });

// Create data in tenant1
await createProject({ name: 'Secret Project', tenantContext: tenant1 });

// Try to access from tenant2 context
const projects = await listProjects({ tenantContext: tenant2 });

// Verify: tenant2 cannot see tenant1's project
assert(projects.length === 0);
```

### Manual Verification [#manual-verification]

```sql
-- Connect as anon_user with tenant1 JWT
SET request.jwt.claims = '{"tenant_id": "tenant-1-id"}';

SELECT * FROM projects;
-- Returns only tenant-1's projects

-- Switch to tenant2 context
SET request.jwt.claims = '{"tenant_id": "tenant-2-id"}';

SELECT * FROM projects;
-- Returns only tenant-2's projects (tenant-1's are invisible)
```

---

## Common Patterns [#common-patterns]

<Accordions type="single">
<Accordion title="User-Owned Data Within Tenant">
For data owned by specific users within a tenant:

```sql
CREATE TABLE documents (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  user_id UUID NOT NULL,  -- Owner within tenant
  title TEXT NOT NULL,
  content TEXT,
  is_public BOOLEAN DEFAULT false,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Users can see their own docs OR public docs in their tenant
CREATE POLICY documents_select ON documents
  FOR SELECT
  USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND (user_id = auth.user_id()::uuid OR is_public = true)
  );

-- Users can only modify their own docs
CREATE POLICY documents_modify ON documents
  FOR ALL
  USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND user_id = auth.user_id()::uuid
  );
```
</Accordion>

<Accordion title="Role-Based Data Access">
Restrict access based on user role:

```sql
CREATE POLICY admin_only_data ON sensitive_table
  FOR ALL
  USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND auth.active_user_role() IN ('owner', 'admin')
  );
```
</Accordion>

<Accordion title="Relation-Gated Access (ReBAC)">
Gate rows on Keto relation tuples using `auth.has_relation()` or `auth.has_any_relation()`. This checks the same permission data the API middleware uses:

```sql
-- Only users with 'owner' or 'can_read' relation can see a storage object
CREATE POLICY storage_objects_read ON storage.objects
  FOR SELECT
  USING (
    tenant_id::text = auth.active_tenant_id()
    AND auth.has_any_relation('StorageObject', id::text, ARRAY['owner', 'can_read'])
  );
```

See [Row-Level Security](/guides/postgresql/rls) for more ReBAC RLS patterns.
</Accordion>

<Accordion title="Shared Reference Data">
For data shared across all tenants (read-only):

```sql
CREATE TABLE subscription_plans (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price INTEGER NOT NULL
);

-- No tenant_id column, no RLS needed
-- All users can read, only super_user can modify
GRANT SELECT ON subscription_plans TO anon_user;
```
</Accordion>
</Accordions>

---

## Related Guides [#related-guides]

- [Tenant Lifecycle](/guides/multi-tenancy/tenants) — Create and manage tenants
- [Roles & Permissions](/guides/multi-tenancy/roles) — Configure access control
- [Permissions Concept](/concepts/permissions) — How ReBAC works
- [Row-Level Security](/guides/postgresql/rls) — Writing custom RLS policies with ReBAC helpers
- [Storage](/guides/storage) — File storage with per-object permissions

# Tenant Lifecycle (/guides/multi-tenancy/tenants)

This guide covers creating tenants, switching between them, and handling tenant deletion.

## UI Components [#ui-components]

Omnibase provides pre-built shadcn components for tenant management in `@omnibase/shadcn`:

<Accordions>
<Accordion title="TenantCreator Component">
Create new organizations or join existing ones via invite token. Auto-detects `?invite_token=` from URL.

```tsx
import { TenantCreator } from '@omnibase/shadcn';

<TenantCreator
  config={{
    defaultMode: 'create',
    createOrganizationText: 'Create Organization',
    joinOrganizationText: 'Join Organization',
    createForm: {
      organizationName: { label: 'Organization Name', placeholder: 'Acme Inc' },
      billingEmail: { label: 'Billing Email', placeholder: 'billing@acme.com' },
    },
  }}
  formActions={{
    createOrganizationAction: async (formData) => {
      await tenantsApi.createTenant({
        createTenantRequest: {
          name: formData.get('organizationName') as string,
          billingEmail: formData.get('billingEmail') as string,
        },
      });
      redirect('/dashboard');
    },
    joinOrganizationAction: async (formData) => {
      await tenantsApi.acceptInvite({
        acceptInviteRequest: { token: formData.get('token') as string },
      });
      redirect('/dashboard');
    },
  }}
/>
```

**Props:**
- `config.defaultMode` — `'create'` or `'join'`
- `config.createForm` — Customize organization name and billing email inputs
- `config.joinForm` — Customize invite token input
- `formActions.createOrganizationAction` — Server action for creation
- `formActions.joinOrganizationAction` — Server action for joining
</Accordion>

<Accordion title="SwitchActiveTenant Component">
Dropdown for switching between tenants with optional "Create Tenant" action.

```tsx
import { SwitchActiveTenant } from '@omnibase/shadcn';

<SwitchActiveTenant
  tenants={userTenants}
  currentTenantId={activeTenantId}
  placeholder="Select organization..."
  formAction={async (formData) => {
    'use server';
    await tenantsApi.switchActiveTenant({
      switchTenantRequest: { tenantId: formData.get('tenant_id') as string },
    });
    revalidatePath('/', 'layout');
  }}
  onCreateTenant={() => router.push('/onboarding')}
  createTenantLabel="Create Organization"
/>
```

**Props:**
- `tenants` — Array of `Tenant` objects
- `currentTenantId` — Currently active tenant ID
- `formAction` — Server action that receives `FormData` with `tenant_id`
- `onTenantChange` — Client-side callback for tenant changes
- `onCreateTenant` — Callback when "Create Tenant" is clicked
- `createTenantLabel` — Custom label for create option
</Accordion>
</Accordions>

## Creating Tenants [#creating-tenants]

When you create a tenant, Omnibase automatically:

1. Creates the tenant record in the database
2. Creates a Stripe customer (if `billingEmail` is provided)
3. Assigns the creating user as `owner`
4. Clones role templates (`owner`, `admin`, `member`) for the tenant
5. Creates permission relationships for owner permissions
6. Generates a JWT token with the new tenant context
7. Sets this tenant as the user's active tenant

### Basic Creation [#basic-creation]

```typescript
import { Configuration, V1TenantsApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
});

const tenantsApi = new V1TenantsApi(config);

const { data } = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'Acme Corporation',
    billingEmail: 'billing@acme.com',
  },
});

console.log('Tenant ID:', data.data.tenant.id);
console.log('Stripe Customer:', data.data.tenant.stripe_customer_id);
console.log('JWT Token:', data.data.token);
```

---

## Listing Tenants [#listing-tenants]

Users can belong to multiple tenants. List all tenants for the current user:

```typescript
import { V1AuthApi } from '@omnibase/core-js';

const authApi = new V1AuthApi(config);

const { data } = await authApi.listTenants();

for (const item of data.data.tenants) {
  console.log(`${item.tenant.name}: ${item.isActive ? 'ACTIVE' : ''}`);
  console.log(`  Role: ${item.role}`);
  console.log(`  Joined: ${item.joinedAt}`);
}
```

---

## Switching Tenants [#switching-tenants]

The **active tenant** determines:

- Which data is visible (via RLS policies)
- Which Stripe customer is used for billing
- Which permissions are checked
- Which JWT claims are generated

### Switch Active Tenant [#switch-active-tenant]

```typescript
await tenantsApi.switchActiveTenant({
  switchTenantRequest: {
    tenantId: 'tenant_abc123',
  },
});

// All subsequent requests use the new tenant context
```

<Component type="info">
When switching tenants, Omnibase updates the `is_active` flag in `tenant_users`, generates a new JWT token, and all subsequent database queries automatically filter by the new tenant.
</Component>

### Get Active Tenant [#get-active-tenant]

```typescript
const { data } = await authApi.getActiveTenant();

console.log('Active Tenant:', data.data.tenant.name);
console.log('Your Role:', data.data.role);
```

### Tenant Switching in Next.js [#tenant-switching-in-nextjs]

<Tabs items={["Server Action","Client Component"]}>
<Tab value="Server Action">
```typescript
// app/actions.ts
'use server';

import { Configuration, V1TenantsApi } from '@omnibase/core-js';
import { revalidatePath } from 'next/cache';
import { cookies } from 'next/headers';

export async function switchTenant(formData: FormData) {
  const tenantId = formData.get('tenant_id') as string;

  const config = new Configuration({
    basePath: process.env.OMNIBASE_API_URL,
    // Pass cookies for authentication
  });

  const tenantsApi = new V1TenantsApi(config);

  await tenantsApi.switchActiveTenant({
    switchTenantRequest: { tenantId },
  });

  // Revalidate to refresh data with new tenant context
  revalidatePath('/', 'layout');

  return { success: true };
}
```
</Tab>

<Tab value="Client Component">
```tsx
'use client';

import { switchTenant } from './actions';

export function TenantSwitcher({ tenants, currentTenantId }) {
  return (
    <form action={switchTenant}>
      <select name="tenant_id" defaultValue={currentTenantId}>
        {tenants.map((t) => (
          <option key={t.id} value={t.id}>
            {t.name}
          </option>
        ))}
      </select>
      <button type="submit">Switch</button>
    </form>
  );
}
```
</Tab>
</Tabs>

---

## Tenant Lookup [#tenant-lookup]

For service-to-service operations, you can look up tenants by ID or Stripe customer ID:

### By Tenant ID [#by-tenant-id]

```typescript
const { data } = await tenantsApi.getTenantByID({
  tenantId: 'tenant_abc123',
});

console.log('Tenant:', data.data.tenant.name);
```

### By Stripe Customer ID [#by-stripe-customer-id]

Useful for Stripe webhook handlers:

```typescript
const { data } = await tenantsApi.getTenantByStripeCustomerID({
  stripeCustomerId: 'cus_abc123',
});

console.log('Tenant:', data.data.tenant.name);
```

<Component type="info">
Lookup endpoints require service key authentication (`X-Service-Key` header) and are intended for server-to-server use.
</Component>

---

## Deleting Tenants [#deleting-tenants]

Only users with the `tenant#delete_tenant` permission (typically owners) can delete a tenant.

```typescript
await tenantsApi.deleteTenant();
```

### What Happens on Deletion [#what-happens-on-deletion]

<Component>
<Component>
### Permission Check [#permission-check]
Omnibase verifies the user has `tenant#delete_tenant` permission.
</Component>

<Component>
### Stripe Cleanup [#stripe-cleanup]
If a Stripe customer exists, it's archived and subscriptions are cancelled.
</Component>

<Component>
### Database Cascade [#database-cascade]
All related records are deleted:
- `auth.tenants` (primary record)
- `auth.tenant_users` (all memberships)
- `auth.tenant_settings`
- `auth.tenant_invites` (pending invitations)
- All tenant-scoped data (via foreign key cascades)
</Component>

<Component>
### Permission Cleanup [#permission-cleanup]
All permission relationships for this tenant are deleted.
</Component>

<Component>
### User Reassignment [#user-reassignment]
Former members are reassigned to another tenant (if they have one) or their identity metadata is updated.
</Component>
</Component>

<Component type="error">
Tenant deletion is irreversible. All data associated with the tenant will be permanently deleted.
</Component>

---

## Tenant Lifecycle Diagram [#tenant-lifecycle-diagram]

```
┌─────────────────────────────────────────────────────────┐
│                    TENANT CREATION                       │
├─────────────────────────────────────────────────────────┤
│  1. User calls createTenant()                           │
│  2. Omnibase creates tenant record                      │
│  3. Stripe customer created automatically               │
│  4. Creating user assigned as owner                     │
│  5. Permission relationship: user → owner → tenant      │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                    TENANT ACTIVE                         │
├─────────────────────────────────────────────────────────┤
│  • Members can be invited                               │
│  • Data is isolated via RLS                             │
│  • Subscriptions can be added                           │
│  • Billing goes to tenant's Stripe customer             │
│  • Users can switch between tenants                     │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                    TENANT DELETION                       │
├─────────────────────────────────────────────────────────┤
│  1. Owner calls deleteTenant()                          │
│  2. All memberships removed                             │
│  3. Stripe subscriptions cancelled                      │
│  4. Data cascade deleted                                │
│  5. Permission relationships cleaned up                 │
└─────────────────────────────────────────────────────────┘
```

---

## Related Guides [#related-guides]

- [Team Invitations](/guides/multi-tenancy/invitations) — Invite users to your tenant
- [RBAC](/guides/multi-tenancy/rbac) — Configure roles and permissions
- [Data Isolation](/guides/multi-tenancy/isolation) — How RLS protects tenant data

# Row-Level Security (/guides/postgresql/rls)

Row-Level Security (RLS) is a PostgreSQL feature that restricts which rows a query can see or modify. Instead of relying on application code to filter data, the database itself enforces access rules on every query.

Omnibase provides helper functions like `auth.active_tenant_id()` that make it easy to write RLS policies for tenant isolation. You enable RLS and write policies per table.

---

## Auth Helper Functions [#auth-helper-functions]

Omnibase provides helper functions for use in RLS policies:

```sql
auth.active_tenant_id()                    -- current tenant UUID (from JWT)
auth.user_id()                             -- current user UUID (from JWT)
auth.active_user_role()                    -- user's role name (DB lookup from permissions.roles)
auth.has_relation(ns, obj, rel)            -- true if user has this relation (Keto lookup)
auth.has_any_relation(ns, obj, rels[])     -- true if user has ANY of the relations (Keto lookup)
```

`active_tenant_id()` and `user_id()` read from JWT claims. `active_user_role()` queries `permissions.roles` directly and `has_relation()` / `has_any_relation()` query Keto relation tuples, so permission changes take effect immediately without requiring a new JWT.

```sql
-- has_relation: does this user have 'delete_tenant' on this Tenant?
SELECT auth.has_relation('Tenant', 'tenant-uuid', 'delete_tenant');
-- Returns: true (if a matching Keto relation tuple exists)

-- has_any_relation: does this user have 'owner' OR 'can_read' on this StorageObject?
-- More efficient than multiple has_relation() calls (single query)
SELECT auth.has_any_relation('StorageObject', 'object-uuid', ARRAY['owner', 'can_read']);
-- Returns: true (if any matching tuple exists)
```

---

## Database Roles [#database-roles]

PostgREST runs every request as one of two roles:

| Role | Used when | Access |
|------|-----------|--------|
| `anon_user` | No session, app key, or service key | Public/read-only access |
| `authenticated` | Valid session or app key with an active tenant | Member of `anon_user`; user-scoped access |

`authenticated` inherits `anon_user`, so existing `GRANT ... TO anon_user` and `TO anon_user` policies keep applying to logged-in users. Use `TO authenticated` when a policy must only apply to logged-in users, and grant writes to `authenticated`:

```sql
GRANT SELECT, INSERT, UPDATE, DELETE ON projects TO authenticated;
```

---

## Writing Custom RLS Policies [#writing-custom-rls-policies]

### 1. Create Your Table [#1-create-your-table]

Include a `tenant_id` column with a foreign key to `auth.tenants`:

```sql
CREATE TABLE projects (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES auth.tenants(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);
```

### 2. Enable RLS and Grant Access [#2-enable-rls-and-grant-access]

```sql
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
GRANT SELECT, INSERT, UPDATE, DELETE ON projects TO anon_user, authenticated;
```

### 3. Add a Policy [#3-add-a-policy]

```sql
CREATE POLICY tenant_isolation ON projects
  FOR ALL
  TO anon_user, authenticated
  USING (tenant_id = auth.active_tenant_id()::uuid)
  WITH CHECK (tenant_id = auth.active_tenant_id()::uuid);
```

| Clause | Applies to | Purpose |
|--------|-----------|---------|
| `USING` | SELECT, UPDATE, DELETE | Filters which rows are visible |
| `WITH CHECK` | INSERT, UPDATE | Validates new/modified rows |

<Component type="warn">
Always use `ON DELETE CASCADE` on `tenant_id` foreign keys so data is cleaned up when a tenant is deleted.
</Component>

---

## Common Patterns [#common-patterns]

### Tenant Isolation (Default) [#tenant-isolation-default]

Every row belongs to exactly one tenant. This is the most common pattern.

```sql
CREATE POLICY tenant_isolation ON your_table
  FOR ALL
  USING (tenant_id = auth.active_tenant_id()::uuid)
  WITH CHECK (tenant_id = auth.active_tenant_id()::uuid);
```

### User-Owned Rows [#user-owned-rows]

Rows belong to a specific user within a tenant. Other tenant members can see public rows.

```sql
-- Users see their own rows + public rows in their tenant
CREATE POLICY user_owned_select ON documents
  FOR SELECT
  USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND (user_id = auth.user_id()::uuid OR is_public = true)
  );

-- Users can only modify their own rows
CREATE POLICY user_owned_modify ON documents
  FOR UPDATE USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND user_id = auth.user_id()::uuid
  );
```

### Relation-Gated Access (ReBAC) [#relation-gated-access-rebac]

Gate rows on Keto relation tuples using `auth.has_relation()` or `auth.has_any_relation()`. These check the same permission data the API middleware uses:

```sql
-- Only users with 'read' relation on Audit namespace can view logs
CREATE POLICY audit_read ON audit_logs
  FOR SELECT
  USING (
    tenant_id = auth.active_tenant_id()::uuid
    AND auth.has_relation('Audit', tenant_id::text, 'read')
  );
```

Use `has_any_relation()` when checking multiple relations — it runs a single query instead of multiple `has_relation()` calls:

```sql
-- Per-object permissions: owner OR can_read can view storage objects
CREATE POLICY storage_objects_read ON storage.objects
  FOR SELECT TO anon_user
  USING (
    tenant_id::text = auth.active_tenant_id()
    AND auth.has_any_relation('StorageObject', id::text, ARRAY['owner', 'can_read'])
  );

-- Per-object permissions: owner OR can_delete can delete storage objects
CREATE POLICY storage_objects_delete ON storage.objects
  FOR DELETE TO anon_user
  USING (
    tenant_id::text = auth.active_tenant_id()
    AND auth.has_any_relation('StorageObject', id::text, ARRAY['owner', 'can_delete'])
  );
```

The namespace and relation map to how permissions are stored: a role permission `storage#manage_all` creates a Keto tuple with namespace=`Storage`, relation=`manage_all` on the tenant object.

### Shared Reference Data [#shared-reference-data]

Tables without `tenant_id` are accessible to everyone. Don't enable RLS — just restrict writes:

```sql
CREATE TABLE plans (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price INTEGER NOT NULL
);

-- All authenticated users can read, only super_user can write
GRANT SELECT ON plans TO anon_user;
```

---

## Indexing Tips [#indexing-tips]

Always include `tenant_id` as the leading column in indexes. RLS adds a `tenant_id` filter to every query, so this keeps lookups fast:

```sql
-- Composite index with tenant_id first
CREATE INDEX idx_projects_tenant_status ON projects(tenant_id, status);

-- Unique constraints should include tenant_id
CREATE UNIQUE INDEX idx_projects_tenant_name ON projects(tenant_id, name);
```

---

## Related [#related]

- [Data Isolation](/guides/multi-tenancy/isolation) — Full deep-dive into JWT structure, database roles, and testing isolation
- [RBAC](/guides/rbac) — Role-based access control
- [Storage](/guides/storage) — File storage with per-object permissions

# Quickstart (/guides/quickstart)

This guide walks you through setting up Omnibase locally, creating your first user and tenant, and configuring Stripe billing. By the end, you'll have a working backend with authentication, multi-tenancy, and payments.

**Time:** ~15 minutes
**Prerequisites:** Docker, Bun (or Node.js 18+)

---

## 1. Install the CLI [#1-install-the-cli]

```bash
npm i -g @omnibase/cli
```

Verify the installation:

```bash
omnibase --version
```

<Component>
<Component href="/cli" title="CLI Reference">
Every `omnibase` command, option, and environment override
</Component>
</Component>

---

## 2. Initialize Your Project [#2-initialize-your-project]

Create a new directory and initialize Omnibase:

```bash
mkdir my-app && cd my-app
omnibase init
```

This creates an `omnibase/` directory with:

```
my-app/
└── omnibase/
    ├── omnibase.toml        # Project config: deployments, auth, versions
    ├── .env.local           # Local env vars & secrets (gitignored)
    ├── db/                  # Database migrations + RLS policies
    ├── email/               # HTML email templates
    ├── permissions/         # RBAC permission namespaces
    └── stripe/              # Stripe product/price config (*.config.json)
```

<Component type="info">
The scaffolder also drops in a sample `omnibase/workers/` Cloudflare Worker so `omnibase start` has something to run out of the box. For real projects you'll usually delete it and point `[[deployments]]` at your own wrangler apps instead.
</Component>

The heart of your project is `omnibase/omnibase.toml`. It declares which apps to deploy, the auth settings, and which service versions to use:

```toml
project_id = "..." # set when you create a cloud project

[[deployments]]
name = "api"
path = "../apps/api"        # any dir with a wrangler.toml + `bun run dev`
port = 8787                 # optional; defaults to 8787 + deployment index

[auth]
website_url = "http://127.0.0.1:3000"
allowed_return_urls = ["http://127.0.0.1:3000", "http://localhost:3000"]
```

<Component>
<Component href="/guides/configuration" title="Project Configuration">
Every section of `omnibase.toml`: deployments, auth, OIDC, local, and version pinning
</Component>
</Component>

---

## 3. Configure Environment [#3-configure-environment]

Local secrets and environment variables live in `omnibase/.env.local`:

```bash
# Required
OMNIBASE_API_URL=http://localhost:8080
OMNIBASE_SERVICE_KEY=VERY_SECRET_KEY

# Auth Configuration
WEBSITE_URL=http://127.0.0.1:3000
COOKIE_SECRET=change-this-to-a-secure-random-string
CIPHER_SECRET=32-character-secret-for-encryption

# Stripe (get keys from https://dashboard.stripe.com/apikeys)
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
```

<Component type="info">
For other environments (a branch, staging, prod) create a matching file — `omnibase/.env.<environment>` or `omnibase/.env.<branch_name>` — and select it with `omnibase --env <name>`. These files are gitignored. Values resolve in order: `process.env` → `omnibase/.env.<env>`.
</Component>

<Component>
<Component href="/guides/configuration" title="Environment Files">
Where secrets live, per-environment files, and the resolution order
</Component>
</Component>

---

## 4. Start Services [#4-start-services]

Launch everything with a single command:

```bash
omnibase start
```

`omnibase start` runs in the foreground and streams logs; press Ctrl+C to stop everything, or use `omnibase start -d` to run the containers in the background (stop them with `omnibase stop`). It does two things:

1. **Starts the control plane** with Docker Compose — Postgres + PgBouncer, the REST API, Auth (Kratos), Permissions (Keto), PostgREST, Mailpit (email), RustFS (S3-compatible storage), and Adminer, then runs database migrations.
2. **Spawns a dev server** (`bun run dev`) for every deployment in `omnibase.toml`, on ports starting at `8787`.

| Service | URL |
|---------|-----|
| REST API | `http://localhost:8080` |
| Auth (Kratos) | `http://127.0.0.1:4433` |
| PostgREST | `http://localhost:8001` |
| Adminer (DB UI) | `http://localhost:8081` |
| RustFS console (storage) | `http://localhost:9001` |
| Mailpit (email UI) | `http://localhost:8025` |
| Your deployments | `http://localhost:8787`+ |

Wait for the health check to pass:

```bash
curl http://localhost:8080/health/ready
# {"status":"ready","ready":true,"services":{"database":"ok","auth":"ok","permissions":"ok","postgrest":"ok","storage":"ok"}}
```

<Component>
<Component href="/cli/start" title="`omnibase start` Reference">
Options like `--build`, ports, and how deployment env is resolved
</Component>
</Component>

---

## 5. Sync Configuration [#5-sync-configuration]

Push your local configurations to the running services:

```bash
omnibase sync all
```

This syncs:
- **Permissions** — RBAC namespaces to Keto
- **Database** — SQL migration files
- **Email** — HTML email templates
- **Stripe** — product/price configuration

(The `env` service is cloud-only and is skipped locally.)

<Component>
<Component href="/cli/sync" title="`omnibase sync` Reference">
Selecting individual services and syncing to cloud environments
</Component>
</Component>

---

## 6. Create Your First User and Tenant [#6-create-your-first-user-and-tenant]

Omnibase ships **typed SDKs generated from the OpenAPI spec** in several languages, so you can use whichever fits your stack:

- **JavaScript / TypeScript** — `@omnibase/core-js`
- **Go** — `github.com/phoenixsolutionsgroup/omnibase/sdk/core/go`
- **Framework SDKs** — `@omnibase/nextjs`, `@omnibase/react`, and shadcn/ui components

Every SDK exposes the same API surface. For this demo we'll use the JavaScript SDK:

```bash
npm install @omnibase/core-js
# or
bun add @omnibase/core-js
```

Create a user and tenant programmatically:

```typescript
import { Configuration, V1AuthApi, V1TenantsLifecycleApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: 'http://localhost:8080',
  apiKey: (name) => (name === 'X-Service-Key' ? 'VERY_SECRET_KEY' : ''), // Server-side operations
});

// Create a user
const authApi = new V1AuthApi(config);
const user = await authApi.createUser({
  createUserRequest: {
    email: 'admin@example.com',
    password: 'secure-password-123',
    name: { first: 'Admin', last: 'User' },
  },
});

console.log('User created:', user.id);

// Create a tenant (organization). The creator becomes the tenant owner.
const tenantsApi = new V1TenantsLifecycleApi(config);
const { tenant, token } = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'Acme Corporation',
    billingEmail: 'billing@acme.com',
  },
});

console.log('Tenant created:', tenant.id);
console.log('Stripe Customer:', tenant.stripeCustomerId);
console.log('Tenant JWT:', token);
```

<Component type="info">
When a tenant is created, Omnibase automatically creates a Stripe customer and returns a tenant-scoped JWT (`token`) you can use for subsequent requests.
</Component>

<Component>
<Component href="/api" title="API & SDK Reference">
REST endpoints and generated JS and Go SDKs
</Component>
</Component>

---

## 7. Configure Stripe Products [#7-configure-stripe-products]

Create a billing configuration as a `*.config.json` file in `omnibase/stripe/` (any name works, e.g. `products.config.json`). The `$schema` points at the running API so your editor gives you typed validation and autocomplete:

```json
{
  "$schema": "http://localhost:8080/api/v1/stripe/schema",
  "version": "1.0.0",
  "products": [
    {
      "id": "free_plan",
      "name": "Free",
      "description": "Get started for free",
      "type": "service",
      "prices": [
        {
          "id": "free_monthly",
          "amount": 0,
          "currency": "usd",
          "interval": "month"
        }
      ]
    },
    {
      "id": "pro_plan",
      "name": "Professional",
      "description": "For growing teams",
      "type": "service",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 2900,
          "currency": "usd",
          "interval": "month"
        },
        {
          "id": "pro_yearly",
          "amount": 29000,
          "currency": "usd",
          "interval": "year"
        }
      ]
    }
  ]
}
```

<Component type="info">
The schema is served by the API at `/api/v1/stripe/schema`, so start services (`omnibase start`) before your editor tries to fetch it. If you don't want editor validation, drop the `$schema` line.
</Component>

Push to Stripe:

```bash
omnibase stripe push
```

You'll see output like:

```
✔ Successfully loaded config
✔ Configuration uploaded successfully!

Products created: 2
   - Free (free_plan)
   - Professional (pro_plan)
Prices created: 3
   - free_monthly (product: free_plan)
   - pro_monthly (product: pro_plan)
   - pro_yearly (product: pro_plan)
```

<Component>
<Component href="/guides/stripe/configuration" title="Stripe Configuration">
Version control, metered billing, webhooks, and the config schema
</Component>
</Component>

---

## 8. Create a Checkout Session [#8-create-a-checkout-session]

Now create a checkout session for your tenant:

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

const { url } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'http://localhost:3000/success',
    cancelUrl: 'http://localhost:3000/pricing',
  },
});

console.log('Checkout URL:', url);
// Redirect user to url
```

---

## Next Steps [#next-steps]

You now have a working Omnibase setup with:
- User authentication via Ory Kratos
- Multi-tenant organization support
- Stripe billing integration

**Continue learning:**

- [Project Configuration](/guides/configuration) — `omnibase.toml` and environment files
- [Multi-Tenancy Guide](/guides/multi-tenancy) — Deep dive into tenant isolation, invitations, and RBAC
- [Stripe Guide](/guides/stripe) — Subscriptions, invoices, metering, and webhooks
- [Self-Hosting Guide](/self-hosting) — Production deployment options
- [API Reference](/api) — Complete API documentation

---

## Stopping Services [#stopping-services]

When you're done developing:

```bash
omnibase stop
```

This gracefully shuts down the control plane containers and terminates any spawned deployment dev servers, while preserving your data.

---

## Troubleshooting [#troubleshooting]

### Services won't start [#services-wont-start]

Check Docker is running:
```bash
docker info
```

### Health check fails [#health-check-fails]

List running containers and inspect the API logs (containers are prefixed with `omnibase-<your-project-dir>`):

```bash
docker ps
docker logs omnibase-my-app-rest-api-1
```

Or restart a single service with the CLI:

```bash
omnibase restart api
```

### Stripe push fails [#stripe-push-fails]

Verify your Stripe keys in `omnibase/.env.local` and ensure you're using test mode keys (`sk_test_...`).

# RBAC Overview (/guides/rbac)

Omnibase uses a fine-grained, relationship-based access control (ReBAC) system powered by Ory Keto. Each tenant manages their own roles with configurable permissions.

## UI Components [#ui-components]

Omnibase provides pre-built shadcn components in `@omnibase/shadcn`:

| Component | Description |
|-----------|-------------|
| `RoleCreator` | Create and edit roles with permission selector |
| `PermissionsSelector` | Row-based permission picker for namespaces and relations |
| `PermissionsSelectorTree` | Tree-based permission picker grouped by JSDoc annotations |
| `UserViewer` | View team members and manage role assignments |

See [Managing Roles](/guides/rbac/roles#ui-components) for usage examples.

## How It Works [#how-it-works]

Permissions are stored as relationship tuples:

```
(Namespace, Object, Relation, Subject)
```

Examples:
```
(Tenant, acme-corp-uuid, can_delete_tenant, User:alice)
(Tenant, acme-corp-uuid, can_invite_user, User:bob)
(Project, proj-123-uuid, can_write, User:carol)
```

When checking permissions, Omnibase verifies the relationship exists between the subject and object.

## Defining Permissions with JSDoc [#defining-permissions-with-jsdoc]

Permissions are defined in TypeScript namespace files with JSDoc annotations that provide metadata for UI rendering:

```typescript title="omnibase/permissions/tenants.ts"
/**
 * @group User Management
 * @displayName Invite Users
 * @role owner
 * @role admin
 */
can_invite_user: User[];
```

| Annotation | Purpose |
|------------|---------|
| `@group` | Primary UI grouping |
| `@subGroup` | Secondary grouping within a group |
| `@displayName` | Human-readable label |
| `@role` | Suggested default role(s) |
| `@hidden` | Hide internal relations from UI |

## Key Concepts [#key-concepts]

### Tenant Permissions vs Resource Permissions [#tenant-permissions-vs-resource-permissions]

<Component type="info">
Only `Tenant` permissions support auto-scoping. The active tenant ID is automatically injected when checking these permissions.
</Component>

| Type | Format | Auto-Scoped |
|------|--------|-------------|
| Tenant permissions | `Tenant#relation` | Yes - uses active tenant |
| Resource permissions | `(Namespace, uuid, relation, subject)` | No - requires explicit UUID |

### No Resource-Wide Wildcards [#no-resource-wide-wildcards]

<Component type="warn">
There is **no** `project#can_read` permission that grants access to all projects. Resource permissions always require a specific UUID.
</Component>

To grant access to resources like projects or documents, create relationships for each resource:

```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Project',
    object: projectId,        // Specific project UUID
    relation: 'can_write',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});
```

## RBAC Guides [#rbac-guides]

<Component>
<Component title="Defining Permissions" href="/docs/guides/rbac/permissions">
Create permission namespaces with JSDoc metadata for UI grouping
</Component>

<Component title="Managing Roles" href="/docs/guides/rbac/roles">
Create roles and assign users within your tenants
</Component>
</Component>

## Quick Example [#quick-example]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
import { V1PermissionsApi } from '@omnibase/core-js';

const permissionsApi = new V1PermissionsApi(config);

// Check if user can delete tenant
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Tenant',
    object: tenantId,
    relation: 'can_delete_tenant',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});

if (data.data.allowed) {
  // User has permission
}
```
</Tab>

<Tab value="Go">
```go
import omnibase "github.com/phoenixsolutionsgroup/omnibase/sdk/core/go"

client := omnibase.NewAPIClient(&omnibase.Configuration{
    Servers: omnibase.ServerConfigurations{
        {URL: apiURL},
    },
}).V1PermissionsAPI

// Check if user can delete tenant
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Tenant",
    Object:    tenantId,
    Relation:  "can_delete_tenant",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    userId,
    },
}).Execute()

if result.Data.Allowed {
    // User has permission
}
```
</Tab>
</Tabs>

## Related [#related]

- [Tenant Management](/guides/multi-tenancy/tenants) — Create and manage tenants
- [Team Invitations](/guides/multi-tenancy/invitations) — Invite users with roles
- [Data Isolation](/guides/multi-tenancy/isolation) — How permissions affect data access
- [Permissions Concept](/concepts/permissions) — Deep dive into ReBAC internals

# Defining Permissions (/guides/rbac/permissions)

Omnibase allows you to define custom permission namespaces using TypeScript with JSDoc annotations. These annotations provide metadata for UI rendering and role suggestions.

## Project Structure [#project-structure]

Permissions are defined in your project's `omnibase/permissions/` directory:

```
omnibase/
└── permissions/
    ├── types.ts             # Type definitions
    ├── tenants.ts           # Tenant namespace (required)
    ├── storage.ts           # Storage namespace (required)
    ├── projects.ts          # Project namespace (example)
    └── ...                  # Your custom namespaces
```

## Required Namespaces [#required-namespaces]

The API owns the canonical namespace files in `apps/api/permissions/`. Every project's namespace class must contain **at least** every relation and permit the API checks or writes — extra relations, permits, and custom classes are fine. Missing entries make API requests fail permission checks with no obvious cause.

Each API release carries the namespaces it needs, and the CLI keeps projects in sync:

- **`omnibase init`** fetches the namespace files for the pinned `api` version from GitHub and writes them to `omnibase/permissions/`.
- **`omnibase start`** calls the running API's `GET /api/v1/permissions/requirements` endpoint, writes any missing namespace files, and warns about missing relations or permits.
- **`omnibase permissions fix`** adds missing relations and permits using the API's own definitions. It only inserts members; existing members are never removed or rewritten.
- **`omnibase permissions push`** and cloud deploys reject namespace uploads that are missing required entries and name exactly what is missing.

<Component type="warn">
If the API does not expose `/api/v1/permissions/requirements`, the image is too old. Set the `api` version under `[versions]` in `omnibase.toml` to a release that includes it, then run `omnibase start` again.
</Component>

---

## JSDoc Annotations [#jsdoc-annotations]

Each permission relation can have JSDoc annotations that provide metadata:

| Annotation | Description | Example |
|------------|-------------|---------|
| `@group` | Primary grouping for UI | `@group User Management` |
| `@subGroup` | Secondary grouping within a group | `@subGroup Role Assignment` |
| `@displayName` | Human-readable name | `@displayName Invite Users` |
| `@role` | Suggested default role (can have multiple) | `@role owner` |
| `@hidden` | Hide from UI (internal relations) | `@hidden` |

### Example with Annotations [#example-with-annotations]

```typescript title="omnibase/permissions/tenants.ts"
import { Context, Namespace } from "./types";

export class User implements Namespace {}
export class ApiKey implements Namespace {}

export class Tenant implements Namespace {
  related: {
    /**
     * @group User Management
     * @displayName Invite Users
     * @role owner
     * @role admin
     */
    can_invite_user: User[];

    /**
     * @group User Management
     * @subGroup Role Assignment
     * @displayName Update User Roles
     * @role owner
     * @role admin
     */
    can_update_user_role: User[];

    /**
     * @group User Management
     * @subGroup Role Assignment
     * @displayName Promote to Owner
     * @role owner
     */
    can_update_user_role_to_owner: User[];

    /**
     * @group Database
     * @subGroup Secrets
     * @displayName View Database Password
     * @role owner
     * @role admin
     */
    can_view_database_password: (User | ApiKey)[];
  };

  permits = {
    invite_user: (ctx: Context): boolean =>
      this.related.can_invite_user.includes(ctx.subject),
    // ... other permits
  };
}
```

---

## Hiding Internal Relations [#hiding-internal-relations]

Use the `@hidden` annotation for relations that are used internally for permission traversal but shouldn't appear in the UI:

```typescript title="omnibase/permissions/projects.ts"
export class Project implements Namespace {
  related: {
    /** @hidden */
    parent_project: Project[];

    /** @hidden */
    tenant: Tenant[];

    /**
     * @group Configuration
     * @displayName View Environment
     * @role owner
     * @role admin
     */
    can_view_project_env: (User | ApiKey)[];
  };
}
```

---

## Permission Types [#permission-types]

### Tenant Permissions (Auto-Scoped) [#tenant-permissions-auto-scoped]

<Component type="info">
Tenant permissions are the **only** permissions that support auto-scoping. The active tenant ID is automatically injected when checking these permissions.
</Component>

When you check a `Tenant` permission, Omnibase automatically uses the user's active tenant:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Check if user can invite others to the current tenant
const result = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Tenant',
    object: tenantId,  // From session context
    relation: 'can_invite_user',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Tenant",
    Object:    tenantId,
    Relation:  "can_invite_user",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    userId,
    },
}).Execute()
```
</Tab>
</Tabs>

### Resource Permissions (UUID Required) [#resource-permissions-uuid-required]

<Component type="warn">
Resource permissions do **not** support wildcards. You must always specify the resource UUID when creating or checking permissions.
</Component>

For resources like projects, documents, or custom entities:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Grant access to a specific project
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Project',
    object: 'proj-123-uuid',  // Specific UUID required
    relation: 'can_write',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Project",
    Object:    "proj-123-uuid",
    Relation:  "can_write",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    userId,
    },
}).Execute()
```
</Tab>
</Tabs>

---

## Hierarchical Permissions [#hierarchical-permissions]

Permissions can inherit from parent resources using the `traverse()` method:

```typescript title="omnibase/permissions/projects.ts"
export class Project implements Namespace {
  related: {
    /** @hidden */
    parent_project: Project[];

    /** @hidden */
    tenant: Tenant[];

    /**
     * @group Database
     * @subGroup Secrets
     * @displayName View Database Password
     * @role owner
     * @role admin
     */
    can_view_database_password: (User | ApiKey)[];
  };

  permits = {
    view_database_password: (ctx: Context): boolean =>
      // Check project-level permission
      this.related.can_view_database_password.includes(ctx.subject) ||
      // Check parent project (for nested projects)
      this.related.parent_project.traverse((p) =>
        p.permits.view_database_password(ctx)
      ) ||
      // Fall back to tenant-level permission
      this.related.tenant.traverse((t) =>
        t.related.can_view_database_password.includes(ctx.subject)
      ),
  };
}
```

This allows granting permissions at the tenant level (applies to all projects) or project level (applies to specific projects).

---

## Subject Types [#subject-types]

Permissions can be granted to different subject types:

| Subject | Description | Usage |
|---------|-------------|-------|
| `User` | Users with sessions | Standard user permissions |
| `ApiKey` | Programmatic API keys | Service-to-service access |

Define which subjects can have a permission using TypeScript union types:

```typescript
related: {
  // User-only permissions
  can_invite_user: User[];
  can_delete_tenant: User[];

  // Permissions for both Users and API keys
  can_view_database_password: (User | ApiKey)[];
  can_rotate_keys: (User | ApiKey)[];
}
```

---

## Syncing Permissions [#syncing-permissions]

After creating or updating permission files, sync them to Omnibase:

<Component>
<Component>
### Validate Configuration [#validate-configuration]

```bash
omnibase validate permissions
```

This checks for syntax errors and invalid references.
</Component>

<Component>
### Sync to Omnibase [#sync-to-omnibase]

```bash
omnibase sync permissions
```

This uploads your permission namespaces with all JSDoc metadata.
</Component>

<Component>
### Verify [#verify]

```bash
omnibase permissions list
```

Lists all registered namespaces with their relations and metadata.
</Component>
</Component>

---

## Fetching Permission Definitions [#fetching-permission-definitions]

The API returns all permission metadata including JSDoc annotations:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
import { V1TenantsApi } from '@omnibase/core-js';

const tenantsApi = new V1TenantsApi(config);
const { data } = await tenantsApi.getRoleDefinitions({
  subject: 'User',  // or 'ApiKey'
});

for (const namespace of data.data.namespaces) {
  console.log(`Namespace: ${namespace.name}`);
  for (const relation of namespace.relations) {
    console.log(`  ${relation.name}`);
    console.log(`    Display: ${relation.displayName}`);
    console.log(`    Group: ${relation.group}`);
    console.log(`    SubGroup: ${relation.subGroup}`);
    console.log(`    Roles: ${relation.roles?.join(', ')}`);
  }
}
```
</Tab>

<Tab value="Go">
```go
import omnibase "github.com/phoenixsolutionsgroup/omnibase/sdk/core/go"

tenantsClient := omnibase.NewAPIClient(&omnibase.Configuration{
    Servers: omnibase.ServerConfigurations{
        {URL: apiURL},
    },
}).V1TenantsAPI

result, _, err := tenantsClient.GetRoleDefinitions(ctx).
    Subject("User").
    Execute()

for _, ns := range result.Data.Namespaces {
    fmt.Printf("Namespace: %s\n", ns.Name)
    for _, rel := range ns.Relations {
        fmt.Printf("  %s\n", rel.Name)
        fmt.Printf("    Display: %s\n", rel.DisplayName)
        fmt.Printf("    Group: %s\n", rel.Group)
        fmt.Printf("    SubGroup: %s\n", rel.SubGroup)
        fmt.Printf("    Roles: %s\n", strings.Join(rel.Roles, ", "))
    }
}
```
</Tab>
</Tabs>

### Response Structure [#response-structure]

```typescript
interface RelationMetadata {
  name: string;           // e.g., "can_invite_user"
  displayName?: string;   // e.g., "Invite Users"
  group?: string;         // e.g., "User Management"
  subGroup?: string;      // e.g., "Role Assignment"
  roles?: string[];       // e.g., ["owner", "admin"]
  subjectTypes: string[]; // e.g., ["User"] or ["User", "ApiKey"]
}
```

---

## UI Components [#ui-components]

Omnibase provides pre-built shadcn components that use the permission metadata:

<Accordions>
<Accordion title="PermissionsSelectorTree Component">
Hierarchical tree view with checkboxes, grouped by `@group` and `@subGroup` annotations.

```tsx
import { PermissionsSelectorTree } from '@omnibase/shadcn';

<PermissionsSelectorTree
  definitions={namespaceDefinitions}
  selectedPermissions={['tenant#can_invite_user', 'tenant#can_view_users']}
  onSelectionChange={(permissions) => {
    console.log('Selected:', permissions);
  }}
  disabled={false}
/>
```

The tree automatically organizes permissions by their JSDoc groups.
</Accordion>

<Accordion title="PermissionsSelector Component">
Row-based permission picker for building permission strings with namespace and object selection.

```tsx
import { PermissionsSelector } from '@omnibase/shadcn';

<PermissionsSelector
  definitions={namespaceDefinitions}
  namespaceMap={{
    project: projects.map(p => ({ id: p.id, label: p.name })),
  }}
  onPermissionsChange={(rows) => {
    console.log('Permission rows:', rows);
  }}
  showPreview={true}
/>
```
</Accordion>

<Accordion title="RoleCreator Component">
Higher-level component combining role name input with permission selection.

```tsx
import { RoleCreator } from '@omnibase/shadcn';

<RoleCreator
  definitions={namespaceDefinitions}
  roles={existingRoles}
  namespaceMap={{ project: projects }}
  onRoleCreate={async ({ role_name, permissions }) => {
    await tenantsApi.createRole({
      createRoleRequest: { roleName: role_name, permissions },
    });
  }}
/>
```
</Accordion>
</Accordions>

---

## Complete Example [#complete-example]

<Tabs items={["Tenant","Project"]}>
<Tab value="Tenant">
```typescript title="omnibase/permissions/tenants.ts"
import { Context, Namespace } from "./types";

export class User implements Namespace {}
export class ApiKey implements Namespace {}

export class Tenant implements Namespace {
  related: {
    /**
     * @group Tenant Administration
     * @displayName Delete Tenant
     * @role owner
     */
    can_delete_tenant: User[];

    /**
     * @group User Management
     * @displayName Invite Users
     * @role owner
     * @role admin
     */
    can_invite_user: User[];

    /**
     * @group User Management
     * @displayName View Users
     * @role owner
     * @role admin
     * @role dev
     * @role member
     */
    can_view_users: User[];

    /**
     * @group API Keys
     * @displayName Create API Keys
     * @role owner
     * @role admin
     * @role dev
     */
    can_create_api_keys: User[];

    /**
     * @group Database
     * @subGroup Secrets
     * @displayName View Database Password
     * @role owner
     * @role admin
     */
    can_view_database_password: (User | ApiKey)[];
  };

  permits = {
    delete_tenant: (ctx: Context): boolean =>
      this.related.can_delete_tenant.includes(ctx.subject),

    invite_user: (ctx: Context): boolean =>
      this.related.can_invite_user.includes(ctx.subject),

    view_users: (ctx: Context): boolean =>
      this.related.can_view_users.includes(ctx.subject),

    create_api_keys: (ctx: Context): boolean =>
      this.related.can_create_api_keys.includes(ctx.subject),

    view_database_password: (ctx: Context): boolean =>
      this.related.can_view_database_password.includes(ctx.subject),
  };
}
```
</Tab>

<Tab value="Project">
```typescript title="omnibase/permissions/projects.ts"
import { ApiKey, Tenant, User } from "./tenants";
import { Context, Namespace } from "./types";

export class Project implements Namespace {
  related: {
    /** @hidden */
    parent_project: Project[];

    /** @hidden */
    tenant: Tenant[];

    /**
     * @group Database
     * @subGroup Secrets
     * @displayName View Database Password
     * @role owner
     * @role admin
     */
    can_view_database_password: (User | ApiKey)[];

    /**
     * @group Configuration
     * @displayName Update Environment
     * @role owner
     * @role admin
     * @role dev
     */
    can_update_project_env: (User | ApiKey)[];
  };

  permits = {
    view_database_password: (ctx: Context): boolean =>
      this.related.can_view_database_password.includes(ctx.subject) ||
      this.related.parent_project.traverse((p) =>
        p.permits.view_database_password(ctx)
      ) ||
      this.related.tenant.traverse((t) =>
        t.related.can_view_database_password.includes(ctx.subject)
      ),

    update_project_env: (ctx: Context): boolean =>
      this.related.can_update_project_env.includes(ctx.subject) ||
      this.related.parent_project.traverse((p) =>
        p.permits.update_project_env(ctx)
      ) ||
      this.related.tenant.traverse((t) =>
        t.related.can_update_project_env.includes(ctx.subject)
      ),
  };
}
```
</Tab>
</Tabs>

---

## Example: Agent + Codebase [#example-agent--codebase]

This example shows how to define custom objects and wire up permission traversal between them. You're building a platform where both users and LLM agents interact with codebases.

### Scenario [#scenario]

- **`User`** — built-in subject type for users
- **`Agent`** — custom subject type for LLM agents (like `User`)
- **`Tenant`** — built-in organizational container
- **`Codebase`** — custom resource object (git repository)

Both `User` and `Agent` can have permissions on a `Codebase`. Permissions can be granted directly on the codebase or at the tenant level (with traversal cascading down).

### Define the Agent Namespace [#define-the-agent-namespace]

```typescript title="omnibase/permissions/agents.ts"
import { Context, Namespace } from "./types";

export class Agent implements Namespace {}
```

### Define the Codebase Namespace [#define-the-codebase-namespace]

```typescript title="omnibase/permissions/codebases.ts"
import { Agent, Context, Namespace, Tenant, User } from "./types";

export class Codebase implements Namespace {
  related: {
    /** @hidden */
    tenant: Tenant[];

    /** @hidden */
    owner: User[];

    /**
     * @group Codebase Access
     * @displayName Edit Code
     * @role owner
     * @role developer
     */
    can_edit: (User | Agent)[];

    /**
     * @group Codebase Access
     * @displayName Push Changes
     * @role owner
     * @role developer
     */
    can_push: (User | Agent)[];

    /**
     * @group Codebase Access
     * @displayName View Code
     * @role owner
     * @role developer
     * @role viewer
     */
    can_view: (User | Agent)[];
  };

  permits = {
    edit: (ctx: Context): boolean =>
      this.related.can_edit.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_edit.includes(ctx.subject)
      ),

    push: (ctx: Context): boolean =>
      this.related.can_push.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_push.includes(ctx.subject)
      ),

    view: (ctx: Context): boolean =>
      this.related.can_view.includes(ctx.subject) ||
      this.related.owner.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.related.can_view.includes(ctx.subject)
      ),
  };
}
```

### Relations Graph [#relations-graph]

```
        ┌──────────┐
        │  User    │
        └────┬─────┘
             │ can_edit
             ▼
       ┌──────────┐      tenant       ┌──────────┐
       │ Codebase │──────────────────▶│  Tenant  │
       └──────────┘                   └──────────┘
             ▲                             ▲
             │ can_push                    │ can_edit
        ┌────┴─────┐              ┌───────┴──────┐
        │  Agent   │              │    User      │
        └──────────┘              └──────────────┘
```

### Granting Permissions [#granting-permissions]

<Tabs items={["Direct Grant","Tenant-Level Grant","Owner Grant"]}>
<Tab value="Direct Grant">
Give an agent push access to a specific codebase:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'can_push',
    subjectId: 'agent-456',
    subjectNamespace: 'Agent',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "can_push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-456",
    },
}).Execute()
```
</Tab>
</Tabs>

Now `agent-456` can push to `Codebase#cb-123`.
</Tab>

<Tab value="Tenant-Level Grant">
Give a user push access to all codebases in a tenant. The `traverse()` call cascades this down:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Tenant',
    object: 'tenant-789',
    relation: 'can_push',
    subjectId: 'user-abc',
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Tenant",
    Object:    "tenant-789",
    Relation:  "can_push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    "user-abc",
    },
}).Execute()
```
</Tab>
</Tabs>

Now `user-abc` can push to every codebase under `Tenant#tenant-789`, because `permits.push` traverses `this.related.tenant` as a fallback.
</Tab>

<Tab value="Owner Grant">
Set a user as the owner of a codebase. The traversal to `owner` handles the rest:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'owner',
    subjectId: 'user-abc',
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "owner",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    "user-abc",
    },
}).Execute()
```
</Tab>
</Tabs>

This creates the relation that `owner.includes()` uses in the `permits` block. Owners inherit edit, push, and view access without those needing to be granted separately.
</Tab>
</Tabs>

### Checking Permissions [#checking-permissions]

<Tabs items={["Agent Check","User via Tenant"]}>
<Tab value="Agent Check">
Check if an agent can push to a codebase:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'push',
    subjectId: 'agent-456',
    subjectNamespace: 'Agent',
  },
});
// data.allowed → true (from the direct grant above)
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "push",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "Agent",
        Object:    "agent-456",
    },
}).Execute()
// result.Data.Allowed → true
```
</Tab>
</Tabs>

**Evaluation path:**
1. Is `agent-456` in `can_push` of `Codebase#cb-123`? → **Yes** → ALLOWED
</Tab>

<Tab value="User via Tenant">
Check if a user can edit a codebase (granted at tenant level):

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
const { data } = await permissionsApi.checkPermission({
  checkPermissionRequest: {
    namespace: 'Codebase',
    object: 'cb-123',
    relation: 'edit',
    subjectId: 'user-abc',
    subjectNamespace: 'User',
  },
});
// data.allowed → true (from the tenant-level grant above)
```
</Tab>

<Tab value="Go">
```go
result, _, err := client.CheckPermission(ctx).CheckPermissionRequest(omnibase.CheckPermissionRequest{
    Namespace: "Codebase",
    Object:    "cb-123",
    Relation:  "edit",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    "user-abc",
    },
}).Execute()
// result.Data.Allowed → true
```
</Tab>
</Tabs>

**Evaluation path:**
1. Is `user-abc` in `can_edit` of `Codebase#cb-123`? → No
2. Follow `owner` relation → no owner set for this codebase
3. Follow `tenant` relation → is `user-abc` in `can_edit` of `Tenant#tenant-789`? → **Yes** → ALLOWED
</Tab>
</Tabs>

### Creating Roles for Agent Permissions [#creating-roles-for-agent-permissions]

Roles can include both User and Agent permissions. Create a "bot-admin" role that grants codebase permissions:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await tenantsApi.createRole({
  createRoleRequest: {
    roleName: 'bot-admin',
    permissions: [
      'codebase#can_push',
      'codebase#can_edit',
      'codebase#can_view',
    ],
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := tenantsClient.CreateRole(ctx).CreateRoleRequest(omnibase.CreateRoleRequest{
    RoleName: "bot-admin",
    Permissions: []string{
        "codebase#can_push",
        "codebase#can_edit",
        "codebase#can_view",
    },
}).Execute()
```
</Tab>
</Tabs>

When you assign this role to a user, they can push/edit/view all codebases in the tenant (assuming the defines use `traverse()` to cascade from `Tenant` → `Codebase`).

---

## Next Steps [#next-steps]

- [Role Configuration](/guides/rbac/roles) — Create roles from permission templates
- [Permissions Concept](/concepts/permissions) — Deep dive into how permissions work
- [Data Isolation](/guides/multi-tenancy/isolation) — How permissions work with RLS

# Managing Roles (/guides/rbac/roles)

Roles are collections of permissions that can be assigned to users. Each tenant manages their own roles independently, giving tenant admins full control over access levels within their organization.

## How Roles Work [#how-roles-work]

Each tenant has its own isolated set of roles:

```
┌───────────────────────────────────────┐
│  Tenant: Acme Corp                    │
│  ├── owner (required)                 │
│  ├── admin (custom)                   │
│  └── developer (custom)               │
└───────────────────────────────────────┘
┌───────────────────────────────────────┐
│  Tenant: Beta Inc                     │
│  ├── owner (required)                 │
│  ├── manager (custom)                 │
│  └── viewer (custom)                  │
└───────────────────────────────────────┘
```

<Component type="info">
Role changes in one tenant do **not** affect other tenants. Each organization has complete control over their role structure.
</Component>

---

## The Owner Role (Required) [#the-owner-role-required]

<Component type="warn">
The `owner` role is created automatically when a tenant is created. The user who creates the tenant is automatically assigned this role. Every tenant must have at least one owner.
</Component>

### Owner Role Behavior [#owner-role-behavior]

- **Auto-assigned**: The tenant creator automatically receives the `owner` role
- **Required**: Cannot be deleted; every tenant must have at least one owner
- **Full control**: Owners typically have all tenant management permissions

---

## Role Suggestions from Permissions [#role-suggestions-from-permissions]

When defining permissions with JSDoc annotations, you can specify which roles should typically have each permission using the `@role` tag:

```typescript title="omnibase/permissions/tenants.ts"
/**
 * @group User Management
 * @displayName Invite Users
 * @role owner
 * @role admin
 */
can_invite_user: User[];
```

These `@role` annotations serve as **suggestions** when creating new roles in the UI. The permission metadata is returned by the API:

```typescript
const { data } = await tenantsApi.getRoleDefinitions({ subject: 'User' });

// Each relation includes suggested roles
for (const namespace of data.data.namespaces) {
  for (const relation of namespace.relations) {
    console.log(`${relation.name}: suggested for ${relation.roles?.join(', ')}`);
  }
}
```

---

## UI Components [#ui-components]

Omnibase provides pre-built shadcn components for role management:

<Accordions>
<Accordion title="RoleCreator Component">
Create and edit roles with autocomplete and permission selection.

```tsx
import { RoleCreator } from '@omnibase/shadcn';

<RoleCreator
  definitions={namespaceDefinitions}
  roles={existingRoles}
  namespaceMap={{
    project: projects.map(p => ({ id: p.id, label: p.name })),
  }}
  onRoleCreate={async (data) => {
    await tenantsApi.createRole({
      createRoleRequest: {
        roleName: data.role_name,
        permissions: data.permissions,
      },
    });
  }}
  onRoleUpdate={async (data) => {
    await tenantsApi.updateRole({
      roleId: data.role_id,
      updateRoleRequest: { permissions: data.permissions },
    });
  }}
/>
```

**Props:**
- `definitions` — Namespace definitions from `getRoleDefinitions()`
- `roles` — Existing roles for autocomplete suggestions
- `namespaceMap` — Optional mapping of namespace to selectable resources
- `onRoleCreate` — Callback when creating a new role
- `onRoleUpdate` — Callback when editing an existing role
</Accordion>

<Accordion title="UserViewer Component">
Display and manage team members with role updates and removal.

```tsx
import { UserViewer } from '@omnibase/shadcn';

<UserViewer
  users={tenantUsers}
  availableRoles={['owner', 'admin', 'member']}
  canEditUsers={hasPermission('tenant#update_user_role')}
  onRoleUpdate={async (userId, newRole) => {
    await tenantsApi.updateTenantUserRole({
      updateTenantUserRoleRequest: { userId, role: newRole },
    });
  }}
  onRemoveUser={async (userId) => {
    await tenantsApi.removeTenantUser({
      removeTenantUserRequest: { userId },
    });
  }}
/>
```

**Props:**
- `users` — Array of `TenantUserResponse` from `listTenantUsers()`
- `availableRoles` — Role names for the dropdown
- `canEditUsers` — Whether to show edit controls
- `onRoleUpdate` — Callback for role changes
- `onRemoveUser` — Callback for user removal
</Accordion>

<Accordion title="PermissionsSelectorTree Component">
Tree-based permission selector grouped by JSDoc annotations.

```tsx
import { PermissionsSelectorTree } from '@omnibase/shadcn';

<PermissionsSelectorTree
  definitions={namespaceDefinitions}
  selectedPermissions={role.permissions}
  onSelectionChange={(permissions) => {
    setSelectedPermissions(permissions);
  }}
/>
```

The tree groups permissions by their `@group` and `@subGroup` annotations.
</Accordion>
</Accordions>

---

## Managing Roles via API [#managing-roles-via-api]

### Creating Roles [#creating-roles]

Create a new role for the current tenant:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
import { V1TenantsApi } from '@omnibase/core-js';

const tenantsApi = new V1TenantsApi(config);

const { data } = await tenantsApi.createRole({
  createRoleRequest: {
    roleName: 'developer',
    permissions: [
      'tenant#can_view_users',
      'tenant#can_create_api_keys',
      'tenant#can_view_api_keys',
    ],
  },
});

console.log('Created role:', data.data.role.id);
```
</Tab>

<Tab value="Go">
```go
import omnibase "github.com/phoenixsolutionsgroup/omnibase/sdk/core/go"

tenantsClient := omnibase.NewAPIClient(&omnibase.Configuration{
    Servers: omnibase.ServerConfigurations{
        {URL: apiURL},
    },
}).V1TenantsAPI

result, _, err := tenantsClient.CreateRole(ctx).CreateRoleRequest(omnibase.CreateRoleRequest{
    RoleName: "developer",
    Permissions: []string{
        "tenant#can_view_users",
        "tenant#can_create_api_keys",
        "tenant#can_view_api_keys",
    },
}).Execute()
fmt.Printf("Created role: %s\n", result.Data.Role.Id)
```
</Tab>
</Tabs>

### Listing Roles [#listing-roles]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
const { data } = await tenantsApi.listRoles();

for (const role of data.data.roles) {
  console.log(`${role.role_name} (${role.id})`);
  console.log(`  Permissions: ${role.permissions.join(', ')}`);
  console.log(`  Users: ${role.user_ids.length}`);
}
```
</Tab>

<Tab value="Go">
```go
result, _, err := tenantsClient.ListRoles(ctx).Execute()
for _, role := range result.Data.Roles {
    fmt.Printf("%s (%s)\n", role.RoleName, role.Id)
    fmt.Printf("  Permissions: %s\n", strings.Join(role.Permissions, ", "))
    fmt.Printf("  Users: %d\n", len(role.UserIds))
}
```
</Tab>
</Tabs>

### Updating Role Permissions [#updating-role-permissions]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await tenantsApi.updateRole({
  roleId: roleId,
  updateRoleRequest: {
    permissions: [
      'tenant#can_view_users',
      'tenant#can_invite_user',  // Added permission
    ],
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := tenantsClient.UpdateRole(ctx, roleId).UpdateRoleRequest(omnibase.UpdateRoleRequest{
    Permissions: []string{
        "tenant#can_view_users",
        "tenant#can_invite_user",
    },
}).Execute()
```
</Tab>
</Tabs>

Permission changes propagate immediately. All users with this role will have updated permissions on their next request.

### Deleting Roles [#deleting-roles]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await tenantsApi.deleteRole({
  roleId: roleId,
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := tenantsClient.DeleteRole(ctx, roleId).Execute()
```
</Tab>
</Tabs>

<Component type="warn">
Before deleting a role, all users must be reassigned to a different role. The `owner` role cannot be deleted.
</Component>

---

## Assigning Users to Roles [#assigning-users-to-roles]

### Via Invitation [#via-invitation]

When inviting users, specify their role:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await tenantsApi.createInvite({
  createTenantUserInviteRequest: {
    email: 'teammate@example.com',
    role: 'developer',  // Role name
    inviteUrl: 'https://app.example.com/auth/onboarding',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := tenantsClient.CreateInvite(ctx).CreateTenantUserInviteRequest(omnibase.CreateTenantUserInviteRequest{
    Email:    "teammate@example.com",
    Role:     "developer",
    InviteUrl: "https://app.example.com/auth/onboarding",
}).Execute()
```
</Tab>
</Tabs>

### Updating Existing User's Role [#updating-existing-users-role]

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
await tenantsApi.updateTenantUserRole({
  updateTenantUserRoleRequest: {
    userId: targetUserId,
    role: 'admin',  // New role name
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := tenantsClient.UpdateTenantUserRole(ctx).UpdateTenantUserRoleRequest(omnibase.UpdateTenantUserRoleRequest{
    Role:   "admin",
    UserId: targetUserId,
}).Execute()
```
</Tab>
</Tabs>

---

## Common Role Patterns [#common-role-patterns]

<Tabs items={["Owner","Admin","Developer","Viewer"]}>
<Tab value="Owner">
**Full Control** — Auto-assigned to tenant creator

Typical permissions:
- All user management permissions
- All API key permissions
- All sensitive data access
- Tenant deletion

```typescript
const ownerPermissions = [
  'tenant#can_delete_tenant',
  'tenant#can_invite_user',
  'tenant#can_remove_user',
  'tenant#can_update_user_role',
  'tenant#can_view_users',
  'tenant#can_update_roles',
  'tenant#can_create_api_keys',
  'tenant#can_view_api_keys',
  'tenant#can_revoke_api_keys',
  'tenant#can_view_database_password',
  'tenant#can_rotate_keys',
];
```
</Tab>

<Tab value="Admin">
**Team Management** — For team managers

Typical permissions:
- User management (invite, remove, update roles)
- API key management
- Cannot delete tenant

```typescript
const adminPermissions = [
  'tenant#can_invite_user',
  'tenant#can_remove_user',
  'tenant#can_update_user_role',
  'tenant#can_view_users',
  'tenant#can_update_roles',
  'tenant#can_create_api_keys',
  'tenant#can_view_api_keys',
  'tenant#can_revoke_api_keys',
];
```
</Tab>

<Tab value="Developer">
**Development Access** — For developers

Typical permissions:
- View team members
- API key management
- Database connection access

```typescript
const developerPermissions = [
  'tenant#can_view_users',
  'tenant#can_create_api_keys',
  'tenant#can_view_api_keys',
  'tenant#can_view_database_connection_string',
  'tenant#can_view_project_env',
];
```
</Tab>

<Tab value="Viewer">
**Read-Only Access** — For external collaborators

Typical permissions:
- View team members only

```typescript
const viewerPermissions = [
  'tenant#can_view_users',
];
```
</Tab>
</Tabs>

---

## Resource-Level Permissions [#resource-level-permissions]

For fine-grained access to specific resources (projects, documents, etc.), use direct permission relationships:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
// Grant project-specific access
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Project',
    object: projectId,
    relation: 'can_write',
    subjectId: userId,
    subjectNamespace: 'User',
  },
});
```
</Tab>

<Tab value="Go">
```go
_, _, err := client.CreateRelationship(ctx).CreateRelationshipRequest(omnibase.CreateRelationshipRequest{
    Namespace: "Project",
    Object:    projectId,
    Relation:  "can_write",
    SubjectSet: omnibase.SubjectSetRequest{
        Namespace: "User",
        Object:    userId,
    },
}).Execute()
```
</Tab>
</Tabs>

This allows scenarios like:
- **Contractor**: No tenant-wide permissions, only specific project access
- **Project Lead**: Manage specific projects without tenant admin access
- **Auditor**: Read-only access to specific resources

---

## Example: Setting Up a New Tenant [#example-setting-up-a-new-tenant]

When a new tenant is created, you might want to set up default roles:

<Tabs groupId="lang" items={["TypeScript","Go"]}>
<Tab value="TypeScript">
```typescript
async function setupTenantRoles(tenantsApi: V1TenantsApi) {
  // Owner role is created automatically

  // Create admin role
  await tenantsApi.createRole({
    createRoleRequest: {
      roleName: 'admin',
      permissions: [
        'tenant#can_invite_user',
        'tenant#can_remove_user',
        'tenant#can_update_user_role',
        'tenant#can_view_users',
        'tenant#can_create_api_keys',
        'tenant#can_view_api_keys',
      ],
    },
  });

  // Create developer role
  await tenantsApi.createRole({
    createRoleRequest: {
      roleName: 'developer',
      permissions: [
        'tenant#can_view_users',
        'tenant#can_create_api_keys',
        'tenant#can_view_api_keys',
        'tenant#can_view_database_connection_string',
      ],
    },
  });

  // Create member role
  await tenantsApi.createRole({
    createRoleRequest: {
      roleName: 'member',
      permissions: [
        'tenant#can_view_users',
      ],
    },
  });
}
```
</Tab>

<Tab value="Go">
```go
func setupTenantRoles(ctx context.Context, tenantsClient *omnibase.V1TenantsAPIService) error {
    // Owner role is created automatically

    // Create admin role
    _, _, err := tenantsClient.CreateRole(ctx).CreateRoleRequest(omnibase.CreateRoleRequest{
        RoleName: "admin",
        Permissions: []string{
            "tenant#can_invite_user",
            "tenant#can_remove_user",
            "tenant#can_update_user_role",
            "tenant#can_view_users",
            "tenant#can_create_api_keys",
            "tenant#can_view_api_keys",
        },
    }).Execute()
    if err != nil {
        return err
    }

    // Create developer role
    _, _, err = tenantsClient.CreateRole(ctx).CreateRoleRequest(omnibase.CreateRoleRequest{
        RoleName: "developer",
        Permissions: []string{
            "tenant#can_view_users",
            "tenant#can_create_api_keys",
            "tenant#can_view_api_keys",
            "tenant#can_view_database_connection_string",
        },
    }).Execute()
    if err != nil {
        return err
    }

    // Create member role
    _, _, err = tenantsClient.CreateRole(ctx).CreateRoleRequest(omnibase.CreateRoleRequest{
        RoleName: "member",
        Permissions: []string{
            "tenant#can_view_users",
        },
    }).Execute()
    return err
}
```
</Tab>
</Tabs>

---

## Next Steps [#next-steps]

- [Defining Permissions](/guides/rbac/permissions) — Create permission namespaces with JSDoc metadata
- [Team Invitations](/guides/multi-tenancy/invitations) — Invite users with specific roles
- [Permissions Concept](/concepts/permissions) — Deep dive into ReBAC internals

# Document Storage (/guides/storage)

Omnibase provides S3-compatible file storage with per-object permissions powered by Ory Keto (ReBAC). Every file gets its own permission tuples, so you can share individual files with specific users without exposing the rest of a tenant's files.

**Key Features:**
- Presigned URLs for direct browser uploads/downloads
- Per-object permissions via Keto (owner, can_read, can_delete, can_make_public)
- Automatic owner assignment on upload
- Share individual files with specific users
- Make files publicly accessible across tenants
- Custom metadata support
- Tenant isolation by default

---

## Architecture Overview [#architecture-overview]

```
┌─────────────┐     1. Request presigned URL     ┌─────────────┐
│   Client    │ ────────────────────────────────►│  Omnibase   │
│  (Browser)  │                                  │     API     │
└─────────────┘                                  └──────┬──────┘
      │                                                 │
      │                                          2. Check Keto
      │                                            permission
      │                                                 │
      │                                                 ▼
      │                                          ┌─────────────┐
      │                                          │  Ory Keto   │
      │                                          │   (ReBAC)   │
      │                                          └─────────────┘
      │
      │  3. Upload/Download directly
      │     using presigned URL
      │
      ▼
┌─────────────┐
│     S3      │
│  (MinIO)    │
└─────────────┘
```

Files are never proxied through the API server. Clients upload and download directly to S3 using time-limited presigned URLs (valid for 15 minutes).

---

## API Endpoints [#api-endpoints]

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/v1/storage/upload` | Get presigned upload URL |
| POST | `/api/v1/storage/download` | Get presigned download URL |
| DELETE | `/api/v1/storage/object` | Delete a file |
| POST | `/api/v1/storage/make-public` | Make a file publicly accessible |

---

## Path Namespaces [#path-namespaces]

<Component type="warning">
Storage paths are bucket-wide, not tenant-scoped. Two tenants cannot both own `avatars/me.png`, and the second upload receives a `409 Conflict`. Prefix every path with the tenant ID or another unique namespace, for example `tenants/${tenantId}/avatars/me.png`.
</Component>

---

## Uploading Files [#uploading-files]

When you upload a file, Omnibase automatically creates an `owner` relation in Keto. This gives you read, delete, and make-public permissions on the file without any extra setup.

### Step 1: Request Upload URL [#step-1-request-upload-url]

```typescript
import { Configuration, V1StorageApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: 'http://localhost:8080',
  headers: {
    'X-Service-Key': 'your-service-key',
    'X-User-Id': userId,
    'X-Tenant-Id': tenantId,
  },
});

const storageApi = new V1StorageApi(config);

const { data } = await storageApi.uploadFile({
  uploadRequest: {
    path: `tenants/${tenantId}/documents/report-2024.pdf`,
    metadata: {
      description: 'Annual report',
      uploaded_by: userId,
    },
  },
});

console.log('Upload URL:', data.data.upload_url);
console.log('File path:', data.data.path);
console.log('Object ID:', data.data.id); // Use this ID for sharing
```

The response includes an `id` field — this is the storage object's UUID. You'll need it to share the file with other users via the permissions API.

### Step 2: Upload to S3 [#step-2-upload-to-s3]

Upload the file directly to S3 using the presigned URL:

```typescript
const file = document.getElementById('file-input').files[0];

await fetch(data.data.upload_url, {
  method: 'PUT',
  body: file,
  headers: {
    'Content-Type': file.type,
  },
});
```

<Component type="info">
Presigned URLs expire after 15 minutes. Request a new URL if the upload fails due to expiration.
</Component>

---

## Downloading Files [#downloading-files]

Downloads check Keto permissions. The requesting user must be the file owner or have a `can_read` relation on the file. Public files skip this check entirely.

### Step 1: Request Download URL [#step-1-request-download-url]

```typescript
const { data } = await storageApi.downloadFile({
  downloadRequest: {
    path: `tenants/${tenantId}/documents/report-2024.pdf`,
  },
});

console.log('Download URL:', data.data.download_url);
```

### Step 2: Download from S3 [#step-2-download-from-s3]

```typescript
// Option 1: Direct browser download
window.location.href = data.data.download_url;

// Option 2: Fetch and process
const response = await fetch(data.data.download_url);
const blob = await response.blob();
```

---

## Deleting Files [#deleting-files]

Deletes check Keto permissions. The requesting user must be the file owner or have a `can_delete` relation. When a file is deleted, all its Keto permission tuples are cleaned up automatically.

```typescript
const { data } = await storageApi.deleteObject({
  deleteObjectRequest: {
    path: `tenants/${tenantId}/documents/report-2024.pdf`,
  },
});

console.log(data.data.message); // "file deleted"
```

<Component type="warning">
Deletion removes the file metadata from PostgreSQL, the file from S3, and all Keto permission tuples. This operation cannot be undone.
</Component>

---

## Sharing Files [#sharing-files]

By default, only the file owner can read, delete, or make a file public. To grant access to other users, create a relationship via the permissions API.

### Grant Read Access [#grant-read-access]

```typescript
import { V1PermissionsApi } from '@omnibase/core-js';

const permissionsApi = new V1PermissionsApi(config);

// Share a file with another user (use the object ID from the upload response)
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'StorageObject',
    object: fileObjectId,       // UUID from upload response
    relation: 'can_read',
    subject_set: {
      namespace: 'User',
      object: otherUserId,      // UUID of user to share with
      relation: '',
    },
  },
});
```

### Grant Delete Access [#grant-delete-access]

```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'StorageObject',
    object: fileObjectId,
    relation: 'can_delete',
    subject_set: {
      namespace: 'User',
      object: otherUserId,
      relation: '',
    },
  },
});
```

### Revoke Access [#revoke-access]

```typescript
await permissionsApi.deleteRelationship({
  namespace: 'StorageObject',
  object: fileObjectId,
  relation: 'can_read',
  subject_set: {
    namespace: 'User',
    object: otherUserId,
    relation: '',
  },
});
```

### Available Relations [#available-relations]

| Relation | Permission | Auto-Created |
|----------|-----------|--------------|
| `owner` | Read, delete, make public | Yes (on upload) |
| `can_read` | Download the file | No |
| `can_delete` | Delete the file | No |
| `can_make_public` | Make the file publicly accessible | No |

---

## Making Files Public [#making-files-public]

Public files are accessible to any authenticated user, regardless of which tenant they belong to. This is useful for shared assets like logos, public documents, or downloadable resources.

### Make a File Public [#make-a-file-public]

```typescript
const { data } = await storageApi.makeFilePublic({
  makePublicRequest: {
    path: `tenants/${tenantId}/assets/company-logo.png`,
  },
});

console.log(data.data.message); // "file is now public"
```

Only the file owner or users with the `can_make_public` relation can make a file public. The operation is idempotent — calling it on an already-public file returns success.

### How Public Files Work [#how-public-files-work]

- Public files skip Keto permission checks on download
- Any authenticated user can download a public file, even from a different tenant
- The download endpoint first looks for the file in the requesting user's tenant, then falls back to checking public files globally
- Making a file public cannot be reversed through the API (update the `is_public` column directly if needed)

---

## Tenant-Wide Storage Access [#tenant-wide-storage-access]

By default, storage permissions are per-object: only the owner and explicitly shared users can access a file. If you want certain users (e.g. admins) to access all files in a tenant, you can set this up using OPL traversal.

### Step 1: Add a Relation to the Tenant Namespace [#step-1-add-a-relation-to-the-tenant-namespace]

In your `permissions.ts` OPL file, add a `can_read_all_storage_objects` relation to the `Tenant` class and a corresponding permit:

```typescript
class Tenant implements Namespace {
  related: {
    // ... existing relations ...
    can_read_all_storage_objects: User[];
  };

  permits = {
    // ... existing permits ...
    read_all_storage_objects: (ctx: Context): boolean =>
      this.related.can_read_all_storage_objects.includes(ctx.subject),
  };
}
```

### Step 2: Add Tenant Traversal to StorageObject [#step-2-add-tenant-traversal-to-storageobject]

Update the `StorageObject` class to traverse the `tenant` relation and check if the user has the tenant-wide permit:

```typescript
class StorageObject implements Namespace {
  related: {
    owner: User[];
    can_read: User[];
    can_delete: User[];
    can_make_public: User[];
    tenant: Tenant[];
  };

  permits = {
    read: (ctx: Context): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_read.includes(ctx.subject) ||
      this.related.tenant.traverse((t) =>
        t.permits.read_all_storage_objects(ctx)),

    // ... other permits stay the same ...
  };
}
```

### Step 3: Assign the Relation to Users [#step-3-assign-the-relation-to-users]

When creating a role (e.g. `admin`), include `tenant#can_read_all_storage_objects` in the role's permissions. Any user assigned that role will automatically be able to read all files in the tenant.

You can also assign it directly via the permissions API:

```typescript
await permissionsApi.createRelationship({
  createRelationshipRequest: {
    namespace: 'Tenant',
    object: tenantId,
    relation: 'can_read_all_storage_objects',
    subject_set: {
      namespace: 'User',
      object: adminUserId,
      relation: '',
    },
  },
});
```

This works because every file upload creates a `tenant` relation linking the StorageObject to its Tenant. The OPL `traverse` follows that link and checks whether the user has the `read_all_storage_objects` permit on the parent Tenant.

You can apply the same pattern for tenant-wide delete or make-public access by adding corresponding relations and permits.

---

## File Paths [#file-paths]

You control the full path structure. Paths must:
- Start with an alphanumeric character
- Contain only: `a-z`, `A-Z`, `0-9`, `/`, `_`, `.`, ` `, `-`
- Be 1-1024 characters long

**Example path structures:**

```
avatars/user-123.png           # User avatars
documents/invoices/2024-01.pdf # Nested directories
assets/logo.png                # Shared assets
reports/q1-summary.pdf         # Team documents
```

---

## Permission Model [#permission-model]

### StorageObject OPL Namespace [#storageobject-opl-namespace]

The `StorageObject` namespace defines per-object permissions:

```typescript
class StorageObject implements Namespace {
  related: {
    owner: User[];           // Set automatically on upload
    can_read: User[];        // Grant via permissions API
    can_delete: User[];      // Grant via permissions API
    can_make_public: User[]; // Grant via permissions API
    tenant: Tenant[];        // Set automatically on upload
  };

  permits = {
    read: (ctx: Context): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_read.includes(ctx.subject),

    delete: (ctx: Context): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_delete.includes(ctx.subject),

    make_public: (ctx: Context): boolean =>
      this.related.owner.includes(ctx.subject) ||
      this.related.can_make_public.includes(ctx.subject),
  };
}
```

### What Happens Automatically [#what-happens-automatically]

**On upload:**
- `owner` relation created → uploader can read, delete, and make the file public
- `tenant` relation created → links the file to its tenant (used for OPL traversal)

**On delete:**
- All Keto tuples for the object are cleaned up (owner, can_read, can_delete, etc.)

### Tenant Isolation [#tenant-isolation]

Files are scoped to a tenant via the `tenant_id` column in `storage.objects`. A user in Tenant A cannot see or access files belonging to Tenant B, even if they know the file path.

The only exception is public files — once a file is made public via `/api/v1/storage/make-public`, any authenticated user can download it regardless of tenant.

---

## Authentication [#authentication]

All storage endpoints require authentication via one of:

| Method | Headers Required |
|--------|------------------|
| Session Auth | Cookie: `omnibase_postgrest_jwt` or Header: `X-Postgrest-Token` |
| Service Key Auth | `X-Service-Key` + `X-User-Id` + `X-Tenant-Id` |

---

## Metadata [#metadata]

Store custom metadata with each file:

```typescript
await storageApi.uploadFile({
  uploadRequest: {
    path: 'documents/contract.pdf',
    metadata: {
      document_type: 'contract',
      client_name: 'Acme Corp',
      version: 2,
      tags: ['legal', 'signed'],
    },
  },
});
```

Metadata is stored as JSONB in PostgreSQL.

---

## Complete Example [#complete-example]

```typescript
import { Configuration, V1StorageApi, V1PermissionsApi } from '@omnibase/core-js';

async function uploadAndShare(file: File, tenantId: string, userId: string, shareWithUserId: string) {
  const config = new Configuration({
    basePath: process.env.OMNIBASE_API_URL,
    headers: {
      'X-Service-Key': process.env.OMNIBASE_SERVICE_KEY,
      'X-User-Id': userId,
      'X-Tenant-Id': tenantId,
    },
  });

  // Upload file
  const storageApi = new V1StorageApi(config);
  const { data: uploadData } = await storageApi.uploadFile({
    uploadRequest: {
      path: `uploads/${Date.now()}-${file.name}`,
      metadata: {
        original_name: file.name,
        content_type: file.type,
        size: file.size,
      },
    },
  });

  // Upload to S3
  await fetch(uploadData.data.upload_url, {
    method: 'PUT',
    body: file,
    headers: { 'Content-Type': file.type },
  });

  // Share with another user
  const permissionsApi = new V1PermissionsApi(config);
  await permissionsApi.createRelationship({
    createRelationshipRequest: {
      namespace: 'StorageObject',
      object: uploadData.data.id,
      relation: 'can_read',
      subject_set: {
        namespace: 'User',
        object: shareWithUserId,
        relation: '',
      },
    },
  });

  return { path: uploadData.data.path, id: uploadData.data.id };
}
```

---

## Error Handling [#error-handling]

| Status | Error | Cause |
|--------|-------|-------|
| 400 | Invalid path | Path doesn't match allowed pattern |
| 403 | Access denied | User doesn't have the required Keto permission |
| 404 | File not found | File doesn't exist in this tenant |

```typescript
try {
  await storageApi.downloadFile({
    downloadRequest: { path: 'missing-file.pdf' },
  });
} catch (error) {
  if (error.response?.status === 404) {
    console.log('File not found');
  } else if (error.response?.status === 403) {
    console.log('Access denied - ask the file owner to share it with you');
  }
}
```

---

## Next Steps [#next-steps]

- [Row-Level Security](/guides/postgresql/rls) — Writing custom RLS policies with ReBAC helpers
- [RBAC Guide](/guides/rbac) — Role-based access control
- [Permissions Concept](/concepts/permissions) — How ReBAC works
- [API Reference](/api) — Complete API documentation

# Checkout & Customer Portal (/guides/stripe/checkout-portal)

Omnibase integrates with Stripe Checkout for secure payment collection and Customer Portal for self-service billing management.

## Stripe Checkout [#stripe-checkout]

Checkout provides a hosted payment page that handles card collection, validation, 3D Secure, and payment processing.

### Creating a Checkout Session [#creating-a-checkout-session]

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
    cancelUrl: 'https://example.com/pricing',
  },
});

// Redirect to Stripe Checkout
window.location.href = data.url;
```

### Checkout Options [#checkout-options]

| Option | Type | Description |
|--------|------|-------------|
| `priceId` | `string` | Config price ID to purchase |
| `successUrl` | `string` | URL to redirect after successful payment |
| `cancelUrl` | `string` | URL to redirect if customer cancels |
| `trialPeriodDays` | `number` | Days of free trial (subscriptions only) |
| `promotionCode` | `string` | Pre-applied promotion code |
| `allowPromotionCodes` | `boolean` | Let customers enter codes at checkout |

### Mode Detection [#mode-detection]

Omnibase automatically detects the checkout mode based on the price:

| Price Type | Checkout Mode | Description |
|------------|---------------|-------------|
| Recurring (has `interval`) | `subscription` | Creates a subscription |
| One-time (no `interval`) | `payment` | Single payment |

### Trial Periods [#trial-periods]

Add a free trial to subscription checkouts:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    trialPeriodDays: 14, // 14-day free trial
  },
});
```

During trial:
- Customer's payment method is collected but not charged
- Subscription status is `trialing`
- `trial_will_end` webhook fires 3 days before trial ends
- Customer is charged when trial ends

### Promotion Codes [#promotion-codes]

#### Pre-Applied Code [#pre-applied-code]

Apply a specific promotion code automatically:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    promotionCode: 'WELCOME50',
  },
});
```

#### Customer-Entered Codes [#customer-entered-codes]

Allow customers to enter their own codes:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    allowPromotionCodes: true,
  },
});
```

<Component type="warn">
You cannot use both `promotionCode` and `allowPromotionCodes` in the same checkout.
</Component>

## Customer Portal [#customer-portal]

The Customer Portal is a Stripe-hosted page where customers can:

- View and download invoices
- Update payment methods
- Change subscription plans
- Cancel subscriptions
- Update billing information

### Creating a Portal Session [#creating-a-portal-session]

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

const { data } = await paymentsApi.createCustomerPortal({
  createPortalRequest: {
    returnUrl: 'https://example.com/settings',
  },
});

// Redirect to Customer Portal
window.location.href = data.url;
```

### Portal Configuration [#portal-configuration]

Configure the Customer Portal in your [Stripe Dashboard](https://dashboard.stripe.com/settings/billing/portal):

- **Invoice history** — Allow viewing past invoices
- **Payment methods** — Allow updating cards
- **Subscription updates** — Allow plan changes
- **Subscription cancellation** — Allow self-service cancellation
- **Customer information** — Allow updating billing details

## Next.js Implementation [#nextjs-implementation]

### Server Actions [#server-actions]

```tsx title="app/(dashboard)/subscriptions/actions.ts"
'use server';

import { redirect } from 'next/navigation';
import { V1PaymentsApi, Configuration } from '@omnibase/core-js';
import { cookies, headers } from 'next/headers';

async function getConfig() {
  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((c) => `${c.name}=${c.value}`)
    .join('; ');

  return new Configuration({
    basePath: process.env.OMNIBASE_API_URL,
    headers: { Cookie: cookieHeader },
  });
}

export async function createCheckout(priceId: string) {
  const config = await getConfig();
  const paymentsApi = new V1PaymentsApi(config);

  const headersList = await headers();
  const host = headersList.get('host');
  const protocol = headersList.get('x-forwarded-proto') || 'https';
  const baseUrl = `${protocol}://${host}`;

  const { data } = await paymentsApi.createCheckout({
    createCheckoutRequest: {
      priceId,
      successUrl: `${baseUrl}/subscriptions?success=true`,
      cancelUrl: `${baseUrl}/subscriptions`,
      trialPeriodDays: 14,
      allowPromotionCodes: true,
    },
  });

  redirect(data.url!);
}

export async function openCustomerPortal() {
  const config = await getConfig();
  const paymentsApi = new V1PaymentsApi(config);

  const headersList = await headers();
  const host = headersList.get('host');
  const protocol = headersList.get('x-forwarded-proto') || 'https';
  const returnUrl = `${protocol}://${host}/subscriptions`;

  const { data } = await paymentsApi.createCustomerPortal({
    createPortalRequest: { returnUrl },
  });

  redirect(data.url!);
}
```

### Subscriptions Page [#subscriptions-page]

```tsx title="app/(dashboard)/subscriptions/page.tsx"
import { V1StripeApi, V1TenantsApi } from '@omnibase/core-js';
import { PricingTable } from '@omnibase/shadcn';
import { createCheckout, openCustomerPortal } from './actions';
import { CustomerPortalButton } from './customer-portal-button';

export default async function SubscriptionsPage() {
  const stripeApi = new V1StripeApi(config);
  const tenantsApi = new V1TenantsApi(config);

  const [{ data: stripeConfig }, { data: subscriptions }] = await Promise.all([
    stripeApi.getStripeConfig(),
    tenantsApi.listTenantSubscriptions(),
  ]);

  const currentPriceId = subscriptions?.[0]?.configPriceId;

  return (
    <div className="container py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-2xl font-bold">Subscription</h1>
        {currentPriceId && (
          <form action={openCustomerPortal}>
            <CustomerPortalButton />
          </form>
        )}
      </div>

      <PricingTable
        products={stripeConfig.products}
        selectedPriceId={currentPriceId}
        onPriceSelect={createCheckout}
        showPricingToggle
        defaultInterval="month"
      />
    </div>
  );
}
```

### Customer Portal Button [#customer-portal-button]

```tsx title="app/(dashboard)/subscriptions/customer-portal-button.tsx"
'use client';

import { useFormStatus } from 'react-dom';
import { Button } from '@/components/ui/button';
import { ExternalLink, Loader2 } from 'lucide-react';

interface CustomerPortalButtonProps {
  label?: string;
  className?: string;
  variant?: 'default' | 'outline' | 'secondary' | 'ghost';
  showIcon?: boolean;
}

export function CustomerPortalButton({
  label = 'Manage Billing',
  className,
  variant = 'outline',
  showIcon = true,
}: CustomerPortalButtonProps) {
  const { pending } = useFormStatus();

  return (
    <Button
      type="submit"
      variant={variant}
      className={className}
      disabled={pending}
    >
      {pending ? (
        <Loader2 className="h-4 w-4 animate-spin mr-2" />
      ) : showIcon ? (
        <ExternalLink className="h-4 w-4 mr-2" />
      ) : null}
      {label}
    </Button>
  );
}
```

## Handling Success [#handling-success]

After successful checkout, handle the return:

```tsx title="app/(dashboard)/subscriptions/page.tsx"
import { Suspense } from 'react';

function SuccessMessage({ searchParams }: { searchParams: { success?: string } }) {
  if (searchParams.success === 'true') {
    return (
      <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-8">
        <h3 className="text-green-800 font-medium">Welcome to Pro!</h3>
        <p className="text-green-700 text-sm">
          Your subscription is now active. You have access to all Pro features.
        </p>
      </div>
    );
  }
  return null;
}

export default async function SubscriptionsPage({
  searchParams,
}: {
  searchParams: { success?: string };
}) {
  return (
    <div>
      <Suspense fallback={null}>
        <SuccessMessage searchParams={searchParams} />
      </Suspense>
      {/* Rest of page */}
    </div>
  );
}
```

## Webhook Events [#webhook-events]

Handle checkout and portal events:

```json
{
  "webhooks": [
    {
      "id": "checkout_events",
      "url": "${WEBHOOK_URL}/api/stripe/checkout",
      "events": [
        "checkout.session.completed",
        "checkout.session.expired",
        "checkout.session.async_payment_succeeded",
        "checkout.session.async_payment_failed"
      ]
    }
  ]
}
```

### Checkout Session Completed [#checkout-session-completed]

```typescript
case 'checkout.session.completed':
  const session = event.data.object as Stripe.Checkout.Session;

  // For subscriptions
  if (session.mode === 'subscription') {
    const subscriptionId = session.subscription as string;
    const customerId = session.customer as string;

    // Activate features for customer
    await activateSubscription(customerId, subscriptionId);
  }

  // For one-time payments
  if (session.mode === 'payment') {
    const paymentIntentId = session.payment_intent as string;

    // Fulfill order
    await fulfillOrder(session.metadata);
  }
  break;
```

## Free Tier Handling [#free-tier-handling]

For $0 prices, Omnibase bypasses Stripe Checkout since Stripe doesn't support free subscriptions:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'free', // $0 price
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
  },
});

// For free prices, the subscription is created directly
// and you receive a success response without a Stripe URL
```

## Error Handling [#error-handling]

Handle common checkout errors:

```typescript
try {
  const { data } = await paymentsApi.createCheckout({
    createCheckoutRequest: {
      priceId: 'pro_monthly',
      successUrl: 'https://example.com/success',
      cancelUrl: 'https://example.com/pricing',
    },
  });

  redirect(data.url!);
} catch (error) {
  if (error.status === 400) {
    // Invalid price ID or configuration
    return { error: 'Invalid plan selected' };
  }
  if (error.status === 402) {
    // Payment required (no payment method)
    return { error: 'Please add a payment method' };
  }
  throw error;
}
```

## Best Practices [#best-practices]

1. **Always Validate Success** — Don't trust the success URL alone; verify via webhook

2. **Handle Expiration** — Checkout sessions expire after 24 hours by default

3. **Use Metadata** — Pass custom data through checkout for order fulfillment

4. **Secure URLs** — Include session IDs in success URLs for verification

5. **Configure Portal** — Customize the Customer Portal to match your business needs

6. **Test Thoroughly** — Use Stripe test mode and test cards before going live

## Related [#related]

- [Subscriptions](/guides/stripe/subscriptions) — Subscription management
- [Coupons & Promotions](/guides/stripe/coupons-promotions) — Discount codes
- [Webhooks](/guides/stripe/webhooks) — Event handling
- [UI Components](/guides/stripe/ui-components) — PricingTable component

# Configuration Guide (/guides/stripe/configuration)

Omnibase uses JSON configuration files to define your Stripe billing setup. This guide covers the complete schema and all available options.

## Configuration Schema [#configuration-schema]

Every configuration file must include a `version` and at least one `product`:

```json title="omnibase/stripe/config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "webhooks": [],
  "meters": [],
  "products": [],
  "coupons": [],
  "promotion_codes": []
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `$schema` | `string` | No | JSON Schema URL for IDE autocomplete |
| `version` | `string` | Yes | Semantic version (e.g., `"1.0.0"`) |
| `webhooks` | `array` | No | Webhook endpoint configurations |
| `meters` | `array` | No | Billing meters for usage-based pricing |
| `products` | `array` | Yes | Product definitions (minimum 1) |
| `coupons` | `array` | No | Discount coupon definitions |
| `promotion_codes` | `array` | No | Promotion codes for coupons |

<Component type="info">
Add `"$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json"` to enable IDE autocomplete in VS Code and other editors.
</Component>

## Version Management [#version-management]

The `version` field must follow semantic versioning:

```json
{
  "version": "1.0.0"
}
```

<Component type="info">
Version changes are tracked in the configuration history. Use `omnibase stripe history` to view past versions.
</Component>

### Version Pattern [#version-pattern]

The version must match the pattern `^\d+\.\d+\.\d+$`:

- `1.0.0` - Valid
- `2.1.0` - Valid
- `1.0` - Invalid (missing patch version)
- `v1.0.0` - Invalid (no `v` prefix)

## File Organization [#file-organization]

You can split your configuration across multiple files for better organization:

<Files>
<Folder name="omnibase" defaultOpen>
<Folder name="stripe" defaultOpen>
<File name="webhook.config.json" />

<File name="subscriptions.config.json" />

<File name="shared-tiers.config.json" />

<File name="cloudflare-workers.config.json" />

<File name="neon.config.json" />

<File name="ses.config.json" />
</Folder>
</Folder>
</Files>

### Example: Subscription Plans [#example-subscription-plans]

```json title="omnibase/stripe/subscriptions.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "products": [
    {
      "id": "free",
      "name": "Free Plan",
      "description": "Get started with Omnibase",
      "type": "service",
      "prices": [
        {
          "id": "free",
          "amount": 0,
          "currency": "usd",
          "interval": "month",
          "usage_type": "licensed",
          "billing_scheme": "per_unit",
          "public": true,
          "ui": {
            "display_name": "Free",
            "billing_period": "Forever",
            "price_display": {
              "custom_text": "Free",
              "show_currency": false
            },
            "features": [
              "Up to 2 instances",
              "Community support"
            ],
            "limits": [
              {
                "text": "2.5% transaction fee",
                "value": 2.5,
                "unit": "percent"
              }
            ]
          }
        }
      ],
      "ui": {
        "display_name": "Free",
        "tagline": "For personal projects",
        "sort_order": 1
      }
    },
    {
      "id": "pro",
      "name": "Pro Plan",
      "description": "For professional developers",
      "type": "service",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "pro_yearly",
          "amount": 49000,
          "currency": "usd",
          "interval": "year",
          "public": true
        }
      ],
      "ui": {
        "display_name": "Pro",
        "tagline": "For growing teams",
        "badge": "Most Popular",
        "highlighted": true,
        "cta_text": "Upgrade to Pro",
        "sort_order": 3
      }
    }
  ]
}
```

### Example: Usage-Based Infrastructure Pricing [#example-usage-based-infrastructure-pricing]

```json title="omnibase/stripe/cloudflare-workers.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "products": [
    {
      "id": "cloudflare_workers",
      "name": "Cloudflare Workers",
      "type": "good",
      "prices": [
        {
          "id": "cloudflare_workers_requests",
          "amount": 60,
          "currency": "usd",
          "interval": "month",
          "usage_type": "metered",
          "billing_scheme": "per_unit",
          "public": false,
          "ui": {
            "display_name": "Worker Requests",
            "billing_period": "per million requests"
          }
        },
        {
          "id": "cloudflare_workers_cpu_ms",
          "amount": 4,
          "currency": "usd",
          "interval": "month",
          "usage_type": "metered",
          "billing_scheme": "per_unit",
          "public": false,
          "ui": {
            "display_name": "CPU Milliseconds",
            "billing_period": "per million ms"
          }
        }
      ]
    }
  ]
}
```

## Environment Variable Interpolation [#environment-variable-interpolation]

Configuration files support environment variable interpolation using `${VAR_NAME}` syntax:

```json
{
  "webhooks": [
    {
      "id": "main_webhook",
      "url": "${STRIPE_WEBHOOK_URL}/api/stripe/webhook",
      "events": ["invoice.created"]
    }
  ]
}
```

Set the environment variable in your `.env` file:

```bash title=".env"
STRIPE_WEBHOOK_URL=https://api.example.com
```

The URL will be expanded to `https://api.example.com/api/stripe/webhook` when pushed to Stripe.

## CLI Commands [#cli-commands]

### Push Configuration [#push-configuration]

Push your local configuration to Stripe:

```bash
omnibase stripe push
```

This command:
1. Validates all configuration files against the schema
2. Calculates the diff between local and remote configurations
3. Creates new products, prices, meters, coupons, promotion codes
4. Updates existing resources where possible
5. Archives removed resources (marks as inactive)
6. Stores the new configuration version in PostgreSQL

### Pull Configuration [#pull-configuration]

Import existing Stripe configuration:

```bash
omnibase stripe pull --output omnibase/stripe/pulled.config.json
```

This fetches all active products, prices, meters, and webhooks from your Stripe account.

### Validate Configuration [#validate-configuration]

Check configuration without pushing:

```bash
omnibase stripe validate
```

Returns validation errors if the configuration is invalid.

### View History [#view-history]

```bash
omnibase stripe history --limit 10
```

Shows recent configuration versions with timestamps and change summaries.

### Reset [#reset]

<Component type="warn">
This is a destructive operation. It archives all products, prices, meters, coupons, and promotion codes in Stripe.
</Component>

```bash
omnibase stripe reset
```

## API Endpoints [#api-endpoints]

### Get Configuration Schema [#get-configuration-schema]

```bash
GET /api/v1/stripe/schema
```

Returns the JSON schema for validating configuration files. Useful for IDE autocomplete.

### Get Public Configuration [#get-public-configuration]

```bash
GET /api/v1/stripe/config
```

Returns the current configuration with only `public: true` prices visible.

### Get Admin Configuration [#get-admin-configuration]

```bash
GET /api/v1/stripe/admin/config
# Header: X-Service-Key: your-service-key
```

Returns the full configuration including private/enterprise prices.

### Update Configuration [#update-configuration]

```bash
POST /api/v1/stripe/admin/config
Content-Type: application/json
X-Service-Key: your-service-key

{
  "version": "1.0.1",
  "products": [...]
}
```

### Validate Configuration [#validate-configuration-1]

```bash
POST /api/v1/stripe/admin/config/validate
Content-Type: application/json
X-Service-Key: your-service-key

{
  "version": "1.0.0",
  "products": [...]
}
```

Returns validation result without applying changes.

### Get Configuration History [#get-configuration-history]

```bash
GET /api/v1/stripe/admin/config/history?limit=10&offset=0
X-Service-Key: your-service-key
```

Returns paginated configuration history.

## Change Detection [#change-detection]

When you push a configuration, Omnibase calculates a diff and reports:

```json
{
  "changes": {
    "products": {
      "created": ["pro"],
      "updated": ["starter"],
      "archived": ["legacy_plan"]
    },
    "prices": {
      "created": ["pro_monthly", "pro_yearly"],
      "updated": [],
      "archived": ["legacy_price"]
    },
    "meters": {
      "created": [],
      "updated": [],
      "deactivated": []
    },
    "webhooks": {
      "created": ["main_webhook"],
      "updated": [],
      "unchanged": []
    }
  }
}
```

### Archiving vs Deletion [#archiving-vs-deletion]

Omnibase archives resources instead of deleting them because Stripe doesn't allow deletion of resources with payment history. Archived resources:

- Are marked as inactive in Stripe
- Cannot be used for new subscriptions
- Remain accessible for historical data

## ID Mapping [#id-mapping]

Every Stripe object Omnibase manages carries its config ID. Products, coupons, promotion codes and webhooks store it in `metadata.omnibase_id`. Prices also use it as their `lookup_key`. Meters have no metadata and are matched by `event_name`.

Products and prices can also carry user metadata. It is synced to Stripe, and removing a key from the config removes it from Stripe. See [Products & Prices](/guides/stripe/products-prices#metadata) for limits and reserved keys.

### Convert IDs [#convert-ids]

Resolve a Stripe ID (for example from a webhook payload) to its config ID. Requires the service key or an app key.

```bash
GET /api/v1/stripe/convert/stripe-id/price_1ABC123
```

Returns:

```json
{
  "stripe_id": "price_1ABC123...",
  "config_id": "pro_monthly",
  "item_type": "price",
  "config_uuid": "8f3c..."
}
```

## Validation Rules [#validation-rules]

### Required Fields [#required-fields]

- Every product must have an `id` and `name`
- Every price must have an `id`, `currency`, and either `amount` or `tiers`
- Every meter must have an `id`, `display_name`, and `event_name`

### Constraints [#constraints]

- Price `amount` must be >= 0
- Currency must be a valid 3-letter code (lowercase)
- Billing interval must be `day`, `week`, `month`, or `year`
- Tiered prices must have `billing_scheme: "tiered"` and a `tiers` array
- Metered prices must reference a defined meter

### Duplicate Detection [#duplicate-detection]

Omnibase rejects configurations with:
- Duplicate product IDs
- Duplicate price IDs (across all products)
- Duplicate meter IDs
- Duplicate webhook URLs

## Migration Support [#migration-support]

When migrating from an existing Stripe setup, you can include `stripe_id` fields:

```json
{
  "id": "pro_monthly",
  "stripe_id": "price_1ABC123...",
  "amount": 4900
}
```

This associates your config ID with an existing Stripe resource.

## Best Practices [#best-practices]

1. **Use Descriptive IDs** — Choose config IDs that are human-readable: `pro_monthly` not `price_1`

2. **Organize by Purpose** — Split configurations into logical files (subscriptions, usage, enterprise)

3. **Version Thoughtfully** — Increment versions when making significant changes

4. **Test in Staging** — Use a separate Stripe account for testing before pushing to production

5. **Review Diffs** — Always review the changes summary before confirming a push

6. **Keep History** — Don't delete old configuration files; version control handles history

## Related [#related]

- [Products & Prices](/guides/stripe/products-prices) — Detailed product and pricing configuration
- [Webhooks](/guides/stripe/webhooks) — Webhook endpoint configuration
- [Metering](/guides/stripe/metering) — Usage-based billing configuration
- [Testing](/guides/stripe/testing) — Testing your configuration

# Coupons & Promotions (/guides/stripe/coupons-promotions)

Omnibase supports Stripe coupons and promotion codes for creating discounts, running promotional campaigns, and offering special pricing to customers.

## Coupons [#coupons]

Coupons define the discount amount and rules. Promotion codes are user-facing codes that apply coupons.

### Coupon Configuration [#coupon-configuration]

```json
{
  "coupons": [
    {
      "id": "summer_sale",
      "name": "Summer Sale 2024",
      "percent_off": 20,
      "duration": "repeating",
      "duration_in_months": 3,
      "max_redemptions": 100,
      "redeem_by": "2024-09-01T00:00:00Z",
      "applies_to": ["pro", "team"],
      "metadata": {
        "campaign": "summer_2024"
      }
    }
  ]
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique coupon identifier |
| `name` | `string` | No | Display name for the coupon |
| `percent_off` | `number` | One of | Percentage discount (1-100) |
| `amount_off` | `integer` | One of | Fixed amount discount (in cents) |
| `currency` | `string` | If amount_off | Currency for fixed amount discounts |
| `duration` | `string` | Yes | `once`, `repeating`, or `forever` |
| `duration_in_months` | `integer` | If repeating | Number of months for repeating |
| `max_redemptions` | `integer` | No | Maximum total redemptions |
| `redeem_by` | `string` | No | Expiration date (ISO 8601) |
| `applies_to` | `string[]` | No | Product IDs this coupon applies to |
| `metadata` | `object` | No | Custom key-value metadata |
| `stripe_id` | `string` | No | Existing Stripe coupon ID |

### Discount Types [#discount-types]

#### Percentage Discount [#percentage-discount]

```json
{
  "id": "20_percent_off",
  "name": "20% Off",
  "percent_off": 20,
  "duration": "once"
}
```

#### Fixed Amount Discount [#fixed-amount-discount]

```json
{
  "id": "10_dollars_off",
  "name": "$10 Off",
  "amount_off": 1000,
  "currency": "usd",
  "duration": "once"
}
```

### Duration Options [#duration-options]

| Duration | Description | Example Use Case |
|----------|-------------|------------------|
| `once` | Applied once to the first invoice | One-time welcome discount |
| `repeating` | Applied for a number of months | 3-month promotional period |
| `forever` | Applied indefinitely | Permanent partner discount |

```json
// One-time discount
{
  "id": "welcome",
  "percent_off": 50,
  "duration": "once"
}

// 6-month discount
{
  "id": "startup_program",
  "percent_off": 50,
  "duration": "repeating",
  "duration_in_months": 6
}

// Permanent discount
{
  "id": "partner",
  "percent_off": 25,
  "duration": "forever"
}
```

### Product-Specific Coupons [#product-specific-coupons]

Restrict coupons to specific products:

```json
{
  "id": "pro_discount",
  "name": "Pro Plan Discount",
  "percent_off": 30,
  "duration": "once",
  "applies_to": ["pro"]
}
```

<Component type="info">
The `applies_to` array uses config product IDs, not Stripe IDs.
</Component>

### Redemption Limits [#redemption-limits]

Control how many times a coupon can be used:

```json
{
  "id": "limited_offer",
  "percent_off": 50,
  "duration": "once",
  "max_redemptions": 100,
  "redeem_by": "2024-12-31T23:59:59Z"
}
```

| Field | Description |
|-------|-------------|
| `max_redemptions` | Total number of times this coupon can be redeemed |
| `redeem_by` | Last date the coupon can be applied |

## Promotion Codes [#promotion-codes]

Promotion codes are user-facing codes that customers enter at checkout.

### Promotion Code Configuration [#promotion-code-configuration]

```json
{
  "promotion_codes": [
    {
      "id": "summer20",
      "code": "SUMMER20",
      "coupon": "summer_sale",
      "active": true,
      "max_redemptions": 50,
      "first_time_transaction": true,
      "minimum_amount": 5000,
      "minimum_amount_currency": "usd",
      "expires_at": "2024-09-01T00:00:00Z",
      "metadata": {
        "source": "email_campaign"
      }
    }
  ]
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique identifier |
| `code` | `string` | Yes | Customer-facing code (e.g., `"SUMMER20"`) |
| `coupon` | `string` | Yes | Config ID of the coupon to apply |
| `active` | `boolean` | No | Whether the code is active (default: true) |
| `max_redemptions` | `integer` | No | Maximum uses for this specific code |
| `first_time_transaction` | `boolean` | No | Only for first-time customers |
| `minimum_amount` | `integer` | No | Minimum order amount (in cents) |
| `minimum_amount_currency` | `string` | If minimum_amount | Currency for minimum |
| `expires_at` | `string` | No | Expiration date (ISO 8601) |
| `metadata` | `object` | No | Custom key-value metadata |
| `stripe_id` | `string` | No | Existing Stripe promotion code ID |

### Promotion Code Restrictions [#promotion-code-restrictions]

#### First-Time Customers Only [#first-time-customers-only]

```json
{
  "id": "new_customer",
  "code": "WELCOME50",
  "coupon": "50_off_first",
  "first_time_transaction": true
}
```

#### Minimum Purchase Amount [#minimum-purchase-amount]

```json
{
  "id": "big_spender",
  "code": "SAVE20",
  "coupon": "20_percent_off",
  "minimum_amount": 10000,
  "minimum_amount_currency": "usd"
}
```

### Multiple Codes Per Coupon [#multiple-codes-per-coupon]

Create multiple promotion codes for the same coupon to track different campaigns:

```json
{
  "coupons": [
    {
      "id": "launch_discount",
      "percent_off": 25,
      "duration": "once"
    }
  ],
  "promotion_codes": [
    {
      "id": "launch_twitter",
      "code": "TWITTER25",
      "coupon": "launch_discount",
      "metadata": { "source": "twitter" }
    },
    {
      "id": "launch_newsletter",
      "code": "NEWS25",
      "coupon": "launch_discount",
      "metadata": { "source": "newsletter" }
    },
    {
      "id": "launch_partner",
      "code": "PARTNER25",
      "coupon": "launch_discount",
      "metadata": { "source": "partner_referral" }
    }
  ]
}
```

## Complete Example [#complete-example]

```json title="omnibase/stripe/promotions.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "coupons": [
    {
      "id": "welcome_50",
      "name": "Welcome Discount",
      "percent_off": 50,
      "duration": "once"
    },
    {
      "id": "annual_20",
      "name": "Annual Plan Discount",
      "percent_off": 20,
      "duration": "forever",
      "applies_to": ["pro", "team"]
    },
    {
      "id": "startup_program",
      "name": "Startup Program",
      "percent_off": 50,
      "duration": "repeating",
      "duration_in_months": 12,
      "max_redemptions": 200
    },
    {
      "id": "black_friday",
      "name": "Black Friday 2024",
      "amount_off": 5000,
      "currency": "usd",
      "duration": "once",
      "redeem_by": "2024-12-02T00:00:00Z"
    }
  ],
  "promotion_codes": [
    {
      "id": "welcome",
      "code": "WELCOME50",
      "coupon": "welcome_50",
      "first_time_transaction": true
    },
    {
      "id": "annual_discount",
      "code": "ANNUAL20",
      "coupon": "annual_20"
    },
    {
      "id": "startup_apply",
      "code": "STARTUP2024",
      "coupon": "startup_program",
      "max_redemptions": 200
    },
    {
      "id": "bf24_twitter",
      "code": "BF24TWITTER",
      "coupon": "black_friday",
      "metadata": { "source": "twitter" }
    },
    {
      "id": "bf24_email",
      "code": "BF24EMAIL",
      "coupon": "black_friday",
      "metadata": { "source": "email" }
    }
  ],
  "products": []
}
```

## Using Promotion Codes [#using-promotion-codes]

### At Checkout [#at-checkout]

Enable promotion codes in checkout:

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

// Allow customers to enter any promotion code
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    allowPromotionCodes: true,
  },
});
```

### Pre-Applied Code [#pre-applied-code]

Apply a specific promotion code automatically:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    promotionCode: 'WELCOME50',
  },
});
```

<Component type="warn">
You cannot use both `allowPromotionCodes` and `promotionCode` at the same time.
</Component>

## Management [#management]

### Deactivating Promotion Codes [#deactivating-promotion-codes]

To deactivate a promotion code, set `active: false`:

```json
{
  "id": "expired_promo",
  "code": "OLDCODE",
  "coupon": "old_discount",
  "active": false
}
```

### Updating Coupons [#updating-coupons]

<Component type="warn">
Some coupon fields cannot be updated after creation. Omnibase may need to create a new coupon with a new Stripe ID.
</Component>

Fields that can be updated:
- `name`
- `metadata`

Fields that require coupon recreation:
- `percent_off` / `amount_off`
- `duration`
- `duration_in_months`
- `max_redemptions`
- `redeem_by`
- `applies_to`

## Best Practices [#best-practices]

1. **Use Descriptive Codes** — Choose codes that are easy to remember and type: `WELCOME50` not `WLC5020240101`

2. **Track Sources** — Use metadata to track where customers found the code:
   ```json
   { "metadata": { "source": "partner_xyz", "campaign": "q4_2024" } }
   ```

3. **Set Limits** — Always set `max_redemptions` and/or `expires_at` for promotional campaigns

4. **Test First** — Create test coupons in your staging environment before production

5. **Monitor Usage** — Track redemption counts through Stripe Dashboard or API

## Related [#related]

- [Checkout & Portal](/guides/stripe/checkout-portal) — Using promotion codes at checkout
- [Configuration Guide](/guides/stripe/configuration) — Full configuration reference
- [Testing](/guides/stripe/testing) — Testing promotion code flows

# Enterprise Pricing (/guides/stripe/enterprise-pricing)

Omnibase supports enterprise pricing through two mechanisms: template-based pricing for discount tiers, and custom per-tenant pricing for negotiated rates.

## Pricing Models [#pricing-models]

| Model | Use Case | Example |
|-------|----------|---------|
| **Template-Based** | Standard discount tiers | 10% off, 25% off, partner pricing |
| **Custom Per-Tenant** | Negotiated rates | Acme Corp gets $39/month instead of $49 |

## Template-Based Pricing [#template-based-pricing]

Templates allow you to define standard discount tiers that can be applied to multiple tenants.

### Configuration [#configuration]

Define enterprise template prices alongside regular prices:

```json
{
  "products": [
    {
      "id": "pro",
      "name": "Pro Plan",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "pro_monthly_tier1",
          "amount": 4410,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier1_10pct_off"
        },
        {
          "id": "pro_monthly_tier2",
          "amount": 3675,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier2_25pct_off"
        }
      ]
    }
  ]
}
```

| Field | Description |
|-------|-------------|
| `public: false` | Hides from public API |
| `enterprise_template` | Template identifier (e.g., `"tier1_10pct_off"`) |

### Applying Templates [#applying-templates]

Apply a template to a tenant's subscription:

```typescript
import { Configuration, V1StripeApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: { 'X-Service-Key': process.env.SERVICE_KEY },
});

const stripeApi = new V1StripeApi(config);

const { data } = await stripeApi.applyEnterpriseTemplate({
  applyEnterpriseTemplateRequest: {
    tenantId: 'tenant_123',
    enterpriseTemplate: 'tier1_10pct_off',
  },
});

console.log(`Prices swapped: ${data.pricesSwapped}`);
// pricesSwapped: 1
```

### What Happens [#what-happens]

1. Omnibase finds the tenant's active subscriptions
2. For each subscription item, finds a matching price with the same base ID and template
3. Swaps the subscription item to use the enterprise price
4. Updates the tenant's `enterprise_template` field
5. Returns the count of prices swapped

### Get Prices by Template [#get-prices-by-template]

List all prices for a specific template:

```typescript
const { data } = await stripeApi.getEnterpriseTemplatesPrices({
  template: 'tier1_10pct_off',
});

data.prices.forEach(price => {
  console.log(`${price.id}: $${price.amount / 100}`);
});
// pro_monthly_tier1: $44.10
// team_monthly_tier1: $134.10
```

## Custom Per-Tenant Pricing [#custom-per-tenant-pricing]

For fully custom pricing, create prices with `enterprise_id`:

### Configuration [#configuration-1]

```json
{
  "products": [
    {
      "id": "pro",
      "name": "Pro Plan",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "pro_monthly_acme",
          "amount": 3900,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_id": "acme_corp"
        },
        {
          "id": "pro_monthly_bigco",
          "amount": 2900,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_id": "bigco_inc"
        }
      ]
    }
  ]
}
```

### Applying Custom Pricing [#applying-custom-pricing]

```typescript
const { data } = await stripeApi.applyEnterpriseCustom({
  applyEnterpriseCustomRequest: {
    tenantId: 'tenant_456',
    enterpriseId: 'acme_corp',
  },
});

console.log(`Prices swapped: ${data.pricesSwapped}`);
```

### Get Prices by Enterprise ID [#get-prices-by-enterprise-id]

```typescript
const { data } = await stripeApi.getEnterpriseCustomPrices({
  enterpriseId: 'acme_corp',
});

data.prices.forEach(price => {
  console.log(`${price.id}: $${price.amount / 100}`);
});
// pro_monthly_acme: $39.00
```

## Tenant Fields [#tenant-fields]

After applying enterprise pricing, the tenant record is updated:

| Field | Description |
|-------|-------------|
| `enterprise_template` | Applied template (e.g., `"tier1_10pct_off"`) |
| `enterprise_id` | Custom enterprise ID (e.g., `"acme_corp"`) |

<Component type="info">
A tenant can have either `enterprise_template` OR `enterprise_id`, not both. Applying one clears the other.
</Component>

## Proration Behavior [#proration-behavior]

When swapping enterprise prices, Omnibase uses `proration_behavior: "none"`:

- No immediate charge or credit
- New price takes effect at next billing cycle
- Customer continues on current price until renewal

This prevents unexpected charges when applying enterprise discounts.

## API Endpoints [#api-endpoints]

### Templates [#templates]

```bash
# Get prices by template
GET /api/v1/stripe/admin/enterprise/prices/by-template/{template}
X-Service-Key: your-service-key

# Apply template to tenant
POST /api/v1/stripe/admin/enterprise/apply-template
X-Service-Key: your-service-key
Content-Type: application/json

{
  "tenant_id": "tenant_123",
  "enterprise_template": "tier1_10pct_off"
}
```

### Custom Pricing [#custom-pricing]

```bash
# Get prices by enterprise ID
GET /api/v1/stripe/admin/enterprise/prices/by-id/{enterprise_id}
X-Service-Key: your-service-key

# Apply custom pricing to tenant
POST /api/v1/stripe/admin/enterprise/apply-custom
X-Service-Key: your-service-key
Content-Type: application/json

{
  "tenant_id": "tenant_456",
  "enterprise_id": "acme_corp"
}
```

## Complete Example [#complete-example]

```json title="omnibase/stripe/enterprise.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "products": [
    {
      "id": "pro",
      "name": "Pro Plan",
      "type": "service",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true,
          "ui": {
            "display_name": "Monthly",
            "billing_period": "per month"
          }
        },
        {
          "id": "pro_yearly",
          "amount": 49000,
          "currency": "usd",
          "interval": "year",
          "public": true,
          "ui": {
            "display_name": "Annual",
            "billing_period": "per year",
            "price_display": {
              "suffix": " (Save 17%)"
            }
          }
        },
        {
          "id": "pro_monthly_tier1",
          "amount": 4410,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier1_10pct_off"
        },
        {
          "id": "pro_yearly_tier1",
          "amount": 44100,
          "currency": "usd",
          "interval": "year",
          "public": false,
          "enterprise_template": "tier1_10pct_off"
        },
        {
          "id": "pro_monthly_tier2",
          "amount": 3675,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier2_25pct_off"
        },
        {
          "id": "pro_yearly_tier2",
          "amount": 36750,
          "currency": "usd",
          "interval": "year",
          "public": false,
          "enterprise_template": "tier2_25pct_off"
        },
        {
          "id": "pro_monthly_acme",
          "amount": 3500,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_id": "acme_corp"
        },
        {
          "id": "pro_yearly_acme",
          "amount": 35000,
          "currency": "usd",
          "interval": "year",
          "public": false,
          "enterprise_id": "acme_corp"
        }
      ]
    },
    {
      "id": "team",
      "name": "Team Plan",
      "type": "service",
      "prices": [
        {
          "id": "team_monthly",
          "amount": 14900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "team_monthly_tier1",
          "amount": 13410,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier1_10pct_off"
        },
        {
          "id": "team_monthly_tier2",
          "amount": 11175,
          "currency": "usd",
          "interval": "month",
          "public": false,
          "enterprise_template": "tier2_25pct_off"
        }
      ]
    }
  ]
}
```

## Workflow [#workflow]

### Setting Up Enterprise Customer [#setting-up-enterprise-customer]

<Component>
<Component>
### Create Enterprise Prices [#create-enterprise-prices]

Add prices with `enterprise_template` or `enterprise_id` to your configuration:

```json
{
  "id": "pro_monthly_acme",
  "amount": 3500,
  "currency": "usd",
  "interval": "month",
  "public": false,
  "enterprise_id": "acme_corp"
}
```
</Component>

<Component>
### Push Configuration [#push-configuration]

```bash
omnibase stripe push
```
</Component>

<Component>
### Customer Signs Up [#customer-signs-up]

Customer subscribes through normal checkout at standard pricing.
</Component>

<Component>
### Apply Enterprise Pricing [#apply-enterprise-pricing]

After contract negotiation, apply the enterprise pricing:

```typescript
await stripeApi.applyEnterpriseCustom({
  applyEnterpriseCustomRequest: {
    tenantId: customer.tenantId,
    enterpriseId: 'acme_corp',
  },
});
```
</Component>

<Component>
### Verify [#verify]

The customer's subscription is now using the enterprise price. New price takes effect at next billing cycle.
</Component>
</Component>

## Best Practices [#best-practices]

1. **Naming Convention** — Use clear template names: `tier1_10pct_off`, `partner_pricing`, `startup_program`

2. **Match Base IDs** — Enterprise prices should match the pattern of base prices (e.g., `pro_monthly` → `pro_monthly_tier1`)

3. **Cover All Intervals** — If you have monthly and yearly prices, create enterprise versions of both

4. **Document Tiers** — Maintain a reference document mapping templates to discount percentages

5. **Audit Trail** — The tenant's `enterprise_template`/`enterprise_id` field provides an audit trail

## Related [#related]

- [Products & Prices](/guides/stripe/products-prices) — Price configuration
- [Subscriptions](/guides/stripe/subscriptions) — Subscription management
- [Configuration Guide](/guides/stripe/configuration) — Full configuration reference

# Stripe Integration Overview (/guides/stripe)

Omnibase provides a comprehensive "Stripe as Code" approach to billing configuration, enabling version control, rollbacks, audit trails, and enterprise-grade payment processing.

## Key Features [#key-features]

<Component>
<Component title="Configuration as Code" href="/docs/guides/stripe/configuration">
Version-controlled billing configuration with JSON/YAML
</Component>

<Component title="Products & Prices" href="/docs/guides/stripe/products-prices">
Define products with multiple pricing tiers and intervals
</Component>

<Component title="Coupons & Promotions" href="/docs/guides/stripe/coupons-promotions">
Create discount codes and promotional campaigns
</Component>

<Component title="Webhooks" href="/docs/guides/stripe/webhooks">
Configure webhook endpoints for event handling
</Component>

<Component title="Subscriptions" href="/docs/guides/stripe/subscriptions">
Manage recurring billing and subscription lifecycle
</Component>

<Component title="Usage-Based Billing" href="/docs/guides/stripe/metering">
Implement metered billing with billing meters
</Component>

<Component title="Checkout & Portal" href="/docs/guides/stripe/checkout-portal">
Integrate Stripe Checkout and Customer Portal
</Component>

<Component title="Invoices" href="/docs/guides/stripe/invoices">
Create and manage invoices programmatically
</Component>

<Component title="Enterprise Pricing" href="/docs/guides/stripe/enterprise-pricing">
Custom pricing templates for enterprise customers
</Component>

<Component title="UI Components" href="/docs/guides/stripe/ui-components">
Pre-built shadcn components for pricing tables and billing UI
</Component>
</Component>

## The Problem with Native Stripe [#the-problem-with-native-stripe]

Stripe's configuration presents several challenges for production systems:

| Challenge | Description |
|-----------|-------------|
| **Immutability** | Products and prices with payment history cannot be deleted |
| **No Version Control** | No built-in rollback or history tracking |
| **Environment Sync** | Difficult to sync configurations between dev/staging/prod |
| **Free Tiers** | Stripe doesn't natively support $0 prices |
| **Enterprise Pricing** | No built-in support for custom per-customer pricing |

## Omnibase Solution [#omnibase-solution]

Omnibase stores your Stripe configuration in PostgreSQL and syncs it to Stripe, providing:

- **Version Control** — Every configuration change is tracked with full history
- **Rollbacks** — Revert to any previous configuration instantly
- **Audit Trails** — Complete history of all billing changes with timestamps
- **Free Tiers** — Support $0 pricing stored locally (bypasses Stripe's limitation)
- **Config ID Mapping** — Human-readable IDs (`pro_monthly`) mapped to Stripe IDs (`price_1ABC...`)
- **Enterprise Pricing** — Template-based and custom per-tenant pricing

## Quick Start [#quick-start]

<Component>
<Component>
### Create Your Configuration [#create-your-configuration]

Create a configuration file in your project:

```json title="omnibase/stripe/subscriptions.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "products": [
    {
      "id": "starter",
      "name": "Starter Plan",
      "description": "Perfect for individuals",
      "type": "service",
      "prices": [
        {
          "id": "starter_monthly",
          "amount": 0,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "ui": {
            "display_name": "Free",
            "price_display": { "custom_text": "Free" }
          }
        }
      ]
    },
    {
      "id": "pro",
      "name": "Professional",
      "description": "For growing businesses",
      "type": "service",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "pro_yearly",
          "amount": 49000,
          "currency": "usd",
          "interval": "year",
          "public": true
        }
      ],
      "ui": {
        "highlighted": true,
        "badge": "Most Popular"
      }
    }
  ]
}
```
</Component>

<Component>
### Push to Stripe [#push-to-stripe]

Use the CLI to validate and push your configuration:

```bash
# Validate configuration without pushing
omnibase stripe validate

# Push configuration to Stripe
omnibase stripe push
```

This will:
1. Validate your configuration against the JSON schema
2. Create/update products and prices in Stripe
3. Store the configuration version in PostgreSQL
4. Generate config ID to Stripe ID mappings
</Component>

<Component>
### Use in Your Application [#use-in-your-application]

Fetch the configuration and create checkouts:

<Tabs items={["Next.js","React","Core API"]}>
<Tab value="Next.js">
```tsx title="app/(dashboard)/subscriptions/page.tsx"
import { V1StripeApi, V1PaymentsApi } from '@omnibase/core-js';

export default async function SubscriptionsPage() {
  const stripeApi = new V1StripeApi(config);
  const paymentsApi = new V1PaymentsApi(config);

  // Get available plans
  const { data: stripeConfig } = await stripeApi.getStripeConfig();

  async function checkout(priceId: string) {
    'use server';
    const { data } = await paymentsApi.createCheckout({
      createCheckoutRequest: {
        priceId,
        successUrl: `${process.env.APP_URL}/subscriptions?success=true`,
        cancelUrl: `${process.env.APP_URL}/subscriptions`,
        trialPeriodDays: 14,
        allowPromotionCodes: true,
      },
    });
    redirect(data.url);
  }

  return <PricingTable products={stripeConfig.products} onSelect={checkout} />;
}
```
</Tab>

<Tab value="React">
```tsx title="components/Pricing.tsx"
import { useEffect, useState } from 'react';
import { V1StripeApi, V1PaymentsApi, Product } from '@omnibase/core-js';

export function Pricing() {
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    const stripeApi = new V1StripeApi(config);
    stripeApi.getStripeConfig().then(({ data }) => {
      setProducts(data.products);
    });
  }, []);

  const handleCheckout = async (priceId: string) => {
    const paymentsApi = new V1PaymentsApi(config);
    const { data } = await paymentsApi.createCheckout({
      createCheckoutRequest: {
        priceId,
        successUrl: `${window.location.origin}/success`,
        cancelUrl: window.location.href,
      },
    });
    window.location.href = data.url;
  };

  return <PricingTable products={products} onSelect={handleCheckout} />;
}
```
</Tab>

<Tab value="Core API">
```typescript title="server/checkout.ts"
import { Configuration, V1StripeApi, V1PaymentsApi } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: { Cookie: cookieHeader },
});

// Get configuration
const stripeApi = new V1StripeApi(config);
const { data: stripeConfig } = await stripeApi.getStripeConfig();

// Create checkout session
const paymentsApi = new V1PaymentsApi(config);
const { data: checkout } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
  },
});

console.log('Checkout URL:', checkout.url);
```
</Tab>
</Tabs>
</Component>
</Component>

## Architecture Overview [#architecture-overview]

```
┌─────────────────┐     ┌──────────────────┐     ┌─────────────┐
│  Config Files   │────▶│  Omnibase API    │────▶│   Stripe    │
│  (JSON/YAML)    │     │  (PostgreSQL)    │     │   (Live)    │
└─────────────────┘     └──────────────────┘     └─────────────┘
        │                       │                       │
        │                       ▼                       │
        │               ┌──────────────────┐            │
        │               │  ID Mappings     │            │
        │               │  config_id ↔     │◀───────────┘
        │               │  stripe_id       │
        │               └──────────────────┘
        │                       │
        ▼                       ▼
┌─────────────────┐     ┌──────────────────┐
│  Version        │     │  Change          │
│  History        │     │  Detection       │
└─────────────────┘     └──────────────────┘
```

**Key Components:**

1. **Configuration Files** — JSON files defining products, prices, meters, webhooks, coupons
2. **PostgreSQL Storage** — Versioned configuration with full history
3. **ID Mapping** — Bi-directional mapping between config IDs and Stripe IDs
4. **Stripe Sync** — Intelligent diffing and synchronization to Stripe API

## Configuration File Structure [#configuration-file-structure]

Omnibase supports multiple configuration files for better organization:

<Files>
<Folder name="omnibase" defaultOpen>
<Folder name="stripe" defaultOpen>
<File name="webhook.config.json" />

<File name="subscriptions.config.json" />

<File name="usage-billing.config.json" />

<File name="enterprise.config.json" />
</Folder>
</Folder>
</Files>

Each file follows the same schema with optional sections:

```json
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "webhooks": [],      // Optional: Webhook endpoints
  "meters": [],        // Optional: Billing meters for metered pricing
  "products": [],      // Required: At least one product
  "coupons": [],       // Optional: Discount coupons
  "promotion_codes": [] // Optional: Promotion codes for coupons
}
```

## Supported Currencies [#supported-currencies]

Omnibase supports 20 currencies:

| Currency | Code | Currency | Code |
|----------|------|----------|------|
| US Dollar | `usd` | Euro | `eur` |
| British Pound | `gbp` | Canadian Dollar | `cad` |
| Australian Dollar | `aud` | Japanese Yen | `jpy` |
| Indian Rupee | `inr` | Brazilian Real | `brl` |
| Mexican Peso | `mxn` | Singapore Dollar | `sgd` |
| Hong Kong Dollar | `hkd` | New Zealand Dollar | `nzd` |
| Swiss Franc | `chf` | Swedish Krona | `sek` |
| Danish Krone | `dkk` | Norwegian Krone | `nok` |
| Polish Zloty | `pln` | Czech Koruna | `czk` |
| Israeli Shekel | `ils` | South African Rand | `zar` |

## CLI Commands [#cli-commands]

| Command | Description |
|---------|-------------|
| `omnibase stripe push` | Push local configuration to Stripe |
| `omnibase stripe pull` | Pull configuration from Stripe account |
| `omnibase stripe validate` | Validate configuration without pushing |
| `omnibase stripe history` | View configuration version history |
| `omnibase stripe webhook secret` | Retrieve webhook signing secrets |

## API Endpoints [#api-endpoints]

### Public Endpoints (No Auth Required) [#public-endpoints-no-auth-required]

| Endpoint | Description |
|----------|-------------|
| `GET /api/v1/stripe/schema` | Get JSON schema for configuration |
| `GET /api/v1/stripe/config` | Get public configuration (filtered) |
| `GET /api/v1/stripe/config/prices/:id` | Get price by config ID |
| `GET /api/v1/stripe/config/products/:id` | Get product by config ID |
| `GET /api/v1/stripe/config/meters/:id` | Get meter by config ID |
| `POST /api/v1/stripe/config/prices/:id/calculate` | Calculate cost for quantity |

### Admin Endpoints (Service Key Required) [#admin-endpoints-service-key-required]

| Endpoint | Description |
|----------|-------------|
| `GET /api/v1/stripe/admin/config` | Get full configuration (unfiltered) |
| `POST /api/v1/stripe/admin/config` | Update configuration |
| `GET /api/v1/stripe/admin/config/history` | Get configuration history |
| `GET /api/v1/stripe/admin/config/pull` | Pull from Stripe |
| `POST /api/v1/stripe/admin/config/validate` | Validate configuration |
| `POST /api/v1/stripe/admin/config/reset` | Reset/archive all resources |
| `GET /api/v1/stripe/admin/webhooks` | List webhooks with secrets |

## What's Next? [#whats-next]

<Component>
<Component title="Configuration Guide" href="/docs/guides/stripe/configuration">
Deep dive into the configuration schema and options
</Component>

<Component title="Products & Prices" href="/docs/guides/stripe/products-prices">
Learn about product types, pricing models, and UI configuration
</Component>

<Component title="Webhooks" href="/docs/guides/stripe/webhooks">
Set up webhook endpoints for billing events
</Component>

<Component title="Subscriptions" href="/docs/guides/stripe/subscriptions">
Implement subscription management in your app
</Component>
</Component>

# Invoices (/guides/stripe/invoices)

Omnibase provides a complete invoice management API for creating custom invoices, adding line items, and handling invoice lifecycle events.

## Invoice Lifecycle [#invoice-lifecycle]

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│    Draft    │────▶│  Finalized  │────▶│    Open     │────▶│    Paid     │
│             │     │             │     │             │     │             │
└─────────────┘     └─────────────┘     └─────────────┘     └─────────────┘
       │                                       │                    │
       │                                       ▼                    │
       │                               ┌─────────────┐              │
       └───────────────────────────────│    Void     │◀─────────────┘
                                       └─────────────┘
```

| Status | Description |
|--------|-------------|
| `draft` | Invoice can be edited, line items added |
| `open` | Invoice sent to customer, awaiting payment |
| `paid` | Payment received |
| `void` | Invoice canceled |
| `uncollectible` | Payment failed, marked as bad debt |

## Creating Invoices [#creating-invoices]

### Create Draft Invoice [#create-draft-invoice]

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

const { data: invoice } = await paymentsApi.createInvoice({
  createInvoiceRequest: {
    currency: 'usd',
    autoAdvance: false, // Keep as draft
    description: 'January 2024 Usage',
    metadata: {
      billing_period: '2024-01',
      tenant_id: 'tenant_123',
    },
  },
});

console.log(invoice.id);     // "in_xxx..."
console.log(invoice.status); // "draft"
```

### Invoice Options [#invoice-options]

| Option | Type | Description |
|--------|------|-------------|
| `currency` | `string` | Invoice currency (e.g., `"usd"`) |
| `autoAdvance` | `boolean` | Auto-finalize and send when created |
| `description` | `string` | Invoice description |
| `metadata` | `object` | Custom key-value metadata |

## Adding Line Items [#adding-line-items]

### By Amount [#by-amount]

Add a custom amount line item:

```typescript
await paymentsApi.addInvoiceLineItem({
  invoiceId: invoice.id,
  addInvoiceLineItemRequest: {
    amount: 5000, // $50.00 in cents
    currency: 'usd',
    description: 'Consulting Services - 2 hours',
  },
});
```

### By Price ID and Quantity [#by-price-id-and-quantity]

Add a line item using a configured price:

```typescript
await paymentsApi.addInvoiceLineItemWithPriceId({
  invoiceId: invoice.id,
  addInvoiceLineItemWithPriceIDRequest: {
    priceId: 'compute_hourly', // Config price ID
    quantity: 730,             // 730 hours
    currency: 'usd',
    description: 'Compute - VKS Starter (730 hours)',
    metadata: {
      project_id: 'proj_123',
    },
  },
});
```

<Component type="info">
When using `priceId`, Omnibase automatically converts your config price ID to the Stripe price ID.
</Component>

## Updating Invoices [#updating-invoices]

Update draft invoices before finalizing:

```typescript
await paymentsApi.updateInvoice({
  invoiceId: invoice.id,
  updateInvoiceRequest: {
    description: 'Updated: January 2024 Usage',
    metadata: {
      updated_at: new Date().toISOString(),
    },
  },
});
```

<Component type="warn">
Only draft invoices can be updated. Attempting to update a finalized invoice returns a 400 error.
</Component>

## Finalizing Invoices [#finalizing-invoices]

Finalize to send the invoice to the customer:

```typescript
const { data: finalizedInvoice } = await paymentsApi.finalizeInvoice({
  invoiceId: invoice.id,
  finalizeInvoiceRequest: {
    autoAdvance: true, // Send immediately
  },
});

console.log(finalizedInvoice.status);          // "open"
console.log(finalizedInvoice.hostedInvoiceUrl); // Stripe-hosted invoice page
console.log(finalizedInvoice.invoicePdf);       // PDF download URL
```

### Auto-Advance Behavior [#auto-advance-behavior]

| autoAdvance | Behavior |
|-------------|----------|
| `true` | Invoice is sent immediately, payment attempted if auto-charge enabled |
| `false` | Invoice is finalized but not sent; manual sending required |

## Getting Invoices [#getting-invoices]

```typescript
const { data: invoice } = await paymentsApi.getInvoice({
  invoiceId: 'in_xxx',
});

console.log(invoice.amountDue);      // Amount due in cents
console.log(invoice.amountPaid);     // Amount paid in cents
console.log(invoice.lineItems);      // Array of line items
console.log(invoice.hostedInvoiceUrl); // Customer invoice URL
```

## Usage-Based Invoice Processing [#usage-based-invoice-processing]

For usage-based billing, process `invoice.created` webhooks to add line items:

### Webhook Handler [#webhook-handler]

```go title="internal/handlers/stripe_event_handler.go"
func (h *StripeEventHandler) handleInvoiceCreated(
    ctx context.Context,
    event stripe.Event,
) error {
    var invoice stripe.Invoice
    json.Unmarshal(event.Data.Raw, &invoice)

    // Skip if not a subscription invoice
    if invoice.Subscription == nil {
        return nil
    }

    billingStart := time.Unix(invoice.PeriodStart, 0)
    billingEnd := time.Unix(invoice.PeriodEnd, 0)

    // Look up tenant by Stripe customer ID
    tenant, err := h.getTenantByCustomerID(invoice.Customer.ID)
    if err != nil {
        return err
    }

    // Get all projects for this tenant
    projects, _ := h.getProjectsForTenant(tenant.ID)

    // Calculate usage for each project
    var allLineItems []UsageLineItem
    for _, project := range projects {
        items, _ := h.usageCalculator.CalculateProjectUsage(
            ctx, &project, billingStart, billingEnd,
        )
        allLineItems = append(allLineItems, items...)
    }

    // Aggregate line items by price ID
    aggregated := aggregateLineItems(allLineItems)

    // Add aggregated line items to invoice
    for _, item := range aggregated {
        _, _, err := h.omnibaseClient.V1PaymentsAPI.
            AddInvoiceLineItemWithPriceId(ctx, invoice.ID).
            XServiceKey(h.serviceKey).
            XTenantId(tenant.ID).
            AddInvoiceLineItemWithPriceIDRequest(omnibase.AddInvoiceLineItemWithPriceIDRequest{
                AddInvoiceLineItemWithConfigPriceRequest: &omnibase.AddInvoiceLineItemWithConfigPriceRequest{
                    Quantity:    item.Quantity,
                    PriceId:     item.PriceID,
                    Description: item.Description,
                    Currency:    omnibase.USD,
                    Metadata:    item.Metadata,
                },
            }).
            Execute()

        if err != nil {
            logger.Logger.Error("Failed to add line item",
                "invoice_id", invoice.ID,
                "price_id", item.PriceID,
                "error", err)
        }
    }

    return nil
}
```

### Line Item Aggregation [#line-item-aggregation]

```go
type aggregatedItem struct {
    item         UsageLineItem
    projectCount int
}

func aggregateLineItems(items []UsageLineItem) []UsageLineItem {
    grouped := make(map[string]*aggregatedItem)

    for _, item := range items {
        if existing, ok := grouped[item.PriceID]; ok {
            // Sum quantities for same price
            existing.item.Quantity += item.Quantity
            existing.projectCount++
        } else {
            grouped[item.PriceID] = &aggregatedItem{
                item:         item,
                projectCount: 1,
            }
        }
    }

    result := make([]UsageLineItem, 0, len(grouped))
    for _, agg := range grouped {
        item := agg.item
        if agg.projectCount > 1 {
            item.Description = fmt.Sprintf(
                "%s (aggregated from %d projects)",
                item.Description, agg.projectCount,
            )
            item.Metadata["project_count"] = fmt.Sprintf("%d", agg.projectCount)
        }
        result = append(result, item)
    }

    return result
}
```

## Webhook Events [#webhook-events]

Subscribe to invoice events:

```json
{
  "webhooks": [
    {
      "id": "invoice_events",
      "url": "${WEBHOOK_URL}/api/stripe/invoices",
      "events": [
        "invoice.created",
        "invoice.finalized",
        "invoice.paid",
        "invoice.payment_failed",
        "invoice.payment_action_required",
        "invoice.upcoming",
        "invoice.marked_uncollectible",
        "invoice.voided"
      ]
    }
  ]
}
```

### Event Handling [#event-handling]

```typescript
switch (event.type) {
  case 'invoice.created':
    // Add usage-based line items (see above)
    await addUsageLineItems(event.data.object);
    break;

  case 'invoice.paid':
    // Payment successful
    const paidInvoice = event.data.object;
    await recordPayment(paidInvoice.customer, paidInvoice.amount_paid);
    break;

  case 'invoice.payment_failed':
    // Payment failed
    const failedInvoice = event.data.object;
    await notifyPaymentFailed(failedInvoice.customer);
    break;

  case 'invoice.upcoming':
    // Invoice will be created soon (useful for previews)
    await sendUpcomingInvoiceNotification(event.data.object);
    break;
}
```

## Complete Example [#complete-example]

### TypeScript SDK [#typescript-sdk]

```typescript
import { V1PaymentsApi, Configuration } from '@omnibase/core-js';

const config = new Configuration({
  basePath: process.env.OMNIBASE_API_URL,
  headers: {
    'X-Service-Key': process.env.SERVICE_KEY,
    'X-Tenant-Id': tenantId,
  },
});

const paymentsApi = new V1PaymentsApi(config);

// 1. Create draft invoice
const { data: invoice } = await paymentsApi.createInvoice({
  createInvoiceRequest: {
    currency: 'usd',
    autoAdvance: false,
    description: 'January 2024 Infrastructure Usage',
  },
});

// 2. Add compute line item
await paymentsApi.addInvoiceLineItemWithPriceId({
  invoiceId: invoice.id,
  addInvoiceLineItemWithPriceIDRequest: {
    priceId: 'vks_starter_hourly',
    quantity: 730,
    currency: 'usd',
    description: 'Compute - VKS Starter (730 hours)',
  },
});

// 3. Add database line item
await paymentsApi.addInvoiceLineItemWithPriceId({
  invoiceId: invoice.id,
  addInvoiceLineItemWithPriceIDRequest: {
    priceId: 'neon_compute_hour',
    quantity: 150,
    currency: 'usd',
    description: 'Database - Neon Compute (150 hours)',
  },
});

// 4. Add storage line item
await paymentsApi.addInvoiceLineItemWithPriceId({
  invoiceId: invoice.id,
  addInvoiceLineItemWithPriceIDRequest: {
    priceId: 'cloudflare_r2_storage',
    quantity: 50,
    currency: 'usd',
    description: 'Storage - Cloudflare R2 (50 GB)',
  },
});

// 5. Finalize and send
const { data: finalInvoice } = await paymentsApi.finalizeInvoice({
  invoiceId: invoice.id,
  finalizeInvoiceRequest: {
    autoAdvance: true,
  },
});

console.log('Invoice sent:', finalInvoice.hostedInvoiceUrl);
```

### Go SDK [#go-sdk]

```go
import (
    "context"
    omnibase "github.com/omnibase/sdk-go"
)

client := omnibase.NewAPIClient(omnibase.NewConfiguration())

// Create invoice
invoice, _, _ := client.V1PaymentsAPI.CreateInvoice(ctx).
    XServiceKey(serviceKey).
    XTenantId(tenantID).
    CreateInvoiceRequest(omnibase.CreateInvoiceRequest{
        Currency:    omnibase.USD,
        AutoAdvance: omnibase.PtrBool(false),
        Description: omnibase.PtrString("January 2024 Usage"),
    }).
    Execute()

// Add line items
for _, item := range usageLineItems {
    _, _, _ = client.V1PaymentsAPI.AddInvoiceLineItemWithPriceId(ctx, invoice.Id).
        XServiceKey(serviceKey).
        XTenantId(tenantID).
        AddInvoiceLineItemWithPriceIDRequest(omnibase.AddInvoiceLineItemWithPriceIDRequest{
            AddInvoiceLineItemWithConfigPriceRequest: &omnibase.AddInvoiceLineItemWithConfigPriceRequest{
                PriceId:     item.PriceID,
                Quantity:    item.Quantity,
                Currency:    omnibase.USD,
                Description: item.Description,
            },
        }).
        Execute()
}

// Finalize
finalInvoice, _, _ := client.V1PaymentsAPI.FinalizeInvoice(ctx, invoice.Id).
    XServiceKey(serviceKey).
    FinalizeInvoiceRequest(omnibase.FinalizeInvoiceRequest{
        AutoAdvance: omnibase.PtrBool(true),
    }).
    Execute()
```

## Best Practices [#best-practices]

1. **Idempotency** — Use metadata to track processed invoices and prevent duplicates

2. **Error Handling** — Log failed line item additions; don't fail the entire invoice

3. **Aggregation** — Aggregate similar line items to keep invoices readable

4. **Descriptions** — Use clear descriptions customers can understand

5. **Metadata** — Include billing period and project references for auditing

6. **Testing** — Test invoice flows in Stripe test mode before production

## Related [#related]

- [Metering](/guides/stripe/metering) — Usage-based billing
- [Webhooks](/guides/stripe/webhooks) — Invoice event handling
- [Subscriptions](/guides/stripe/subscriptions) — Subscription-generated invoices

# Usage-Based Billing (/guides/stripe/metering)

Omnibase supports usage-based (metered) billing for scenarios where you charge based on consumption rather than a flat fee. This is ideal for API calls, compute time, storage, and similar metrics.

## Billing Meters [#billing-meters]

Billing meters track usage events and aggregate them for billing. Define meters in your configuration:

```json
{
  "meters": [
    {
      "id": "api_calls",
      "display_name": "API Calls",
      "event_name": "api_call",
      "default_aggregation": {
        "formula": "sum"
      },
      "customer_mapping": {
        "event_payload_key": "customer_id",
        "type": "by_id"
      },
      "value_settings": {
        "event_payload_key": "value"
      }
    }
  ]
}
```

### Meter Configuration [#meter-configuration]

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique meter identifier |
| `display_name` | `string` | Yes | Human-readable name |
| `event_name` | `string` | Yes | Event name to track |
| `stripe_id` | `string` | No | Existing Stripe meter ID (migration) |
| `default_aggregation` | `object` | Yes | How to aggregate events |
| `customer_mapping` | `object` | No | How to identify customers |
| `value_settings` | `object` | No | How to extract values |

### Aggregation Formulas [#aggregation-formulas]

| Formula | Description | Use Case |
|---------|-------------|----------|
| `sum` | Sum all values | API calls, data transfer |
| `count` | Count events | Requests, transactions |
| `last` | Use last value | Current storage size |

## Metered Prices [#metered-prices]

Link a price to a meter for usage-based billing:

```json
{
  "products": [
    {
      "id": "api_usage",
      "name": "API Usage",
      "type": "service",
      "prices": [
        {
          "id": "api_per_call",
          "currency": "usd",
          "interval": "month",
          "usage_type": "metered",
          "meter": "api_calls",
          "billing_scheme": "per_unit",
          "amount": 1
        }
      ]
    }
  ]
}
```

### Per-Unit Metered Pricing [#per-unit-metered-pricing]

Charge a fixed amount per unit:

```json
{
  "id": "compute_hours",
  "currency": "usd",
  "interval": "month",
  "usage_type": "metered",
  "meter": "compute_time",
  "billing_scheme": "per_unit",
  "amount": 10
}
```

This charges $0.10 per unit of compute time.

### Tiered Metered Pricing [#tiered-metered-pricing]

For volume discounts, use tiered pricing:

```json
{
  "id": "api_tiered",
  "currency": "usd",
  "interval": "month",
  "usage_type": "metered",
  "meter": "api_calls",
  "billing_scheme": "tiered",
  "tiers_mode": "graduated",
  "tiers": [
    { "up_to": 1000, "unit_amount": 0 },
    { "up_to": 10000, "unit_amount": 100 },
    { "up_to": 100000, "unit_amount": 50 },
    { "up_to": "inf", "unit_amount": 25 }
  ]
}
```

This creates a pricing structure:
- First 1,000 calls: Free
- 1,001 - 10,000: $0.01 per call
- 10,001 - 100,000: $0.005 per call
- 100,000+: $0.0025 per call

## Recording Usage [#recording-usage]

### Via API [#via-api]

```typescript
import { V1PaymentsApi } from '@omnibase/core-js';

const paymentsApi = new V1PaymentsApi(config);

// Record 100 API calls
await paymentsApi.recordUsage({
  recordUsageRequest: {
    meterEventName: 'api_call',
    value: '100',
  },
});
```

### Via Go SDK [#via-go-sdk]

```go
import (
    "context"
    omnibase "github.com/omnibase/sdk-go"
)

client := omnibase.NewClient(os.Getenv("OMNIBASE_API_URL"))

err := client.V1PaymentsAPI.RecordUsage(ctx).
    XServiceKey(serviceKey).
    XTenantId(tenantID).
    RecordUsageRequest(omnibase.RecordUsageRequest{
        MeterEventName: "api_call",
        Value:          "100",
    }).
    Execute()
```

### Batch Recording [#batch-recording]

For high-volume scenarios, batch usage events:

```typescript
// Record usage in batches (e.g., every minute)
async function recordBatchedUsage() {
  const usage = getUsageFromBuffer(); // Your buffered usage data

  await paymentsApi.recordUsage({
    recordUsageRequest: {
      meterEventName: 'api_call',
      value: String(usage.count),
    },
  });
}

// Run every minute
setInterval(recordBatchedUsage, 60000);
```

## Usage Calculation Service [#usage-calculation-service]

For complex usage scenarios (like managed hosting), Omnibase provides a usage calculation service:

### Project Usage Calculation [#project-usage-calculation]

```go
type UsageLineItem struct {
    PriceID     string            // Config price ID
    Quantity    int64             // Quantity of units
    Description string            // Human-readable description
    ProjectID   string            // Project reference
    Metadata    map[string]string // Additional metadata
}

func (u *UsageCalculator) CalculateProjectUsage(
    ctx context.Context,
    project *models.Project,
    billingStart, billingEnd time.Time,
) ([]UsageLineItem, error) {
    var lineItems []UsageLineItem

    // Calculate compute usage
    if project.ComputeDeploymentID != nil {
        items, _ := u.calculateComputeUsage(ctx, project, billingStart, billingEnd)
        lineItems = append(lineItems, items...)
    }

    // Calculate storage usage
    if project.StorageDeploymentID != nil {
        items, _ := u.calculateStorageUsage(ctx, project, billingStart, billingEnd)
        lineItems = append(lineItems, items...)
    }

    // Calculate database usage
    if project.DatabaseDeploymentID != nil {
        items, _ := u.calculateDatabaseUsage(ctx, project, billingStart, billingEnd)
        lineItems = append(lineItems, items...)
    }

    return lineItems, nil
}
```

### Usage Categories [#usage-categories]

| Category | Metrics | Unit |
|----------|---------|------|
| **Compute** | VPS hours, Cloud Run vCPU-seconds | Hours, vCPU-seconds |
| **Storage** | GB stored, operations (Class A/B) | GB-month, operations |
| **Database** | Compute hours, storage GB | Hours, GB-hours |
| **Email** | Emails sent | Count |
| **Workers** | Requests, CPU milliseconds | Millions |

### Billing Period Normalization [#billing-period-normalization]

For VPS billing, Omnibase normalizes to 730 hours/month:

```go
const StandardMonthHours = 730 // 365 * 24 / 12

// If project ran full billing period, cap at standard hours
if ranFullBillingPeriod {
    billableHours = StandardMonthHours
}
```

## Displaying Usage [#displaying-usage]

### Usage Preview API [#usage-preview-api]

```typescript
// Get usage preview for a billing period
const response = await fetch(
  `/api/projects/${projectId}/usage?start=${startDate}&end=${endDate}`
);

const usage = await response.json();
// {
//   project_id: "...",
//   billing_start: "2024-01-01T00:00:00Z",
//   billing_end: "2024-02-01T00:00:00Z",
//   line_items: [...],
//   item_count: 5
// }
```

### Usage Chart Component [#usage-chart-component]

```tsx title="components/UsageChart.tsx"
import { V1StripeApi } from '@omnibase/core-js';

const CATEGORY_MAP = {
  compute: ['vks_', 'gcp_cloudrun_'],
  storage: ['cloudflare_r2_'],
  database: ['neon_'],
  email: ['ses_email'],
  workers: ['cloudflare_workers_'],
};

function categorizeLineItem(priceId: string): string {
  for (const [category, prefixes] of Object.entries(CATEGORY_MAP)) {
    if (prefixes.some(p => priceId.startsWith(p))) {
      return category;
    }
  }
  return 'other';
}

function formatQuantity(priceId: string, quantity: number): string {
  if (priceId.includes('hourly')) return `${quantity} hrs`;
  if (priceId.includes('gb_month')) return `${quantity} GB`;
  if (priceId.includes('requests')) return `${(quantity / 1_000_000).toFixed(2)}M reqs`;
  return String(quantity);
}

export function UsageChart({ lineItems }) {
  const stripeApi = new V1StripeApi(config);

  const itemsWithPrices = await Promise.all(
    lineItems.map(async (item) => {
      const { data } = await stripeApi.getPriceByID({ priceId: item.PriceID });
      return {
        ...item,
        price: data.price,
        category: categorizeLineItem(item.PriceID),
        cost: calculateCost(item.PriceID, data.price.amount, item.Quantity),
      };
    })
  );

  const totalCost = itemsWithPrices.reduce((sum, item) => sum + item.cost, 0);

  return (
    <table>
      <thead>
        <tr>
          <th>Category</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Cost</th>
        </tr>
      </thead>
      <tbody>
        {itemsWithPrices.map((item) => (
          <tr key={item.PriceID}>
            <td>{item.category}</td>
            <td>{item.Description}</td>
            <td>{formatQuantity(item.PriceID, item.Quantity)}</td>
            <td>${(item.cost / 100).toFixed(2)}</td>
          </tr>
        ))}
      </tbody>
      <tfoot>
        <tr>
          <td colSpan={3}>Estimated Total</td>
          <td>${(totalCost / 100).toFixed(2)}</td>
        </tr>
      </tfoot>
    </table>
  );
}
```

## Cost Calculation API [#cost-calculation-api]

Calculate costs for any quantity:

```typescript
const { data } = await stripeApi.calculatePriceCost({
  priceId: 'api_tiered',
  calculatePriceCostRequest: { quantity: 50000 },
});

console.log(data.cost_cents);              // Total cost in cents
console.log(data.effective_unit_cost_cents); // Average cost per unit
console.log(data.billing_scheme);          // "tiered"
console.log(data.tiers_mode);              // "graduated"
```

## Invoice Integration [#invoice-integration]

For `invoice.created` webhooks, calculate and add usage line items:

```go
func (h *StripeEventHandler) handleInvoiceCreated(
    ctx context.Context,
    event stripe.Event,
) error {
    var invoice stripe.Invoice
    json.Unmarshal(event.Data.Raw, &invoice)

    billingStart := time.Unix(invoice.PeriodStart, 0)
    billingEnd := time.Unix(invoice.PeriodEnd, 0)

    // Get all projects for tenant
    projects := getProjectsForCustomer(invoice.Customer.ID)

    // Calculate usage for each project
    var allLineItems []UsageLineItem
    for _, project := range projects {
        items, _ := h.usageCalculator.CalculateProjectUsage(
            ctx, &project, billingStart, billingEnd,
        )
        allLineItems = append(allLineItems, items...)
    }

    // Aggregate by price ID
    aggregated := aggregateLineItems(allLineItems)

    // Add to invoice
    for _, item := range aggregated {
        h.addInvoiceLineItem(ctx, invoice.ID, item)
    }

    return nil
}
```

## Complete Example [#complete-example]

```json title="omnibase/stripe/usage-billing.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "meters": [
    {
      "id": "api_calls",
      "display_name": "API Calls",
      "event_name": "api_call",
      "default_aggregation": { "formula": "sum" }
    },
    {
      "id": "storage_gb",
      "display_name": "Storage (GB)",
      "event_name": "storage_usage",
      "default_aggregation": { "formula": "last" }
    }
  ],
  "products": [
    {
      "id": "usage_plan",
      "name": "Usage-Based Plan",
      "type": "service",
      "prices": [
        {
          "id": "base_monthly",
          "amount": 999,
          "currency": "usd",
          "interval": "month",
          "usage_type": "licensed",
          "ui": {
            "display_name": "Base Fee"
          }
        },
        {
          "id": "api_usage",
          "currency": "usd",
          "interval": "month",
          "usage_type": "metered",
          "meter": "api_calls",
          "billing_scheme": "tiered",
          "tiers_mode": "graduated",
          "tiers": [
            { "up_to": 10000, "unit_amount": 0 },
            { "up_to": 100000, "unit_amount": 10 },
            { "up_to": "inf", "unit_amount": 5 }
          ],
          "ui": {
            "display_name": "API Calls",
            "billing_period": "per 1,000 calls"
          }
        },
        {
          "id": "storage_usage",
          "currency": "usd",
          "interval": "month",
          "usage_type": "metered",
          "meter": "storage_gb",
          "billing_scheme": "per_unit",
          "amount": 25,
          "ui": {
            "display_name": "Storage",
            "billing_period": "per GB/month"
          }
        }
      ]
    }
  ]
}
```

## Best Practices [#best-practices]

1. **Batch Usage Events** — Don't send individual events; batch them for performance

2. **Use Appropriate Aggregation** — `sum` for cumulative metrics, `last` for point-in-time metrics

3. **Include Free Tiers** — Start tiered pricing with a free tier for better customer experience

4. **Display Usage** — Show customers their current usage and projected costs

5. **Set Usage Alerts** — Notify customers when they approach usage thresholds

## Related [#related]

- [Products & Prices](/guides/stripe/products-prices) — Tiered pricing configuration
- [Invoices](/guides/stripe/invoices) — Adding usage to invoices
- [Webhooks](/guides/stripe/webhooks) — Invoice event handling

# Products & Prices (/guides/stripe/products-prices)

Products represent what you sell, and prices define how much customers pay. Omnibase supports per-unit pricing, tiered pricing, and usage-based billing.

## Product Configuration [#product-configuration]

### Basic Product Structure [#basic-product-structure]

```json
{
  "id": "pro",
  "name": "Professional Plan",
  "description": "For growing businesses",
  "type": "service",
  "metadata": { "tier": "pro" },
  "stripe_id": "prod_xxx",
  "prices": [],
  "ui": {}
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique identifier for the product (config ID) |
| `name` | `string` | Yes | Product name displayed in Stripe and your UI |
| `description` | `string` | No | Product description |
| `type` | `string` | No | `service` (subscriptions) or `good` (one-time) |
| `metadata` | `object` | No | String metadata synced to the Stripe product |
| `stripe_id` | `string` | No | Existing Stripe product ID (for migrations) |
| `prices` | `array` | Yes | Array of price definitions (minimum 1) |
| `ui` | `object` | No | UI display configuration |

### Product Types [#product-types]

| Type | Use Case | Example |
|------|----------|---------|
| `service` | Recurring subscriptions | SaaS plans, memberships |
| `good` | One-time purchases, usage | Infrastructure, API calls |

## Price Configuration [#price-configuration]

### Per-Unit Pricing [#per-unit-pricing]

The simplest pricing model charges a fixed amount:

```json
{
  "id": "pro_monthly",
  "amount": 4900,
  "currency": "usd",
  "interval": "month",
  "interval_count": 1,
  "usage_type": "licensed",
  "billing_scheme": "per_unit",
  "public": true,
  "default": true,
  "metadata": { "billing": "monthly" },
  "stripe_id": "price_xxx",
  "ui": {}
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | Yes | Unique price identifier |
| `amount` | `number` | Yes | Price in smallest currency unit (cents for USD) |
| `currency` | `string` | Yes | 3-letter ISO currency code (lowercase) |
| `interval` | `string` | No | Billing interval: `day`, `week`, `month`, `year` |
| `interval_count` | `integer` | No | Number of intervals between billings (default: 1) |
| `usage_type` | `string` | No | `licensed` (fixed) or `metered` (usage-based) |
| `billing_scheme` | `string` | No | `per_unit` (default) or `tiered` |
| `public` | `boolean` | No | Visible in public API (`true`/`null` = public) |
| `default` | `boolean` | No | Default price for the product |
| `tax_included_in_price` | `boolean` | No | Whether tax is included |
| `metadata` | `object` | No | String metadata synced to the Stripe price |
| `stripe_id` | `string` | No | Existing Stripe price ID (for migrations) |
| `ui` | `object` | No | UI display configuration |

### Tiered Pricing [#tiered-pricing]

For volume-based or graduated pricing:

```json
{
  "id": "api_calls_tiered",
  "currency": "usd",
  "interval": "month",
  "usage_type": "metered",
  "meter": "api_calls",
  "billing_scheme": "tiered",
  "tiers_mode": "graduated",
  "tiers": [
    { "up_to": 1000, "unit_amount": 0 },
    { "up_to": 10000, "unit_amount": 100 },
    { "up_to": 100000, "unit_amount": 50 },
    { "up_to": "inf", "unit_amount": 25 }
  ]
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `billing_scheme` | `string` | Yes | Must be `tiered` |
| `tiers_mode` | `string` | Yes | `graduated` or `volume` |
| `tiers` | `array` | Yes | Array of tier definitions |
| `metadata` | `object` | No | String metadata synced to the Stripe price |

### Metadata [#metadata]

Products and prices accept an optional `metadata` object. Values must be strings; numbers and booleans are rejected rather than coerced.

```json
{
  "id": "pg_scale_large_monthly",
  "amount": 3500,
  "currency": "usd",
  "interval": "month",
  "metadata": {
    "size": "large",
    "postgres_cpu": "2",
    "postgres_ram_gb": "8"
  }
}
```

Rules:

- Metadata is optional on products, prices, or both.
- A metadata-only change updates the existing Stripe product or price in place; it never recreates a price.
- Removing a key from the config removes it from Stripe on the next sync.
- Values are limited to 500 characters and keys to 40. Stripe allows 50 keys per object; Omnibase reserves 3, leaving 47 user keys.
- `omnibase_id`, `omnibase_managed` and `omnibase_hash` are reserved.

### Tier Modes [#tier-modes]

**Graduated Pricing** — Each tier's price applies only to units within that tier:

```
Example: 15,000 API calls
- First 1,000: Free (1,000 × $0.00)
- Next 9,000: $0.01 each (9,000 × $0.01 = $90)
- Next 5,000: $0.005 each (5,000 × $0.005 = $25)
Total: $115
```

**Volume Pricing** — The applicable tier's price applies to ALL units:

```
Example: 15,000 API calls (falls in 10,001-100,000 tier)
- All 15,000: $0.005 each (15,000 × $0.005 = $75)
Total: $75
```

### Tier Structure [#tier-structure]

```json
{
  "up_to": 1000,
  "flat_amount": 0,
  "unit_amount": 100
}
```

| Field | Type | Description |
|-------|------|-------------|
| `up_to` | `integer` or `"inf"` | Upper limit of this tier. Use `"inf"` for the final tier |
| `flat_amount` | `integer` | Flat fee for this tier (in cents) |
| `unit_amount` | `integer` | Per-unit price for this tier (in cents) |

<Component type="warn">
The final tier must have `"up_to": "inf"` to handle any quantity.
</Component>

### Sub-Cent Pricing [#sub-cent-pricing]

For high-volume usage pricing, you may need sub-cent amounts:

```json
{
  "id": "compute_hourly",
  "amount": 0.684,
  "currency": "usd",
  "interval": "month",
  "usage_type": "metered"
}
```

Omnibase supports decimal amounts for precise pricing.

## Free Tiers [#free-tiers]

Unlike Stripe, Omnibase supports $0 prices:

```json
{
  "id": "free",
  "amount": 0,
  "currency": "usd",
  "interval": "month",
  "ui": {
    "price_display": {
      "custom_text": "Free"
    }
  }
}
```

Free prices are stored in PostgreSQL and bypass Stripe checkout.

## Enterprise Pricing [#enterprise-pricing]

### Template-Based Pricing [#template-based-pricing]

Create discount templates for enterprise tiers:

```json
{
  "id": "pro_monthly_enterprise_tier1",
  "amount": 4410,
  "currency": "usd",
  "interval": "month",
  "public": false,
  "enterprise_template": "tier1_10pct_off"
}
```

### Custom Per-Tenant Pricing [#custom-per-tenant-pricing]

Create custom pricing for specific customers:

```json
{
  "id": "pro_monthly_acme",
  "amount": 3920,
  "currency": "usd",
  "interval": "month",
  "public": false,
  "enterprise_id": "acme_corp"
}
```

See [Enterprise Pricing](/guides/stripe/enterprise-pricing) for details.

## UI Configuration [#ui-configuration]

### Product UI [#product-ui]

```json
{
  "ui": {
    "display_name": "Pro",
    "tagline": "For growing teams",
    "features": [
      "Unlimited projects",
      "Priority support",
      "Advanced analytics"
    ],
    "badge": "Most Popular",
    "cta_text": "Upgrade to Pro",
    "highlighted": true,
    "sort_order": 3
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `display_name` | `string` | Display name in UI |
| `tagline` | `string` | Short description/tagline |
| `features` | `string[]` | List of product features |
| `badge` | `string` | Badge text (`"Most Popular"`, `"Best Value"`, etc.) |
| `cta_text` | `string` | Call-to-action button text |
| `highlighted` | `boolean` | Highlight this product in pricing table |
| `sort_order` | `integer` | Display order (lower = first) |

### Price UI [#price-ui]

```json
{
  "ui": {
    "display_name": "Monthly",
    "billing_period": "per month",
    "price_display": {
      "custom_text": "Custom",
      "show_currency": true,
      "suffix": "/month"
    },
    "features": [
      "Everything in Free",
      "API access"
    ],
    "limits": [
      {
        "text": "0.75% transaction fee",
        "value": 0.75,
        "unit": "percent"
      },
      {
        "text": "Unlimited instances",
        "value": null,
        "unit": "instances"
      }
    ]
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `display_name` | `string` | Price tier name |
| `billing_period` | `string` | Human-readable period (`"per month"`, `"Forever"`) |
| `price_display` | `object` | Custom price display options |
| `features` | `string[]` | Features specific to this price |
| `limits` | `array` | Usage limits for this price |

### Price Display Options [#price-display-options]

```json
{
  "price_display": {
    "custom_text": "Free",
    "show_currency": false,
    "suffix": "/month"
  }
}
```

| Field | Type | Description |
|-------|------|-------------|
| `custom_text` | `string` | Custom text instead of price (`"Free"`, `"Custom"`) |
| `show_currency` | `boolean` | Whether to show currency symbol |
| `suffix` | `string` | Text after price (`"/month"`, `"/year"`) |

### Price Limits [#price-limits]

```json
{
  "limits": [
    {
      "text": "2 instances",
      "value": 2,
      "unit": "instances"
    },
    {
      "text": "2.5% transaction fee",
      "value": 2.5,
      "unit": "percent"
    }
  ]
}
```

## Complete Example [#complete-example]

```json title="omnibase/stripe/subscriptions.config.json"
{
  "$schema": "https://dashboard.omnibase.tech/api/stripe-config.schema.json",
  "version": "1.0.0",
  "products": [
    {
      "id": "free",
      "name": "Free Plan",
      "description": "Get started with Omnibase",
      "type": "service",
      "prices": [
        {
          "id": "free",
          "amount": 0,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "ui": {
            "display_name": "Free",
            "billing_period": "Forever",
            "price_display": { "custom_text": "Free" },
            "limits": [
              { "text": "2 instances", "value": 2, "unit": "instances" },
              { "text": "2.5% transaction fee", "value": 2.5, "unit": "percent" }
            ]
          }
        }
      ],
      "ui": {
        "display_name": "Free",
        "tagline": "For personal projects",
        "sort_order": 1
      }
    },
    {
      "id": "starter",
      "name": "Starter Plan",
      "type": "service",
      "prices": [
        {
          "id": "starter_monthly",
          "amount": 1900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        }
      ],
      "ui": {
        "display_name": "Starter",
        "tagline": "For small teams",
        "sort_order": 2
      }
    },
    {
      "id": "pro",
      "name": "Pro Plan",
      "type": "service",
      "prices": [
        {
          "id": "pro_monthly",
          "amount": 4900,
          "currency": "usd",
          "interval": "month",
          "public": true,
          "default": true
        },
        {
          "id": "pro_yearly",
          "amount": 49000,
          "currency": "usd",
          "interval": "year",
          "public": true
        }
      ],
      "ui": {
        "display_name": "Pro",
        "tagline": "For growing teams",
        "badge": "Most Popular",
        "highlighted": true,
        "sort_order": 3
      }
    },
    {
      "id": "enterprise",
      "name": "Enterprise",
      "type": "service",
      "prices": [
        {
          "id": "enterprise",
          "amount": 0,
          "currency": "usd",
          "public": true,
          "ui": {
            "price_display": { "custom_text": "Custom" }
          }
        }
      ],
      "ui": {
        "display_name": "Enterprise",
        "tagline": "For large organizations",
        "cta_text": "Contact Sales",
        "sort_order": 4
      }
    }
  ]
}
```

## API Usage [#api-usage]

### Get Price Details [#get-price-details]

```typescript
import { V1StripeApi } from '@omnibase/core-js';

const stripeApi = new V1StripeApi(config);

// Get price by config ID
const { data } = await stripeApi.getPriceByID({ priceId: 'pro_monthly' });
console.log(data.price.amount); // 4900
console.log(data.product.name); // "Pro Plan"
```

### Calculate Cost [#calculate-cost]

```typescript
// Calculate cost for a quantity
const { data } = await stripeApi.calculatePriceCost({
  priceId: 'api_calls_tiered',
  calculatePriceCostRequest: { quantity: 15000 },
});

console.log(data.cost_cents); // Cost in cents
console.log(data.effective_unit_cost_cents); // Average cost per unit
console.log(data.tiers_mode); // "graduated" or "volume"
```

### Get All Products [#get-all-products]

```typescript
const { data: stripeConfig } = await stripeApi.getStripeConfig();

// Filter to public products
const publicProducts = stripeConfig.products.filter(p =>
  p.prices.some(price => price.public !== false)
);
```

## Related [#related]

- [Configuration Guide](/guides/stripe/configuration) — Full configuration reference
- [Metering](/guides/stripe/metering) — Usage-based pricing with meters
- [Enterprise Pricing](/guides/stripe/enterprise-pricing) — Custom pricing for enterprises
- [Checkout & Portal](/guides/stripe/checkout-portal) — Creating checkout sessions

# Subscriptions (/guides/stripe/subscriptions)

Omnibase provides a complete subscription management system built on Stripe, with tenant-level subscription tracking and automatic customer creation.

## Subscription Lifecycle [#subscription-lifecycle]

```
┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Tenant    │────▶│  Checkout   │────▶│   Active    │────▶│  Canceled   │
│   Created   │     │   Session   │     │ Subscription│     │             │
└─────────────┘     └─────────────┘     └─────────────┘     └─────────────┘
       │                                       │
       ▼                                       ▼
┌─────────────┐                        ┌─────────────┐
│   Stripe    │                        │   Trial     │
│  Customer   │                        │   Period    │
│   Created   │                        └─────────────┘
└─────────────┘
```

## Automatic Customer Creation [#automatic-customer-creation]

When a tenant is created with a `billing_email`, Omnibase automatically creates a Stripe customer:

```typescript
import { V1TenantsApi } from '@omnibase/core-js';

const tenantsApi = new V1TenantsApi(config);

// Create tenant with billing email
const { data: tenant } = await tenantsApi.createTenant({
  createTenantRequest: {
    name: 'Acme Corp',
    billingEmail: 'billing@acme.com',
  },
});

// Stripe customer ID is automatically populated
console.log(tenant.stripeCustomerId); // "cus_xxx..."
```

## Subscription States [#subscription-states]

| State | Description |
|-------|-------------|
| `active` | Subscription is currently active and billing |
| `trialing` | Subscription is in trial period |
| `past_due` | Payment failed but subscription still active |
| `canceled` | Subscription has been canceled |
| `paused` | Subscription is paused (if enabled) |
| `incomplete` | Initial payment failed during checkout |

## Managing Subscriptions [#managing-subscriptions]

### List Tenant Subscriptions [#list-tenant-subscriptions]

```typescript
import { V1TenantsApi } from '@omnibase/core-js';

const tenantsApi = new V1TenantsApi(config);

const { data: subscriptions } = await tenantsApi.listTenantSubscriptions();

subscriptions.forEach(sub => {
  console.log(`Plan: ${sub.configPriceId}`);
  console.log(`Status: ${sub.status}`);
  console.log(`Current Period: ${new Date(sub.currentPeriodStart * 1000)} - ${new Date(sub.currentPeriodEnd * 1000)}`);

  if (sub.trialEnd) {
    console.log(`Trial ends: ${new Date(sub.trialEnd * 1000)}`);
  }
});
```

### Get Single Subscription [#get-single-subscription]

```typescript
const { data: subscription } = await tenantsApi.getTenantSubscription({
  configPriceId: 'pro_monthly',
});

console.log(subscription.status);
console.log(subscription.cancelAtPeriodEnd);
```

### Add Subscription [#add-subscription]

```typescript
const { data } = await tenantsApi.addTenantSubscription({
  addTenantSubscriptionRequest: {
    priceId: 'pro_monthly',
  },
});

console.log('Subscription created:', data.subscriptionId);
```

### Cancel Subscription [#cancel-subscription]

```typescript
await tenantsApi.removeTenantSubscription({
  removeTenantSubscriptionRequest: {
    priceId: 'pro_monthly',
  },
});
```

<Component type="info">
By default, subscriptions are canceled at the end of the current billing period. The customer retains access until then.
</Component>

## Subscription Response [#subscription-response]

```typescript
interface SubscriptionResponse {
  subscriptionId: string;      // Stripe subscription ID
  configPriceId: string;       // Your config price ID
  status: string;              // active, trialing, canceled, etc.
  isLegacyPrice: boolean;      // True if price was migrated
  currentPeriodStart: number;  // Unix timestamp
  currentPeriodEnd: number;    // Unix timestamp
  cancelAtPeriodEnd: boolean;  // Will cancel at period end
  canceledAt?: number;         // When canceled (if applicable)
  trialStart?: number;         // Trial start (if applicable)
  trialEnd?: number;           // Trial end (if applicable)
}
```

## Billing Status [#billing-status]

Check if a tenant has a valid payment method:

```typescript
const { data } = await tenantsApi.getTenantBillingStatus();

if (data.isActive) {
  console.log('Payment method is attached');
} else {
  console.log('No payment method - redirect to billing setup');
}
```

## Server-Side Implementation [#server-side-implementation]

### Next.js Example [#nextjs-example]

```tsx title="app/(dashboard)/subscriptions/page.tsx"
import { V1StripeApi, V1TenantsApi, V1PaymentsApi } from '@omnibase/core-js';
import { redirect } from 'next/navigation';
import { PricingTable } from '@omnibase/shadcn';

export default async function SubscriptionsPage() {
  const stripeApi = new V1StripeApi(config);
  const tenantsApi = new V1TenantsApi(config);
  const paymentsApi = new V1PaymentsApi(config);

  // Get available plans
  const { data: stripeConfig } = await stripeApi.getStripeConfig();

  // Get current subscription
  const { data: subscriptions } = await tenantsApi.listTenantSubscriptions();
  const currentPriceId = subscriptions?.[0]?.configPriceId;

  async function createCheckout(priceId: string) {
    'use server';
    const { data } = await paymentsApi.createCheckout({
      createCheckoutRequest: {
        priceId,
        successUrl: `${process.env.APP_URL}/subscriptions?success=true`,
        cancelUrl: `${process.env.APP_URL}/subscriptions`,
        trialPeriodDays: 14,
        allowPromotionCodes: true,
      },
    });
    redirect(data.url!);
  }

  async function openPortal() {
    'use server';
    const { data } = await paymentsApi.createCustomerPortal({
      createPortalRequest: {
        returnUrl: `${process.env.APP_URL}/subscriptions`,
      },
    });
    redirect(data.url!);
  }

  return (
    <div className="container py-8">
      <h1 className="text-2xl font-bold mb-8">Subscription</h1>

      <PricingTable
        products={stripeConfig.products}
        selectedPriceId={currentPriceId}
        onPriceSelect={createCheckout}
        showPricingToggle
      />

      {currentPriceId && (
        <form action={openPortal} className="mt-8">
          <button type="submit" className="btn">
            Manage Billing
          </button>
        </form>
      )}
    </div>
  );
}
```

## Trial Periods [#trial-periods]

Add trial periods when creating checkout sessions:

```typescript
const { data } = await paymentsApi.createCheckout({
  createCheckoutRequest: {
    priceId: 'pro_monthly',
    successUrl: 'https://example.com/success',
    cancelUrl: 'https://example.com/pricing',
    trialPeriodDays: 14, // 14-day free trial
  },
});
```

### Trial Behavior [#trial-behavior]

- Customer is not charged during trial
- Payment method is collected but not charged
- Subscription transitions to `active` when trial ends
- `trial_will_end` webhook fires 3 days before trial ends

## Handling Subscription Changes [#handling-subscription-changes]

### Upgrade/Downgrade [#upgradedowngrade]

When a customer changes plans, the subscription item price is swapped:

```typescript
// This is typically handled through Customer Portal
// or programmatically via the admin API
```

### Proration [#proration]

By default, Stripe prorates charges when customers change plans mid-cycle:

- **Upgrade**: Customer is charged the prorated difference immediately
- **Downgrade**: Customer receives credit applied to future invoices

## Webhook Events [#webhook-events]

Subscribe to these events for subscription management:

```json
{
  "webhooks": [
    {
      "id": "subscription_events",
      "url": "${WEBHOOK_URL}/api/stripe/subscriptions",
      "events": [
        "customer.subscription.created",
        "customer.subscription.updated",
        "customer.subscription.deleted",
        "customer.subscription.paused",
        "customer.subscription.resumed",
        "customer.subscription.trial_will_end"
      ]
    }
  ]
}
```

### Event Handling [#event-handling]

```typescript
switch (event.type) {
  case 'customer.subscription.created':
    // New subscription started
    const subscription = event.data.object;
    await activateTenantFeatures(subscription.customer);
    break;

  case 'customer.subscription.updated':
    // Subscription changed (plan change, status change, etc.)
    await updateTenantPlan(subscription.customer, subscription.items);
    break;

  case 'customer.subscription.deleted':
    // Subscription canceled
    await deactivateTenantFeatures(subscription.customer);
    break;

  case 'customer.subscription.trial_will_end':
    // Trial ending in 3 days - send reminder email
    await sendTrialEndingEmail(subscription.customer);
    break;
}
```

## Legacy Price Handling [#legacy-price-handling]

When prices are updated in your configuration, Omnibase tracks the history:

```typescript
const { data: subscriptions } = await tenantsApi.listTenantSubscriptions();

subscriptions.forEach(sub => {
  if (sub.isLegacyPrice) {
    console.log(`${sub.configPriceId} is on a legacy price`);
    // Consider migrating to current price
  }
});
```

## Best Practices [#best-practices]

1. **Always Use Config IDs** — Reference prices by config ID (`pro_monthly`), not Stripe ID (`price_xxx`)

2. **Handle All States** — Your UI should handle `active`, `trialing`, `past_due`, and `canceled` states

3. **Implement Webhooks** — Don't rely on polling; use webhooks for real-time updates

4. **Graceful Degradation** — When a subscription is `past_due`, consider a grace period before restricting access

5. **Trial Communication** — Send emails before trial ends to improve conversion

## Related [#related]

- [Checkout & Portal](/guides/stripe/checkout-portal) — Creating checkout sessions
- [Webhooks](/guides/stripe/webhooks) — Handling subscription events
- [Enterprise Pricing](/guides/stripe/enterprise-pricing) — Custom pricing for enterprises
- [UI Components](/guides/stripe/ui-components) — PricingTable component

# UI Components (/guides/stripe/ui-components)

Omnibase provides pre-built React components via the `@omnibase/shadcn` package for displaying pricing information and handling billing interactions.

## Installation [#installation]

```bash
bun add @omnibase/shadcn @omnibase/core-js
```

## PricingTable [#pricingtable]

The `PricingTable` component displays your Stripe products with pricing, features, and a selection interface.

### Basic Usage [#basic-usage]

```tsx
import { PricingTable } from '@omnibase/shadcn';
import { V1StripeApi } from '@omnibase/core-js';

export default async function PricingPage() {
  const stripeApi = new V1StripeApi(config);
  const { data: stripeConfig } = await stripeApi.getStripeConfig();

  return (
    <PricingTable
      products={stripeConfig.products}
      onPriceSelect={(priceId, productId) => {
        console.log(`Selected: ${priceId} from ${productId}`);
      }}
    />
  );
}
```

### Props [#props]

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `products` | `Product[]` | Required | Array of products from Stripe config |
| `selectedPriceId` | `string` | — | Currently selected price (shows visual indicator) |
| `onPriceSelect` | `(priceId: string, productId: string) => void` | — | Callback when a price is selected |
| `className` | `string` | — | Additional CSS classes |
| `showPricingToggle` | `boolean` | `false` | Show month/year interval toggle |
| `defaultInterval` | `"month"` \| `"year"` | `"month"` | Default billing interval |

### Features [#features]

#### Responsive Design [#responsive-design]

The component automatically adapts to screen size:

| Screen Size | Behavior |
|-------------|----------|
| Mobile | Single-card carousel with swipe navigation |
| Tablet | Single-card carousel |
| Desktop | 3-card carousel (or grid if ≤3 products) |

#### Billing Period Toggle [#billing-period-toggle]

When `showPricingToggle={true}`, displays a month/year toggle:

```tsx
<PricingTable
  products={products}
  showPricingToggle={true}
  defaultInterval="month"
/>
```

The toggle only appears if products have prices with different intervals.

#### Selected Price Indicator [#selected-price-indicator]

Highlight the current subscription:

```tsx
<PricingTable
  products={products}
  selectedPriceId="pro_monthly"
  onPriceSelect={handleSelect}
/>
```

The selected product displays with a visual ring indicator.

#### Product Highlighting [#product-highlighting]

Products with `ui.highlighted: true` display a "Most Popular" badge:

```json
{
  "id": "pro",
  "name": "Pro Plan",
  "ui": {
    "highlighted": true,
    "badge": "Most Popular"
  }
}
```

### Complete Example [#complete-example]

```tsx title="app/(dashboard)/subscriptions/page.tsx"
import { V1StripeApi, V1TenantsApi, V1PaymentsApi, Product } from '@omnibase/core-js';
import { PricingTable } from '@omnibase/shadcn';
import { redirect } from 'next/navigation';

export default async function SubscriptionsPage() {
  const stripeApi = new V1StripeApi(config);
  const tenantsApi = new V1TenantsApi(config);

  const [{ data: stripeConfig }, { data: subscriptions }] = await Promise.all([
    stripeApi.getStripeConfig(),
    tenantsApi.listTenantSubscriptions(),
  ]);

  const currentPriceId = subscriptions?.[0]?.configPriceId;

  async function handleCheckout(priceId: string) {
    'use server';
    const paymentsApi = new V1PaymentsApi(config);
    const { data } = await paymentsApi.createCheckout({
      createCheckoutRequest: {
        priceId,
        successUrl: `${process.env.APP_URL}/subscriptions?success=true`,
        cancelUrl: `${process.env.APP_URL}/subscriptions`,
        trialPeriodDays: 14,
        allowPromotionCodes: true,
      },
    });
    redirect(data.url!);
  }

  return (
    <div className="container py-12">
      <div className="text-center mb-12">
        <h1 className="text-4xl font-bold mb-4">Choose Your Plan</h1>
        <p className="text-muted-foreground">
          Select the perfect plan for your needs
        </p>
      </div>

      <PricingTable
        products={stripeConfig.products as Product[]}
        selectedPriceId={currentPriceId}
        onPriceSelect={handleCheckout}
        showPricingToggle
        defaultInterval="month"
      />
    </div>
  );
}
```

## Data Types [#data-types]

The PricingTable component uses types from `@omnibase/core-js`:

### Product [#product]

```typescript
interface Product {
  id: string;                    // Config ID (e.g., "pro")
  stripeId?: string;             // Stripe product ID
  name: string;                  // Display name
  description?: string;          // Product description
  type?: "service" | "good";     // Product type
  prices: Price[];               // Array of prices
  ui?: ProductUI;                // UI customization
}
```

### ProductUI [#productui]

```typescript
interface ProductUI {
  displayName?: string;          // Override display name
  tagline?: string;              // Short tagline (e.g., "Perfect for teams")
  features?: string[];           // List of features
  badge?: string;                // Badge text (e.g., "Most Popular")
  ctaText?: string;              // Button text (e.g., "Upgrade to Pro")
  highlighted?: boolean;         // Highlight this product
  sortOrder?: number;            // Display order (lower = first)
}
```

### Price [#price]

```typescript
interface Price {
  id: string;                    // Config ID (e.g., "pro_monthly")
  stripeId?: string;             // Stripe price ID
  amount: number;                // Amount in cents (4900 = $49.00)
  currency: string;              // Currency code (e.g., "usd")
  interval?: string;             // "month", "year", "week", "day"
  intervalCount?: number;        // Billing frequency (default: 1)
  usageType?: string;            // "licensed" or "metered"
  billingScheme?: string;        // "per_unit" or "tiered"
  public?: boolean;              // Visible in public API
  default?: boolean;             // Default price for product
  ui?: PriceUI;                  // UI customization
}
```

### PriceUI [#priceui]

```typescript
interface PriceUI {
  displayName?: string;          // Override display name
  billingPeriod?: string;        // Human-readable period (e.g., "per month")
  priceDisplay?: PriceDisplay;   // Custom price display
  features?: string[];           // Price-specific features
  limits?: PriceLimit[];         // Usage limits
}
```

### PriceDisplay [#pricedisplay]

```typescript
interface PriceDisplay {
  customText?: string;           // Custom text (e.g., "Free", "Custom")
  showCurrency?: boolean;        // Show currency symbol
  suffix?: string;               // Text after price (e.g., " (Save 17%)")
}
```

### PriceLimit [#pricelimit]

```typescript
interface PriceLimit {
  text: string;                  // Limit description
  value?: number;                // Numeric value
  unit?: string;                 // Unit (e.g., "instances", "percent")
}
```

## Customizing Display [#customizing-display]

### Custom Price Text [#custom-price-text]

For free tiers or custom pricing:

```json
{
  "id": "free",
  "amount": 0,
  "currency": "usd",
  "interval": "month",
  "ui": {
    "priceDisplay": {
      "customText": "Free",
      "showCurrency": false
    }
  }
}
```

Renders as: **Free** (instead of $0.00)

### Enterprise/Contact Sales [#enterprisecontact-sales]

```json
{
  "id": "enterprise",
  "amount": 0,
  "currency": "usd",
  "ui": {
    "priceDisplay": {
      "customText": "Custom"
    }
  }
}
```

### Savings Suffix [#savings-suffix]

```json
{
  "id": "pro_yearly",
  "amount": 49000,
  "currency": "usd",
  "interval": "year",
  "ui": {
    "priceDisplay": {
      "suffix": " (Save 17%)"
    }
  }
}
```

Renders as: **$490.00/year (Save 17%)**

### Feature Lists [#feature-lists]

Define features at the product or price level:

```json
{
  "id": "pro",
  "name": "Pro Plan",
  "ui": {
    "features": [
      "Unlimited projects",
      "Priority support",
      "Advanced analytics"
    ]
  },
  "prices": [
    {
      "id": "pro_monthly",
      "amount": 4900,
      "currency": "usd",
      "interval": "month",
      "ui": {
        "features": [
          "Everything in Starter",
          "API access"
        ]
      }
    }
  ]
}
```

### Usage Limits [#usage-limits]

Display limits with values:

```json
{
  "id": "starter_monthly",
  "amount": 1900,
  "ui": {
    "limits": [
      { "text": "5 projects", "value": 5, "unit": "projects" },
      { "text": "10 GB storage", "value": 10, "unit": "GB" },
      { "text": "1.5% transaction fee", "value": 1.5, "unit": "percent" }
    ]
  }
}
```

## Currency Support [#currency-support]

The PricingTable supports these currencies with proper symbol formatting:

| Currency | Symbol | Code |
|----------|--------|------|
| US Dollar | $ | `usd` |
| Euro | € | `eur` |
| British Pound | £ | `gbp` |
| Japanese Yen | ¥ | `jpy` |
| Canadian Dollar | CA$ | `cad` |
| Australian Dollar | A$ | `aud` |

Other currencies display the currency code.

## Sorting Products [#sorting-products]

Products are sorted by `ui.sortOrder`:

```json
[
  { "id": "free", "ui": { "sortOrder": 1 } },
  { "id": "starter", "ui": { "sortOrder": 2 } },
  { "id": "pro", "ui": { "sortOrder": 3 } },
  { "id": "enterprise", "ui": { "sortOrder": 4 } }
]
```

Lower numbers appear first. Products without `sortOrder` appear at the end.

## TenantCreator [#tenantcreator]

The `TenantCreator` component includes billing-related functionality for initial organization setup.

### Usage [#usage]

```tsx
import { TenantCreator } from '@omnibase/shadcn';

export function OnboardingPage() {
  return (
    <TenantCreator
      config={{
        defaultMode: 'create',
        createForm: {
          organizationName: {
            label: 'Organization Name',
            placeholder: 'Acme Corp',
          },
          billingEmail: {
            label: 'Billing Email',
            placeholder: 'billing@acme.com',
          },
        },
      }}
      actions={{
        createOrganizationAction: async (formData) => {
          'use server';
          // Create tenant with billing email
          await tenantsApi.createTenant({
            createTenantRequest: {
              name: formData.get('name') as string,
              billingEmail: formData.get('billing_email') as string,
            },
          });
        },
      }}
    />
  );
}
```

The `billingEmail` field triggers automatic Stripe customer creation when the tenant is created.

## Styling [#styling]

Components are built with Tailwind CSS and shadcn/ui. Customize via:

### CSS Variables [#css-variables]

Override shadcn/ui CSS variables in your global styles:

```css title="app/globals.css"
:root {
  --primary: 222.2 84% 4.9%;
  --primary-foreground: 210 40% 98%;
  /* ... other variables */
}
```

### className Prop [#classname-prop]

Add custom classes:

```tsx
<PricingTable
  products={products}
  className="max-w-5xl mx-auto"
/>
```

### Component Customization [#component-customization]

For deeper customization, you can import and modify the component source from `@omnibase/shadcn`.

## Storybook [#storybook]

View component variations in Storybook:

```bash
cd public/sdk/component/shadcn
bun run storybook
```

Available stories:
- `Default` — Standard pricing table
- `WithSelectedPrice` — Pre-selected subscription
- `YearlyDefault` — Annual pricing selected
- `WithoutToggle` — No interval toggle
- `SingleProduct` — Single product display
- `CustomStyling` — Full page example
- `CarouselExample` — Multiple products with carousel

## Related [#related]

- [Products & Prices](/guides/stripe/products-prices) — Configure product UI
- [Checkout & Portal](/guides/stripe/checkout-portal) — Handle price selection
- [Subscriptions](/guides/stripe/subscriptions) — Display current subscription

# Webhooks (/guides/stripe/webhooks)

Webhooks allow your application to receive real-time notifications about events in your Stripe account, such as successful payments, subscription changes, and invoice updates.

## Webhook Configuration [#webhook-configuration]

### Basic Webhook Setup [#basic-webhook-setup]

```json
{
  "webhooks": [
    {
      "id": "main_webhook",
      "url": "${STRIPE_WEBHOOK_URL}/api/stripe/webhook",
      "events": [
        "customer.subscription.created",
        "customer.subscription.updated",
        "customer.subscription.deleted",
        "invoice.paid",
        "invoice.payment_failed"
      ],
      "connect": false
    }
  ]
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | `string` | No | Unique identifier for the webhook |
| `url` | `string` | Yes | Webhook endpoint URL |
| `events` | `string[]` | Yes | List of events to subscribe to (minimum 1) |
| `connect` | `boolean` | No | Listen to Stripe Connect events (default: false) |

### Environment Variable Interpolation [#environment-variable-interpolation]

Use `${VAR_NAME}` syntax for environment-specific URLs:

```json
{
  "webhooks": [
    {
      "id": "main_webhook",
      "url": "${STRIPE_WEBHOOK_URL}/api/stripe/webhook",
      "events": ["invoice.created"]
    }
  ]
}
```

Set the environment variable:

```bash title=".env"
STRIPE_WEBHOOK_URL=https://api.example.com
```

## Supported Events [#supported-events]

Omnibase supports 60+ Stripe webhook events organized by category:

### Account Events [#account-events]

| Event | Description |
|-------|-------------|
| `account.updated` | Account details changed |
| `account.application.deauthorized` | OAuth application disconnected |
| `account.external_account.created` | Bank account/card added |
| `account.external_account.deleted` | Bank account/card removed |
| `account.external_account.updated` | Bank account/card updated |

### Customer Events [#customer-events]

| Event | Description |
|-------|-------------|
| `customer.created` | New customer created |
| `customer.updated` | Customer details updated |
| `customer.deleted` | Customer deleted |

### Subscription Events [#subscription-events]

| Event | Description |
|-------|-------------|
| `customer.subscription.created` | New subscription started |
| `customer.subscription.updated` | Subscription changed |
| `customer.subscription.deleted` | Subscription canceled |
| `customer.subscription.paused` | Subscription paused |
| `customer.subscription.resumed` | Subscription resumed |
| `customer.subscription.trial_will_end` | Trial ending soon (3 days) |

### Payment Events [#payment-events]

| Event | Description |
|-------|-------------|
| `payment_intent.created` | Payment intent created |
| `payment_intent.succeeded` | Payment successful |
| `payment_intent.payment_failed` | Payment failed |
| `payment_intent.canceled` | Payment canceled |
| `payment_intent.requires_action` | Requires customer action (3DS) |

### Charge Events [#charge-events]

| Event | Description |
|-------|-------------|
| `charge.succeeded` | Charge successful |
| `charge.failed` | Charge failed |
| `charge.refunded` | Charge refunded |
| `charge.captured` | Charge captured |
| `charge.dispute.created` | Dispute opened |
| `charge.dispute.updated` | Dispute updated |
| `charge.dispute.closed` | Dispute closed |

### Invoice Events [#invoice-events]

| Event | Description |
|-------|-------------|
| `invoice.created` | Draft invoice created |
| `invoice.finalized` | Invoice finalized |
| `invoice.paid` | Invoice paid |
| `invoice.payment_failed` | Payment failed |
| `invoice.payment_action_required` | Requires customer action |
| `invoice.upcoming` | Upcoming invoice notification |
| `invoice.marked_uncollectible` | Marked uncollectible |
| `invoice.voided` | Invoice voided |

### Checkout Events [#checkout-events]

| Event | Description |
|-------|-------------|
| `checkout.session.completed` | Checkout completed |
| `checkout.session.expired` | Checkout expired |
| `checkout.session.async_payment_succeeded` | Async payment succeeded |
| `checkout.session.async_payment_failed` | Async payment failed |

### Product & Price Events [#product--price-events]

| Event | Description |
|-------|-------------|
| `product.created` | Product created |
| `product.updated` | Product updated |
| `product.deleted` | Product archived |
| `price.created` | Price created |
| `price.updated` | Price updated |
| `price.deleted` | Price archived |

### Other Events [#other-events]

| Event | Description |
|-------|-------------|
| `payout.created` | Payout initiated |
| `payout.paid` | Payout completed |
| `payout.failed` | Payout failed |
| `refund.created` | Refund created |
| `refund.updated` | Refund updated |
| `payment_method.attached` | Payment method attached |
| `payment_method.detached` | Payment method detached |
| `transfer.created` | Transfer created |
| `transfer.reversed` | Transfer reversed |

## Stripe Connect Webhooks [#stripe-connect-webhooks]

For platforms using Stripe Connect, set `connect: true` to receive events from connected accounts:

```json
{
  "webhooks": [
    {
      "id": "platform_webhook",
      "url": "${WEBHOOK_URL}/api/stripe/webhook",
      "events": [
        "account.updated",
        "payment_intent.succeeded"
      ],
      "connect": false
    },
    {
      "id": "connect_webhook",
      "url": "${WEBHOOK_URL}/api/stripe/connect-webhook",
      "events": [
        "account.updated",
        "payment_intent.succeeded",
        "payout.paid"
      ],
      "connect": true
    }
  ]
}
```

## Webhook Secrets [#webhook-secrets]

After configuring webhooks, retrieve the signing secrets:

### CLI [#cli]

```bash
omnibase stripe webhook secret
```

### API [#api]

```bash
GET /api/v1/stripe/admin/webhooks
X-Service-Key: your-service-key
```

Response:

```json
{
  "webhooks": [
    {
      "id": "main_webhook",
      "stripe_id": "we_1ABC123...",
      "url": "https://api.example.com/api/stripe/webhook",
      "events": ["invoice.paid", "customer.subscription.created"],
      "connect": false,
      "secret": "whsec_xxxxxxxxxxxxx"
    }
  ]
}
```

## Handling Webhooks [#handling-webhooks]

### Signature Verification [#signature-verification]

Always verify webhook signatures to ensure events are from Stripe:

<Tabs items={["Next.js","Go"]}>
<Tab value="Next.js">
```typescript title="app/api/stripe/webhook/route.ts"
import Stripe from 'stripe';
import { headers } from 'next/headers';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

export async function POST(request: Request) {
  const body = await request.text();
  const headersList = await headers();
  const signature = headersList.get('stripe-signature')!;

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
  } catch (err) {
    console.error('Webhook signature verification failed');
    return new Response('Invalid signature', { status: 400 });
  }

  switch (event.type) {
    case 'customer.subscription.created':
      const subscription = event.data.object as Stripe.Subscription;
      // Handle new subscription
      break;
    case 'invoice.paid':
      const invoice = event.data.object as Stripe.Invoice;
      // Handle paid invoice
      break;
    case 'invoice.payment_failed':
      const failedInvoice = event.data.object as Stripe.Invoice;
      // Handle failed payment
      break;
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  return new Response('OK', { status: 200 });
}
```
</Tab>

<Tab value="Go">
```go title="internal/handlers/stripe_webhook.go"
package handlers

import (
    "encoding/json"
    "io"
    "net/http"
    "os"

    "github.com/gin-gonic/gin"
    "github.com/stripe/stripe-go/v82/webhook"
)

func HandleStripeWebhook(c *gin.Context) {
    body, err := io.ReadAll(c.Request.Body)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read body"})
        return
    }

    signature := c.GetHeader("Stripe-Signature")
    webhookSecret := os.Getenv("STRIPE_WEBHOOK_SECRET")

    event, err := webhook.ConstructEvent(body, signature, webhookSecret)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid signature"})
        return
    }

    switch event.Type {
    case "customer.subscription.created":
        var subscription stripe.Subscription
        json.Unmarshal(event.Data.Raw, &subscription)
        // Handle new subscription

    case "invoice.paid":
        var invoice stripe.Invoice
        json.Unmarshal(event.Data.Raw, &invoice)
        // Handle paid invoice

    case "invoice.payment_failed":
        var invoice stripe.Invoice
        json.Unmarshal(event.Data.Raw, &invoice)
        // Handle failed payment
    }

    c.JSON(http.StatusOK, gin.H{"received": true})
}
```
</Tab>
</Tabs>

## Common Webhook Patterns [#common-webhook-patterns]

### Subscription Lifecycle [#subscription-lifecycle]

```json
{
  "webhooks": [
    {
      "id": "subscription_events",
      "url": "${WEBHOOK_URL}/api/webhooks/subscriptions",
      "events": [
        "customer.subscription.created",
        "customer.subscription.updated",
        "customer.subscription.deleted",
        "customer.subscription.paused",
        "customer.subscription.resumed",
        "customer.subscription.trial_will_end"
      ]
    }
  ]
}
```

### Payment Monitoring [#payment-monitoring]

```json
{
  "webhooks": [
    {
      "id": "payment_events",
      "url": "${WEBHOOK_URL}/api/webhooks/payments",
      "events": [
        "payment_intent.succeeded",
        "payment_intent.payment_failed",
        "charge.refunded",
        "charge.dispute.created"
      ]
    }
  ]
}
```

### Invoice Processing [#invoice-processing]

```json
{
  "webhooks": [
    {
      "id": "invoice_events",
      "url": "${WEBHOOK_URL}/api/webhooks/invoices",
      "events": [
        "invoice.created",
        "invoice.finalized",
        "invoice.paid",
        "invoice.payment_failed",
        "invoice.marked_uncollectible"
      ]
    }
  ]
}
```

## Idempotency [#idempotency]

Webhooks may be delivered multiple times. Ensure your handlers are idempotent:

```typescript
async function handleInvoicePaid(invoice: Stripe.Invoice) {
  // Check if already processed
  const existing = await db.payments.findUnique({
    where: { stripeInvoiceId: invoice.id },
  });

  if (existing) {
    console.log(`Invoice ${invoice.id} already processed`);
    return;
  }

  // Process the invoice
  await db.payments.create({
    data: {
      stripeInvoiceId: invoice.id,
      amount: invoice.amount_paid,
      customerId: invoice.customer as string,
      processedAt: new Date(),
    },
  });
}
```

## Testing Webhooks [#testing-webhooks]

### Local Development [#local-development]

Use the Stripe CLI to forward webhooks to your local server:

```bash
stripe listen --forward-to localhost:3000/api/stripe/webhook
```

### Trigger Test Events [#trigger-test-events]

```bash
stripe trigger customer.subscription.created
stripe trigger invoice.paid
stripe trigger payment_intent.succeeded
```

<Component type="info">
See [Testing Guide](/guides/stripe/testing) for comprehensive webhook testing strategies.
</Component>

## Best Practices [#best-practices]

1. **Verify Signatures** — Always verify webhook signatures in production

2. **Respond Quickly** — Return a 2xx response within 10 seconds; process asynchronously if needed

3. **Handle Idempotency** — Webhooks may be delivered multiple times

4. **Log Events** — Log all received events for debugging

5. **Use Specific Events** — Subscribe only to events you need

6. **Separate Endpoints** — Consider separate endpoints for different event categories

## Related [#related]

- [Subscriptions](/guides/stripe/subscriptions) — Handling subscription events
- [Invoices](/guides/stripe/invoices) — Invoice webhook processing
- [Testing](/guides/stripe/testing) — Testing webhook handlers

# Cron Jobs (/guides/workers/cron)

Schedule automated tasks that run on Cloudflare's global network. Perfect for periodic data syncing, cleanup jobs, report generation, and API polling.

## What Are Cron Jobs? [#what-are-cron-jobs]

Cron jobs are scheduled tasks that run automatically at specified times or intervals. Omnibase Workers support cron triggers, allowing you to execute code on a schedule without managing servers or infrastructure.

### Key Features [#key-features]

- **Reliable Execution** — Guaranteed to run at scheduled times
- **Global Distribution** — Runs on Cloudflare's edge network
- **No Infrastructure** — Serverless, no servers to maintain
- **Standard Syntax** — Uses familiar cron expression format
- **Environment Variables** — Full access to your environment config

---

## Quick Start [#quick-start]

<Component>
<Component>
### Define Cron Schedule [#define-cron-schedule]

Add cron schedules to your `omnibase/workers/wrangler.toml`:

```toml title="wrangler.toml"
name = "omnibase-edge"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[triggers]
crons = [
  "0 * * * *",      # Every hour
  "0 0 * * *",      # Daily at midnight
  "*/15 * * * *"    # Every 15 minutes
]
```
</Component>

<Component>
### Add Scheduled Handler [#add-scheduled-handler]

Add a `scheduled` handler to your worker in `omnibase/workers/src/index.ts`:

```typescript title="src/index.ts"
import { Hono } from "hono";
import { cors } from "hono/cors";

type EnvVars = {
  OMNIBASE_API_URL: string;
  API_KEY: string;
};

const app = new Hono<{ Bindings: EnvVars }>();

app.use("/*", cors());

app.get("/", (c) => {
  return c.json({
    message: "Hello from the edge!",
    timestamp: new Date().toISOString(),
  });
});

export default {
  fetch: app.fetch,

  // Handle scheduled cron triggers
  async scheduled(event, env, ctx) {
    console.log("Cron job triggered at:", new Date(event.scheduledTime).toISOString());

    // Your scheduled task logic here
    await performScheduledTask(env);
  },
};

async function performScheduledTask(env: EnvVars) {
  // Example: Call your Omnibase API
  const response = await fetch(`${env.OMNIBASE_API_URL}/api/v1/cleanup`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${env.API_KEY}`,
    },
  });

  console.log("Cleanup task completed:", response.status);
}
```
</Component>

<Component>
### Deploy [#deploy]

Deploy your worker with the cron schedules:

```bash
omnibase cloud workers deploy --env production
```

Your cron jobs are now active and will run according to the defined schedules.
</Component>
</Component>

---

## Cron Syntax [#cron-syntax]

Cron expressions use the standard format: `minute hour day month dayOfWeek`

### Common Patterns [#common-patterns]

| Expression | Description |
|------------|-------------|
| `* * * * *` | Every minute |
| `*/5 * * * *` | Every 5 minutes |
| `*/15 * * * *` | Every 15 minutes |
| `0 * * * *` | Every hour at minute 0 |
| `0 */6 * * *` | Every 6 hours |
| `0 0 * * *` | Daily at midnight (00:00) |
| `0 9 * * *` | Daily at 9:00 AM |
| `0 0 * * 0` | Weekly on Sunday at midnight |
| `0 0 1 * *` | Monthly on the 1st at midnight |
| `0 0 1 1 *` | Yearly on January 1st at midnight |

### Syntax Breakdown [#syntax-breakdown]

```
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6) (Sunday = 0)
│ │ │ │ │
* * * * *
```

<Component type="info">
Cloudflare Workers supports standard cron syntax with `*`, ranges (`1-5`), lists (`1,3,5`), and steps (`*/15`).
</Component>

---

## Scheduled Event Object [#scheduled-event-object]

The `scheduled` handler receives three arguments:

```typescript
async scheduled(
  event: ScheduledEvent,
  env: EnvVars,
  ctx: ExecutionContext
) {
  // event.scheduledTime - Timestamp when this invocation was scheduled
  // event.cron - The cron expression that triggered this event
  // env - Your environment variables
  // ctx - Execution context for waitUntil
}
```

### ScheduledEvent Properties [#scheduledevent-properties]

```typescript
interface ScheduledEvent {
  scheduledTime: number;  // Unix timestamp in milliseconds
  cron: string;           // The cron pattern that triggered this event
}
```

### Example: Using Event Data [#example-using-event-data]

```typescript
export default {
  fetch: app.fetch,

  async scheduled(event, env, ctx) {
    const scheduledDate = new Date(event.scheduledTime);

    console.log("Triggered by cron:", event.cron);
    console.log("Scheduled for:", scheduledDate.toISOString());

    // Different logic based on which cron triggered
    if (event.cron === "0 0 * * *") {
      await runDailyReport(env);
    } else if (event.cron === "0 * * * *") {
      await runHourlySync(env);
    }
  },
};
```

---

## Use Cases [#use-cases]

### Daily Report Generation [#daily-report-generation]

Send daily reports via email or save to storage:

```typescript
async scheduled(event, env, ctx) {
  if (event.cron !== "0 9 * * *") return; // Only run at 9 AM

  const report = await generateDailyReport(env);

  // Send report via your API
  await fetch(`${env.OMNIBASE_API_URL}/api/v1/reports`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${env.API_KEY}`,
    },
    body: JSON.stringify(report),
  });

  console.log("Daily report sent successfully");
}
```

### Cleanup Jobs [#cleanup-jobs]

Remove expired data periodically:

```typescript
async scheduled(event, env, ctx) {
  // Run every hour to clean up expired sessions
  const response = await fetch(
    `${env.OMNIBASE_API_URL}/api/v1/sessions/cleanup`,
    {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${env.API_KEY}`,
      },
    }
  );

  const result = await response.json();
  console.log(`Cleaned up ${result.deletedCount} expired sessions`);
}
```

### API Polling [#api-polling]

Poll external APIs and sync data:

```typescript
async scheduled(event, env, ctx) {
  // Poll external API every 15 minutes
  const data = await fetch("https://api.external.com/data");
  const json = await data.json();

  // Sync to your Omnibase API
  await fetch(`${env.OMNIBASE_API_URL}/api/v1/sync`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${env.API_KEY}`,
    },
    body: JSON.stringify(json),
  });

  console.log("Data synced from external API");
}
```

### Cache Warming [#cache-warming]

Pre-warm caches before peak traffic:

```typescript
async scheduled(event, env, ctx) {
  // Warm cache before business hours (8 AM)
  if (event.cron !== "0 8 * * *") return;

  const endpoints = [
    "/api/v1/products",
    "/api/v1/categories",
    "/api/v1/featured",
  ];

  for (const endpoint of endpoints) {
    await fetch(`${env.OMNIBASE_API_URL}${endpoint}`, {
      headers: {
        "Authorization": `Bearer ${env.API_KEY}`,
      },
    });
  }

  console.log("Cache warmed successfully");
}
```

---

## Environment Variables [#environment-variables]

Access environment variables the same way as in your edge functions:

```typescript
type EnvVars = {
  OMNIBASE_API_URL: string;
  DATABASE_URL: string;
  API_KEY: string;
};

export default {
  fetch: app.fetch,

  async scheduled(event, env: EnvVars, ctx) {
    // Use environment variables
    const apiUrl = env.OMNIBASE_API_URL;
    const apiKey = env.API_KEY;

    await performTask(apiUrl, apiKey);
  },
};
```

Environment variables are configured in `omnibase/environments/.env.production` (or your target environment) and automatically injected when you deploy.

---

## Testing Locally [#testing-locally]

You can test cron triggers locally by calling your scheduled handler manually:

```typescript
// Add a test endpoint for local development
app.get("/test-cron", async (c) => {
  // Manually invoke the scheduled handler
  const event = {
    scheduledTime: Date.now(),
    cron: "0 * * * *",
  };

  await scheduled(event, c.env, {} as ExecutionContext);

  return c.json({ message: "Cron job executed" });
});

export default {
  fetch: app.fetch,
  async scheduled(event, env, ctx) {
    await performScheduledTask(env);
  },
};
```

Then trigger it manually:

```bash
# Start local development
cd omnibase/workers
bun dev

# In another terminal, trigger the test endpoint
curl http://localhost:8787/test-cron
```

<Component type="warn">
Remove test endpoints before deploying to production to avoid unauthorized executions.
</Component>

---

## Best Practices [#best-practices]

### Use waitUntil for Background Tasks [#use-waituntil-for-background-tasks]

Extend execution beyond the scheduled handler:

```typescript
async scheduled(event, env, ctx) {
  // Process immediately
  const result = await quickTask();

  // Process in background (doesn't block)
  ctx.waitUntil(slowBackgroundTask(env));

  console.log("Scheduled handler completed, background task running");
}
```

### Handle Errors Gracefully [#handle-errors-gracefully]

Always catch and log errors:

```typescript
async scheduled(event, env, ctx) {
  try {
    await performTask(env);
    console.log("Task completed successfully");
  } catch (error) {
    console.error("Task failed:", error.message);

    // Optional: Send error notification
    await notifyError(env, error);
  }
}
```

### Keep Tasks Lightweight [#keep-tasks-lightweight]

Cron jobs have execution time limits. For long-running tasks, break them into smaller chunks or use queues:

```typescript
// ✅ Good: Quick task
async scheduled(event, env, ctx) {
  const items = await fetchItemsToProcess(env);

  // Queue each item for background processing
  for (const item of items) {
    ctx.waitUntil(processItem(item, env));
  }
}

// ❌ Bad: Long-running synchronous task
async scheduled(event, env, ctx) {
  const items = await fetchItemsToProcess(env);

  // This might timeout
  for (const item of items) {
    await processItem(item, env); // Blocks on each item
  }
}
```

### Add Logging [#add-logging]

Log execution for debugging and monitoring:

```typescript
async scheduled(event, env, ctx) {
  const startTime = Date.now();

  console.log("Cron started:", {
    cron: event.cron,
    scheduledTime: new Date(event.scheduledTime).toISOString(),
  });

  try {
    await performTask(env);

    const duration = Date.now() - startTime;
    console.log(`Cron completed in ${duration}ms`);
  } catch (error) {
    console.error("Cron failed:", error);
    throw error;
  }
}
```

---

## Deployment [#deployment]

Deploy your worker with cron schedules:

```bash
# Deploy to specific environment
omnibase cloud workers deploy --env production
omnibase cloud workers deploy --env staging
omnibase cloud workers deploy --env dev
```

The CLI automatically reads cron schedules from `wrangler.toml` and configures them on Cloudflare Workers.

<Component type="info">
Cron schedules are updated every time you deploy. You don't need to manually configure them separately.
</Component>

---

## Limitations [#limitations]

- **Minimum Interval**: Cron jobs run at most once per minute
- **Execution Time**: Cron handlers have the same CPU time limits as regular Workers requests
- **No Guarantees on Exact Time**: Cron jobs run within a few seconds of the scheduled time, but exact timing isn't guaranteed
- **No Overlapping Executions**: If a cron job is still running when the next execution is scheduled, the new execution is skipped

---

## Next Steps [#next-steps]

- [Edge Functions](/docs/guides/workers/edge-functions) — Learn about HTTP-triggered workers
- [Queues](/docs/guides/workers/queues) — Process background jobs with guaranteed delivery (coming soon)
- [Hono Documentation](https://hono.dev/) — Explore the Hono framework

# Edge Functions (/guides/workers/edge-functions)

Omnibase Workers are serverless functions that run on [Cloudflare Workers](https://workers.cloudflare.com/) using the [Hono](https://hono.dev/) web framework. Deploy globally distributed APIs that respond in milliseconds.

## Quick Start [#quick-start]

<Component>
<Component>
### Initialize Your Project [#initialize-your-project]

If you haven't already initialized Omnibase, create a new project:

```bash
omnibase init
```

This creates an `omnibase/workers/` directory with a starter edge function.
</Component>

<Component>
### Project Structure [#project-structure]

Your workers directory contains:

```
omnibase/workers/
├── src/
│   └── index.ts        # Main entry point
├── package.json        # Dependencies
├── wrangler.toml       # Cloudflare Workers config
└── tsconfig.json       # TypeScript config
```
</Component>

<Component>
### Write Your First Function [#write-your-first-function]

Open `omnibase/workers/src/index.ts`:

```typescript
import { Hono } from "hono";
import { cors } from "hono/cors";

type EnvVars = any;

const app = new Hono<{ Bindings: EnvVars }>();

// Enable CORS
app.use("/*", cors());

// Hello world endpoint
app.get("/", (c) => {
  return c.json({
    message: "Hello from the edge!",
    timestamp: new Date().toISOString(),
  });
});

// Example API endpoint
app.get("/api/users/:id", (c) => {
  const userId = c.req.param("id");
  return c.json({
    id: userId,
    name: "John Doe",
    email: "john@example.com",
  });
});

export default {
  fetch: app.fetch,
};
```
</Component>

<Component>
### Local Development [#local-development]

Install dependencies and run locally:

```bash
cd omnibase/workers
bun install
bun dev
```

Your edge function is now running at `http://localhost:8787`
</Component>

<Component>
### Deploy to Omnibase [#deploy-to-omnibase]

Deploy your workers to Omnibase Cloud:

```bash
omnibase cloud workers deploy
```

For specific environments:

```bash
omnibase cloud workers deploy --env production
omnibase cloud workers deploy --env staging
omnibase cloud workers deploy --env dev
```

Your function is now live globally on Cloudflare's edge network.
</Component>
</Component>

---

## Routing [#routing]

Hono provides intuitive routing with automatic parameter parsing:

```typescript
// GET /api/posts
app.get("/api/posts", async (c) => {
  const posts = await fetchPosts();
  return c.json(posts);
});

// GET /api/posts/:id
app.get("/api/posts/:id", async (c) => {
  const id = c.req.param("id");
  const post = await fetchPost(id);
  return c.json(post);
});

// POST /api/posts
app.post("/api/posts", async (c) => {
  const body = await c.req.json();
  const newPost = await createPost(body);
  return c.json(newPost, 201);
});

// PUT /api/posts/:id
app.put("/api/posts/:id", async (c) => {
  const id = c.req.param("id");
  const body = await c.req.json();
  const updated = await updatePost(id, body);
  return c.json(updated);
});

// DELETE /api/posts/:id
app.delete("/api/posts/:id", async (c) => {
  const id = c.req.param("id");
  await deletePost(id);
  return c.json({ success: true });
});
```

---

## Environment Variables [#environment-variables]

Environment variables are managed through Omnibase environment files located in `omnibase/environments/`.

### Configure Environment Variables [#configure-environment-variables]

Add your variables to the environment file for your target environment:

```bash
# omnibase/environments/.env.production
OMNIBASE_API_URL=https://api.yourdomain.com
DATABASE_URL=postgresql://...
API_KEY=your-secret-key
STRIPE_SECRET_KEY=sk_live_...
```

```bash
# omnibase/environments/.env.staging
OMNIBASE_API_URL=https://staging-api.yourdomain.com
DATABASE_URL=postgresql://...
API_KEY=your-staging-key
STRIPE_SECRET_KEY=sk_test_...
```

### Access Environment Variables [#access-environment-variables]

Access them in your worker code via `c.env`:

```typescript
app.get("/api/data", async (c) => {
  const apiKey = c.env.API_KEY;
  const dbUrl = c.env.DATABASE_URL;

  if (!apiKey) {
    return c.json({ error: "Missing API key" }, 401);
  }

  return c.json({ data: "secure data" });
});
```

### TypeScript Types [#typescript-types]

Define your environment variables for type safety:

```typescript
type EnvVars = {
  OMNIBASE_API_URL: string;
  DATABASE_URL: string;
  API_KEY: string;
  STRIPE_SECRET_KEY: string;
};

const app = new Hono<{ Bindings: EnvVars }>();

app.get("/api/secure", async (c) => {
  // Now c.env is fully typed with autocomplete
  const apiUrl = c.env.OMNIBASE_API_URL;
  const apiKey = c.env.API_KEY;

  return c.json({ connected: true });
});
```

<Component type="info">
When you deploy with `omnibase cloud workers deploy --env production`, the CLI automatically reads from `omnibase/environments/.env.production` and injects those variables into your worker.
</Component>

---

## Middleware [#middleware]

Hono makes it easy to add middleware for common tasks:

<Tabs items={["Logging","CORS"]}>
<Tab value="Logging">
```typescript
import { Hono } from "hono";
import { logger } from "hono/logger";

const app = new Hono();

// Log all requests
app.use("*", logger());

app.get("/", (c) => {
  return c.json({ message: "Logged!" });
});
```
</Tab>

<Tab value="CORS">
```typescript
import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();

// Enable CORS for all routes
app.use("/*", cors({
  origin: ["https://yourdomain.com"],
  allowMethods: ["GET", "POST", "PUT", "DELETE"],
  allowHeaders: ["Content-Type", "Authorization"],
  credentials: true,
}));

app.get("/api/data", (c) => {
  return c.json({ data: "accessible cross-origin" });
});
```
</Tab>
</Tabs>

---

## Request & Response [#request--response]

### Reading Request Data [#reading-request-data]

```typescript
// Query parameters
app.get("/search", (c) => {
  const query = c.req.query("q");
  const page = c.req.query("page") || "1";
  return c.json({ query, page });
});

// Request body (JSON)
app.post("/api/data", async (c) => {
  const body = await c.req.json();
  return c.json({ received: body });
});

// Headers
app.get("/info", (c) => {
  const userAgent = c.req.header("user-agent");
  const auth = c.req.header("authorization");
  return c.json({ userAgent, auth });
});

// Route parameters
app.get("/users/:id", (c) => {
  const id = c.req.param("id");
  return c.json({ userId: id });
});
```

### Returning Responses [#returning-responses]

```typescript
// JSON response
app.get("/json", (c) => {
  return c.json({ status: "ok" });
});

// Text response
app.get("/text", (c) => {
  return c.text("Plain text response");
});

// HTML response
app.get("/html", (c) => {
  return c.html("<h1>Hello World</h1>");
});

// Custom status code
app.get("/not-found", (c) => {
  return c.json({ error: "Not found" }, 404);
});

// Redirect
app.get("/redirect", (c) => {
  return c.redirect("/new-location");
});

// Custom headers
app.get("/custom", (c) => {
  return c.json({ data: "value" }, 200, {
    "X-Custom-Header": "custom-value",
    "Cache-Control": "max-age=3600",
  });
});
```

---

## Error Handling [#error-handling]

```typescript
import { Hono } from "hono";

const app = new Hono();

// Global error handler
app.onError((err, c) => {
  console.error(`Error: ${err.message}`);

  return c.json({
    error: "Internal server error",
    message: err.message,
  }, 500);
});

// Not found handler
app.notFound((c) => {
  return c.json({
    error: "Not found",
    path: c.req.path,
  }, 404);
});

// Route-level error handling
app.get("/api/risky", async (c) => {
  try {
    const data = await riskyOperation();
    return c.json(data);
  } catch (error) {
    return c.json({ error: error.message }, 500);
  }
});
```

---

## Common Use Cases [#common-use-cases]

### Proxy to Omnibase API [#proxy-to-omnibase-api]

```typescript
app.get("/api/users", async (c) => {
  const response = await fetch(`${c.env.OMNIBASE_API_URL}/v1/users`, {
    headers: {
      "X-Service-Key": c.env.OMNIBASE_SERVICE_KEY,
    },
  });

  const data = await response.json();
  return c.json(data);
});
```

### Webhook Handler [#webhook-handler]

```typescript
app.post("/webhooks/stripe", async (c) => {
  const signature = c.req.header("stripe-signature");
  const body = await c.req.text();

  // Verify webhook signature
  const event = verifyStripeWebhook(body, signature, c.env.STRIPE_WEBHOOK_SECRET);

  // Handle the event
  switch (event.type) {
    case "payment_intent.succeeded":
      await handlePaymentSuccess(event.data);
      break;
    case "customer.subscription.updated":
      await handleSubscriptionUpdate(event.data);
      break;
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  return c.json({ received: true });
});
```

### Health Check Endpoint [#health-check-endpoint]

```typescript
app.get("/health", (c) => {
  return c.json({
    status: "healthy",
    timestamp: new Date().toISOString(),
    environment: c.env.ENVIRONMENT || "unknown",
  });
});
```

---

## Best Practices [#best-practices]

### Keep Workers Fast [#keep-workers-fast]

Workers are optimized for quick responses. Avoid long-running operations:

```typescript
// ✅ Good: Quick response
app.post("/api/process", async (c) => {
  const data = await c.req.json();
  // Return immediately
  return c.json({ queued: true });
});

// ❌ Bad: Slow operation blocks the worker
app.post("/api/process", async (c) => {
  const data = await c.req.json();
  await slowProcessing(data); // Takes 10+ seconds
  return c.json({ done: true });
});
```

### Use TypeScript [#use-typescript]

Get full type safety and better developer experience:

```typescript
type EnvVars = {
  DATABASE_URL: string;
  API_KEY: string;
};

const app = new Hono<{ Bindings: EnvVars }>();

// c.env is now fully typed
app.get("/", (c) => {
  const dbUrl = c.env.DATABASE_URL; // ✅ Autocomplete works
  return c.json({ connected: true });
});
```

### Handle Errors Gracefully [#handle-errors-gracefully]

Always implement error handling:

```typescript
app.onError((err, c) => {
  console.error(`Error: ${err.message}`);
  return c.json({ error: "Something went wrong" }, 500);
});

app.notFound((c) => {
  return c.json({ error: "Not found" }, 404);
});
```

---

## Next Steps [#next-steps]

- [Hono Documentation](https://hono.dev/) — Learn more about the Hono framework
- [Cloudflare Workers](https://developers.cloudflare.com/workers/) — Explore Workers platform features

<Component type="info">
Need scheduled jobs or background processing? Check out the [Cron Jobs](/docs/guides/workers/cron) and [Queues](/docs/guides/workers/queues) guides (coming soon).
</Component>

# Workers Overview (/guides/workers)

Omnibase Workers provide serverless compute on [Cloudflare Workers](https://workers.cloudflare.com/) using the [Hono](https://hono.dev/) web framework. Build globally distributed APIs, background jobs, and scheduled tasks that run at the edge.

<Component type="info">
A Worker is one kind of [deployment](/guides/deployments) — anything `wrangler` can deploy works, from Hono edge functions to Next.js apps compiled with OpenNext. See the [Deployments guide](/guides/deployments) for how apps are declared in `omnibase.toml`, run locally, and ship to the edge.
</Component>

## What Are Workers? [#what-are-workers]

Workers are lightweight, serverless functions that run on Cloudflare's global network across 300+ cities. They execute close to your users for ultra-low latency and can handle millions of requests per second.

### Key Benefits [#key-benefits]

- **Global Distribution** — Deploy once, run everywhere on Cloudflare's edge
- **Zero Cold Starts** — Instant execution with no warmup time
- **Unlimited Scale** — Automatically scales to handle traffic spikes
- **Low Latency** — Sub-10ms response times globally
- **Built on Standards** — Uses Web APIs (Request/Response) with full TypeScript support

## Features [#features]

<Component>
<Component title="Edge Functions" href="/guides/workers/edge-functions">
HTTP APIs that run globally at the edge with sub-10ms latency
</Component>

<Component title="Cron Jobs" href="/guides/workers/cron">
Scheduled tasks for automated workflows and background processing
</Component>

<Component title="Queues" href="/guides/workers/queues">
Background job processing with guaranteed delivery and automatic retries
</Component>
</Component>

## Quick Start [#quick-start]

```bash
# Initialize Omnibase (scaffolds the sample omnibase/workers/ app)
omnibase init

# Navigate to workers directory
cd omnibase/workers

# Install dependencies
bun install

# Run the app locally (or use `omnibase start` to run the full stack)
bun dev

# Deploy to Omnibase
omnibase cloud workers deploy
```

Your worker will be deployed globally on Cloudflare's edge network via Omnibase.

## Architecture [#architecture]

Omnibase Workers are built with:

- **Hono** — Fast, lightweight web framework (Express-like API)
- **Cloudflare Workers** — Edge runtime with V8 isolates
- **Wrangler** — CLI for development and deployment
- **TypeScript** — Full type safety and autocomplete

```typescript
import { Hono } from "hono";
import { cors } from "hono/cors";

const app = new Hono();

app.use("/*", cors());

app.get("/api/hello", (c) => {
  return c.json({
    message: "Hello from the edge!",
    location: c.req.header("cf-ray"),
  });
});

export default {
  fetch: app.fetch,
};
```

## Project Structure [#project-structure]

```
omnibase/workers/
├── src/
│   └── index.ts        # Main entry point
├── package.json        # Dependencies (Hono, etc.)
├── wrangler.toml       # Cloudflare Workers config
├── tsconfig.json       # TypeScript config
└── .env                # Local environment variables
```

## Use Cases [#use-cases]

### API Endpoints [#api-endpoints]

Build REST APIs that respond in milliseconds globally:

```typescript
app.get("/api/users/:id", async (c) => {
  const userId = c.req.param("id");
  const user = await fetchUser(userId);
  return c.json(user);
});
```

### Webhooks [#webhooks]

Handle incoming webhooks from Stripe, GitHub, etc.:

```typescript
app.post("/webhooks/stripe", async (c) => {
  const event = await c.req.json();
  await processStripeEvent(event);
  return c.json({ received: true });
});
```

### Content Proxying [#content-proxying]

Cache and optimize content at the edge:

```typescript
app.get("/images/:id", async (c) => {
  const id = c.req.param("id");
  const response = await fetch(`https://storage.example.com/${id}`);

  return new Response(response.body, {
    headers: {
      "Cache-Control": "public, max-age=31536000",
    },
  });
});
```

### Edge Redirects [#edge-redirects]

Handle redirects at the edge without hitting your origin:

```typescript
app.get("/old-path", (c) => {
  return c.redirect("/new-path", 301);
});
```

## Environment Variables [#environment-variables]

Environment variables are managed through Omnibase env files in `omnibase/.env.*` — see [Environment Variables & Secrets](/guides/deployments/environment-variables) for build-time injection, `{VAR}` interpolation, and where secrets live.

### Configure Variables [#configure-variables]

Add your variables to the appropriate env file, one per environment:

```bash
# omnibase/.env.local (local dev)
OMNIBASE_API_URL=http://localhost:8080
```

```bash
# omnibase/.env.production (deployed with `--env production`)
OMNIBASE_API_URL=https://api.yourdomain.com
```

### Access in Workers [#access-in-workers]

Access environment variables via `c.env` in your worker code:

```typescript
app.get("/api/data", async (c) => {
  const apiUrl = c.env.OMNIBASE_API_URL;

  return c.json({ connected: true });
});
```

<Component type="info">
When you deploy with `omnibase cloud workers deploy --env production`, the CLI resolves variables from `omnibase/.env.production` and injects them into the build and the packaged worker.
</Component>

## Deployment [#deployment]

### Local Development [#local-development]

Run locally with hot reload:

```bash
cd omnibase/workers
bun dev
```

Access at `http://localhost:8787`

### Deploy to Omnibase [#deploy-to-omnibase]

Deploy your workers to Omnibase Cloud:

```bash
omnibase cloud workers deploy
```

For specific environments:

```bash
omnibase cloud workers deploy --env production
omnibase cloud workers deploy --env staging
omnibase cloud workers deploy --env dev
```

Your worker will be deployed globally on Cloudflare's edge network and accessible at your project's worker URL.

## Best Practices [#best-practices]

### Keep Workers Lightweight [#keep-workers-lightweight]

Workers are designed for fast execution. Avoid heavy processing:

```typescript
// ✅ Good: Quick response with offloading
app.post("/api/process", async (c) => {
  const data = await c.req.json();
  // Queue heavy processing
  await c.env.QUEUE.send({ data });
  return c.json({ queued: true });
});

// ❌ Bad: Heavy processing blocks worker
app.post("/api/process", async (c) => {
  const data = await c.req.json();
  await heavyProcessing(data); // Takes 5+ seconds
  return c.json({ done: true });
});
```

### Use TypeScript [#use-typescript]

Get full type safety and autocomplete:

```typescript
type EnvVars = {
  DATABASE_URL: string;
  API_KEY: string;
};

const app = new Hono<{ Bindings: EnvVars }>();

app.get("/", (c) => {
  // c.env is now fully typed
  const dbUrl = c.env.DATABASE_URL;
  return c.json({ connected: true });
});
```

### Cache Responses [#cache-responses]

Leverage Cloudflare's cache for static responses:

```typescript
app.get("/api/data", async (c) => {
  const cached = await caches.default.match(c.req.url);
  if (cached) return cached;

  const data = await fetchData();
  const response = c.json(data);

  c.executionCtx.waitUntil(
    caches.default.put(c.req.url, response.clone())
  );

  return response;
});
```

## Next Steps [#next-steps]

<Component>
<Component title="Edge Functions" href="/guides/workers/edge-functions">
Learn how to build and deploy edge functions with Hono
</Component>

<Component title="Hono Documentation" href="https://hono.dev/">
Explore Hono's full API and middleware ecosystem
</Component>

<Component title="Cloudflare Workers" href="https://developers.cloudflare.com/workers/">
Deep dive into the Workers platform
</Component>
</Component>

# Queues (/guides/workers/queues)

Process background jobs asynchronously with guaranteed delivery. Perfect for heavy processing, email sending, webhook retries, and any task that shouldn't block your API responses.

## What Are Queues? [#what-are-queues]

Queues enable asynchronous message passing between workers. Send messages to a queue from your API endpoints, then process them in the background with automatic retries and guaranteed delivery.

### Key Features [#key-features]

- **Guaranteed Delivery** — Messages are persisted and retried automatically
- **Batch Processing** — Process multiple messages at once for efficiency
- **Automatic Retries** — Failed messages retry up to 3 times
- **No Infrastructure** — Fully managed by Cloudflare

---

## Quick Start [#quick-start]

<Component>
<Component>
### Configure Queue [#configure-queue]

Add queue configuration to `omnibase/workers/wrangler.toml`:

```toml title="wrangler.toml"
name = "omnibase-edge"
main = "src/index.ts"
compatibility_date = "2024-01-01"

# Producer: Send messages to queue
[[queues.producers]]
queue = "background-jobs"
binding = "JOB_QUEUE"

# Consumer: Process messages from queue
[[queues.consumers]]
queue = "background-jobs"
max_batch_size = 10
```
</Component>

<Component>
### Send Messages (Producer) [#send-messages-producer]

Send messages to the queue from your API:

```typescript title="src/index.ts"
import { Hono } from "hono";

type EnvVars = {
  JOB_QUEUE: Queue;
};

const app = new Hono<{ Bindings: EnvVars }>();

app.post("/api/process", async (c) => {
  const data = await c.req.json();

  // Send to queue for background processing
  await c.env.JOB_QUEUE.send({
    type: "process-data",
    userId: data.userId,
    payload: data,
    timestamp: Date.now(),
  });

  return c.json({ queued: true });
});
```
</Component>

<Component>
### Process Messages (Consumer) [#process-messages-consumer]

Add a queue handler to process messages:

```typescript title="src/index.ts"
export default {
  fetch: app.fetch,

  // Process messages from queue
  async queue(batch, env) {
    for (const message of batch.messages) {
      try {
        const data = message.body;
        console.log("Processing:", data);

        // Your processing logic
        await processJob(data, env);

        // Mark as successfully processed
        message.ack();
      } catch (error) {
        console.error("Job failed:", error);
        // Message will be retried automatically
        message.retry();
      }
    }
  },
};
```
</Component>

<Component>
### Deploy [#deploy]

Deploy your worker with queue configuration:

```bash
omnibase cloud workers deploy --env production
```

Your queue is now active and will process messages in the background.
</Component>
</Component>

---

## Sending Messages [#sending-messages]

### Basic Send [#basic-send]

```typescript
// Send single message
await env.MY_QUEUE.send({ userId: 123, action: "process" });
```

### Batch Send [#batch-send]

Send multiple messages efficiently:

```typescript
// Send multiple messages at once
await env.MY_QUEUE.sendBatch([
  { body: { userId: 1, action: "email" } },
  { body: { userId: 2, action: "email" } },
  { body: { userId: 3, action: "email" } },
]);
```

### With Delay [#with-delay]

Delay message processing:

```typescript
// Process after 60 seconds
await env.MY_QUEUE.send(
  { userId: 123 },
  { delaySeconds: 60 }
);
```

---

## Processing Messages [#processing-messages]

### Message Object [#message-object]

```typescript
interface QueueMessage {
  id: string;              // Unique message ID
  timestamp: Date;         // When message was sent
  body: any;              // Your message data
  ack: () => void;        // Mark as successfully processed
  retry: () => void;      // Retry this message
}
```

### Batch Processing [#batch-processing]

```typescript
async queue(batch: MessageBatch, env: EnvVars) {
  console.log(`Processing ${batch.messages.length} messages`);

  for (const message of batch.messages) {
    try {
      await handleMessage(message.body, env);
      message.ack();
    } catch (error) {
      console.error("Failed:", error);
      message.retry();
    }
  }
}
```

### Parallel Processing [#parallel-processing]

Process messages concurrently for speed:

```typescript
async queue(batch, env) {
  await Promise.all(
    batch.messages.map(async (message) => {
      try {
        await handleMessage(message.body, env);
        message.ack();
      } catch (error) {
        message.retry();
      }
    })
  );
}
```

---

## Use Cases [#use-cases]

### Email Sending [#email-sending]

Don't block API responses while sending emails:

```typescript
// API endpoint - responds immediately
app.post("/api/signup", async (c) => {
  const { email, name } = await c.req.json();

  // Queue welcome email
  await c.env.EMAIL_QUEUE.send({
    type: "welcome-email",
    email,
    name,
  });

  return c.json({ success: true });
});

// Queue consumer - sends email in background
async queue(batch, env) {
  for (const message of batch.messages) {
    const { type, email, name } = message.body;

    if (type === "welcome-email") {
      await sendEmail(email, `Welcome ${name}!`, env);
      message.ack();
    }
  }
}
```

### Webhook Processing [#webhook-processing]

Retry failed webhooks automatically:

```typescript
app.post("/api/webhooks/stripe", async (c) => {
  const event = await c.req.json();

  await c.env.WEBHOOK_QUEUE.send({
    provider: "stripe",
    event,
  });

  return c.json({ received: true });
});
```

### Data Processing [#data-processing]

Handle heavy computations in the background:

```typescript
app.post("/api/reports/generate", async (c) => {
  const { userId, reportType } = await c.req.json();

  await c.env.REPORT_QUEUE.send({
    userId,
    reportType,
    requestedAt: Date.now(),
  });

  return c.json({ status: "processing" });
});
```

---

## Best Practices [#best-practices]

### Always ack() or retry() [#always-ack-or-retry]

Always explicitly handle each message:

```typescript
for (const message of batch.messages) {
  try {
    await processMessage(message.body);
    message.ack();  // ✅ Mark as done
  } catch (error) {
    message.retry(); // ✅ Retry later
  }
}
```

### Use Batch Processing [#use-batch-processing]

Process multiple messages together when possible:

```typescript
async queue(batch, env) {
  // Extract all user IDs
  const userIds = batch.messages.map(m => m.body.userId);

  // Fetch data once for all users
  const users = await fetchUsers(userIds, env);

  // Process all messages
  for (const message of batch.messages) {
    const user = users.find(u => u.id === message.body.userId);
    await process(user);
    message.ack();
  }
}
```

### Add Message Metadata [#add-message-metadata]

Include useful debugging information:

```typescript
await env.MY_QUEUE.send({
  type: "process-order",
  orderId: 123,
  userId: 456,
  timestamp: Date.now(),
  source: "api",
});
```

### Handle Retries Gracefully [#handle-retries-gracefully]

Design idempotent handlers that can safely retry:

```typescript
async queue(batch, env) {
  for (const message of batch.messages) {
    const { orderId } = message.body;

    // Check if already processed
    const exists = await checkIfProcessed(orderId, env);
    if (exists) {
      message.ack();
      continue;
    }

    try {
      await processOrder(orderId, env);
      message.ack();
    } catch (error) {
      message.retry();
    }
  }
}
```

---

## Configuration [#configuration]

### Multiple Queues [#multiple-queues]

Use different queues for different job types:

```toml title="wrangler.toml"
[[queues.producers]]
queue = "emails"
binding = "EMAIL_QUEUE"

[[queues.producers]]
queue = "webhooks"
binding = "WEBHOOK_QUEUE"

[[queues.consumers]]
queue = "emails"
max_batch_size = 5

[[queues.consumers]]
queue = "webhooks"
max_batch_size = 10
```

### Batch Size [#batch-size]

Control how many messages are processed at once:

```toml
[[queues.consumers]]
queue = "my-queue"
max_batch_size = 10  # Process up to 10 messages per batch
```

<Component type="info">
Larger batch sizes improve throughput but increase processing time. Start with 10 and adjust based on your needs.
</Component>

---

## Deployment [#deployment]

Deploy your worker with queue configuration:

```bash
omnibase cloud workers deploy --env production
```

Queues are automatically created when you deploy. No additional setup required.

---

## Next Steps [#next-steps]

- [Edge Functions](/docs/guides/workers/edge-functions) — Build APIs that send messages to queues
- [Cron Jobs](/docs/guides/workers/cron) — Schedule periodic jobs that use queues
- [Cloudflare Queues](https://developers.cloudflare.com/queues/) — Deep dive into the platform

# Next.js Changelog (/nextjs)

**Latest: v0.10.0**

[Read the Next.js v0.10.0 docs](/nextjs/0.10.0)

All Next.js releases are listed below, newest first. Each version links to its docs, or to its GitHub release when the docs for that version are no longer published. See the [changelog for every package](/changelog).

## v0.10.0 [#v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.10.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.9.1...nextjs-v0.10.0)

**Bug Fixes**

* **auth:** Logout removes `omnibase_session_token` instead of legacy `ory_*` [5a1652e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5a1652efef67754aecf976809fe54b57bb850d64)

**Features**

* proxy PostgREST through the API and remove client-held PostgREST tokens [49d317f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/49d317f00f94a78ac71e719c08ee8f76622e8553)

## v0.9.1 [#v091]

[Docs](/nextjs/0.9.1) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.9.0...nextjs-v0.9.1)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)

## v0.9.0 [#v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.9.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.4...nextjs-v0.9.0)

**Features**

* **nextjs:** support custom cookie domain for session token exchange [35cafd4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35cafd403f5de28bf9d0a76c8ff958fbebe157d2)

## v0.8.4 [#v084]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.4) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.3...nextjs-v0.8.4)

**Bug Fixes**

* **nextjs:** guard against empty session exchange codes [555e655](https://github.com/PhoenixSolutionsGroup/omnibase/commit/555e655a1afdb8bd015f8c8908dd29354cba4565)

## v0.8.3 [#v083]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.3) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.2...nextjs-v0.8.3)

**Bug Fixes**

* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)

## v0.8.2 [#v082]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.2) · 2026-01-21 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.1...nextjs-v0.8.2)

**Bug Fixes**

* **nextjs:** add JWT expiration checking in PostgREST middleware [bb5795d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bb5795df4ac2048d9f4bac479d10d704a731227b)

## v0.8.1 [#v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.8.0...nextjs-v0.8.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)
* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)
* **sdk/nextjs:** use @ory/client-fetch types for flow compatibility [a7411b3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/a7411b3d9aa15bd1496c4bfdd53796687082fc57)

## v0.8.0 [#v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.8.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.7.0...nextjs-v0.8.0)

**Bug Fixes**

* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)

**Features**

* **sdk/nextjs:** add error flow support and verification redirect [6440955](https://github.com/PhoenixSolutionsGroup/omnibase/commit/64409557d5c41468a6aba3918268116da8d0eb7e)

## v0.7.0 [#v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/nextjs-v0.7.0) · 2026-01-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/nextjs-v0.6.5...nextjs-v0.7.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)

## v0.6.5 [#v065]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.5) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.4...@omnibase/nextjs@0.6.5)

**Bug Fixes**

* remove api_url from FlowRouterProps interface [af58e1f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/af58e1f6c004db0e7e3550360472b8ccd21dba0c)

## v0.6.4 [#v064]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.4) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.3...@omnibase/nextjs@0.6.4)

**Bug Fixes**

* env var issues [bdfe006](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bdfe006ab5823f1b5595301dea2c049c55c51553)

## v0.6.3 [#v063]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.3) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.2...@omnibase/nextjs@0.6.3)

**Note:** Version bump only for package @omnibase/nextjs

## v0.6.2 [#v062]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.2) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.6.0...@omnibase/nextjs@0.6.2)

**Bug Fixes**

* workspace dep [873ec22](https://github.com/PhoenixSolutionsGroup/omnibase/commit/873ec22664a213e0853fc3b80482c3f1c7a64012)

## v0.6.0 [#v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fnextjs%400.6.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/nextjs@0.5.0...@omnibase/nextjs@0.6.0)

**Code Refactoring**

* **nextjs:** derive auth URL from api_url and remove server action exports [cd4b975](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cd4b97570d861ea2cfa4a4c60118a0d30ba1f212)

**BREAKING CHANGES**

* **nextjs:** The /auth/permissions and /auth/tenants exports have been removed. Auth flow functions (getLoginFlow, getRegistrationFlow, etc.) now require an api_url parameter. Migration: pass process.env.NEXT_PUBLIC_OMNIBASE_API_URL as api_url to all auth flow functions.

## v0.5.2 [#v052]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/nextjs/CHANGELOG.md)

**Patch Changes**

- Updated auth url to get derived from api_url

## v0.5.0 [#v050]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/nextjs/CHANGELOG.md)

**Minor Changes**

- 2971db8: Added API's to update user roles in tenant
- 065f048: Added Protected Route utility function to enforce auth sessions

**Patch Changes**

- daf020a: Fixed edge case where middleware would fail for new users before creating a tenant
- Updated dependencies [2971db8]
  - @omnibase/core-js@0.6.0

# Overview (/overview)

Complete documentation for the Omnibase platform. Each product has its own versioned reference alongside the shared guides and concepts.

<Component type="info">
API references are generated from the OpenAPI spec. SDK and component references are generated from their source packages.
</Component>

## Products [#products]

<Component>
<Component href="/api" title="REST API">
Endpoints, request schemas, and generated JS and Go SDKs
</Component>

<Component href="/cli" title="CLI">
Project management, deployments, and administrative commands
</Component>

<Component href="/nextjs" title="Next.js">
Authentication, session management, and middleware helpers
</Component>

<Component href="/react" title="React">
Hooks and components for authenticated interfaces
</Component>

<Component href="/shadcn" title="Shadcn">
Pre-built UI components for authentication and tenant management
</Component>
</Component>

## Learn [#learn]

<Component>
<Component href="/guides/quickstart" title="Guides">
Getting started, configuration, and deployment tutorials
</Component>

<Component href="/concepts/tenants" title="Concepts">
Tenancy, permissions, billing, and platform architecture
</Component>
</Component>

# react (/react/0.3.7)

**React SDK for OmniBase authentication and session management**

The OmniBase React SDK provides React 19+ hooks, components, and context providers for integrating Ory Kratos authentication flows into your React applications. Built on top of `@omnibase/core-js`, it delivers type-safe session management, route protection, and seamless authentication state handling.

![npm version](https://img.shields.io/npm/v/@omnibase/react)
![License](https://img.shields.io/npm/l/@omnibase/react)
![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)

## Features [#features]

| Feature | Description | Documentation |
|---------|-------------|---------------|
| Session Management | React hook for accessing user session with loading states | [Session Docs](https://docs.omnibase.dev) |
| Authentication Context | Provider component for app-wide authentication configuration | [Context Docs](https://docs.omnibase.dev) |
| Route Protection | Component-based client-side route guards | [Protection Docs](https://docs.omnibase.dev) |
| Direct Ory Access | Low-level hook for custom authentication flows | [API Reference](https://docs.omnibase.dev) |
| Type Safety | Full TypeScript definitions with comprehensive type coverage | [Types Reference](https://docs.omnibase.dev) |

## Quick Start [#quick-start]

```tsx
import { AuthClientProvider, useSession } from '@omnibase/react';

function App() {
  return (
    <AuthClientProvider basePath="http://localhost:4000">
      <Dashboard />
    </AuthClientProvider>
  );
}

function Dashboard() {
  const { session, loading } = useSession();

  if (loading) return <div>Loading...</div>;
  if (!session || !session.active) return <div>Please log in</div>;

  return <div>Welcome, {session.identity.traits.email}!</div>;
}
```

## Installation [#installation]

```bash
# npm
npm install @omnibase/react

# yarn
yarn add @omnibase/react

# pnpm
pnpm add @omnibase/react

# bun
bun add @omnibase/react
```

## Modules Overview [#modules-overview]

The SDK is organized into three main modules:

- **Context** - `AuthClientProvider` for app-wide authentication configuration and `useAuth()` for accessing the Ory Kratos client instance
- **Hooks** - `useSession()` for session state management with automatic loading and error handling
- **Components** - `ProtectedRoute` for client-side route protection with customizable redirect behavior

## Complete Workflow Example [#complete-workflow-example]

```tsx
import { 
  AuthClientProvider, 
  useSession, 
  useAuth,
  ProtectedRoute 
} from '@omnibase/react';
import { useRouter } from 'next/navigation';

// 1. Wrap your app with the provider
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthClientProvider basePath={process.env.NEXT_PUBLIC_API_URL!}>
      {children}
    </AuthClientProvider>
  );
}

// 2. Use session hook for authenticated components
function UserProfile() {
  const { session, loading } = useSession();

  if (loading) return <div>Loading profile...</div>;
  
  if (!session?.active) {
    return <div>Not authenticated</div>;
  }

  return (
    <div>
      <h1>{session.identity.traits.email}</h1>
      <p>User ID: {session.identity.id}</p>
    </div>
  );
}

// 3. Protect routes with ProtectedRoute component
function DashboardPage() {
  const router = useRouter();

  return (
    <ProtectedRoute
      onInvalidSession={() => {
        router.push('/auth/login');
        return null;
      }}
    >
      <div>
        <h1>Protected Dashboard</h1>
        <UserProfile />
      </div>
    </ProtectedRoute>
  );
}

// 4. Use direct Ory access for custom flows
function LogoutButton() {
  const ory = useAuth();

  const handleLogout = async () => {
    const { data } = await ory.createBrowserLogoutFlow();
    window.location.href = data.logout_url;
  };

  return <button onClick={handleLogout}>Sign Out</button>;
}
```

## Error Handling [#error-handling]

The `useSession()` hook provides consistent error handling with loading states:

```tsx
function SecureComponent() {
  const { session, loading } = useSession();

  // Handle loading state
  if (loading) {
    return <div>Verifying session...</div>;
  }

  // Handle unauthenticated or inactive session
  if (!session || !session.active) {
    return <div>Access denied. Please log in.</div>;
  }

  // Session is valid and active
  return <div>Secure content for {session.identity.traits.email}</div>;
}
```

## Environment Configuration [#environment-configuration]

```bash
# Required: OmniBase API endpoint
NEXT_PUBLIC_API_URL=https://your-api-endpoint.com

# Or pass directly to AuthClientProvider
# basePath="https://your-api-endpoint.com"
```

## Environment Support [#environment-support]

| Environment | Status | Notes |
|-------------|--------|-------|
| React 19+ | ✅ | Required peer dependency |
| React 18 | ❌ | Not supported |
| TypeScript | ✅ | Full type definitions included |
| Next.js | ✅ | Works with App Router and Pages Router |
| Vite | ✅ | Full compatibility |
| Create React App | ✅ | Full compatibility |
| ESM/CJS | ✅ | Both module formats supported |

## Related Packages [#related-packages]

- **[@omnibase/core-js](https://www.npmjs.com/package/@omnibase/core-js)** - Core SDK with all API methods for authentication, tenants, and database operations
- **[@omnibase/shadcn](https://www.npmjs.com/package/@omnibase/shadcn)** - Pre-built authentication UI components with shadcn/ui integration
- **[@omnibase/nextjs](https://www.npmjs.com/package/@omnibase/nextjs)** - Next.js optimized SDK with middleware and server component support

## API Reference [#api-reference]

For detailed API documentation including all hooks, components, and types, visit the [full API reference](https://docs.omnibase.dev).

## License [#license]

MIT

# React Changelog (/react)

**Latest: v0.3.7**

[Read the React v0.3.7 docs](/react/0.3.7)

All React releases are listed below, newest first. Each version links to its docs, or to its GitHub release when the docs for that version are no longer published. See the [changelog for every package](/changelog).

## v0.3.7 [#v037]

[Docs](/react/0.3.7) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.6...react-v0.3.7)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)

## v0.3.6 [#v036]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.6) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.5...react-v0.3.6)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)

## v0.3.5 [#v035]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.5) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.4...react-v0.3.5)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)

## v0.3.4 [#v034]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.4) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.3...react-v0.3.4)

**Bug Fixes**

* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)

## v0.3.3 [#v033]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.3) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.2...react-v0.3.3)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)

## v0.3.2 [#v032]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.2) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.1...react-v0.3.2)

**Bug Fixes**

* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)

## v0.3.1 [#v031]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.1) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.3.0...react-v0.3.1)

**Bug Fixes**

* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

## v0.3.0 [#v030]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/react-v0.3.0) · 2026-01-05 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/react-v0.2.2...react-v0.3.0)

**Bug Fixes**

* **api:** add missing return after error in UpdateConfig handler [57a6e29](https://github.com/PhoenixSolutionsGroup/omnibase/commit/57a6e29d860e1ee3649e30ce0b61b747e6ed0b00)
* **api:** add webhook duplicate URL and empty event validation [6ec19ee](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6ec19ee921f1895f908cf85f2bff815a554eafd9)
* **api:** change price amount type to float64 for decimal support [7b072e4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/7b072e48f5611311ea169d8188e7cd4b352d97fa)
* **api:** improve Stripe error handling and invoice ID validation [4785ec3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4785ec3fc1a5450bd6f12f43c88c37be47575dac)
* **api:** resolve contract test failures for Stripe endpoints [6faea3a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/6faea3af2116fb86ce6f4e54bc9293e65008bfb3)
* **api:** return empty array instead of null for tenant users [091058f](https://github.com/PhoenixSolutionsGroup/omnibase/commit/091058f5f5ee8dc9a9a96ffd383bc54cd8227918)
* **api:** treat Keto 400 as 404 for relationship deletion [79df0c9](https://github.com/PhoenixSolutionsGroup/omnibase/commit/79df0c99012ca8d9868550dce4c4374ad312bf26)
* **ci:** also show logs on workflow cancellation [19a56b5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/19a56b505e409f7e299df6efa9cdbe648113feb0)
* **ci:** call scripts directly in release-api-prepare [da13938](https://github.com/PhoenixSolutionsGroup/omnibase/commit/da13938eb460eeeff6aa164ee1a5796d98a3d7e2)
* **ci:** improve Auth readiness checks and add failure logging [2b35ae8](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2b35ae8ffd52c80a7af67c78d39d31bfbd692ba8)
* **ci:** improve caching in release workflow [c48ce58](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c48ce58d5bd47c9eb317e392fc748a83c9eaa154)
* **ci:** improve Keto readiness checks to prevent test failures [965d700](https://github.com/PhoenixSolutionsGroup/omnibase/commit/965d700659255806bb31987c8e77a4273e72471c)
* **ci:** serialize release jobs to prevent race conditions [ed2e043](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ed2e04324b832c84874d7544ecd6f3845ba4fdf8)
* **ci:** update node version and fix ES module errors in release workflow [bf97a60](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bf97a60828da514a5b575ab94ca25033abfabc61)
* **ci:** upgrade to Node 24 for npm trusted publishing [cf5dc10](https://github.com/PhoenixSolutionsGroup/omnibase/commit/cf5dc10128c887b0e439888aa5ad4ec46c754393)
* **ci:** use jq instead of npm for SDK version update [20dde0e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/20dde0e7894893c492ce141156e01f03456b14f6)
* **cli:** add default values for required Kratos environment variables [40e99aa](https://github.com/PhoenixSolutionsGroup/omnibase/commit/40e99aae14111d3733bdf34b6a6a5da4e6635417)
* **cli:** add missing adm-zip dependency [145df41](https://github.com/PhoenixSolutionsGroup/omnibase/commit/145df41ded35c64a80b3da57face700efaba270c)
* **payments:** return proper HTTP status codes for Stripe errors [3f46cad](https://github.com/PhoenixSolutionsGroup/omnibase/commit/3f46cad9fd61120ee9d376b131e398911f93370c)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **tests:** increase schemathesis workers and rate limit [1d0f0b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/1d0f0b6ce6be46f4b4232af809e69393302d3dfb)

**Features**

* **api:** add config lookup endpoints for price/product/meter [b11b30e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/b11b30e33a5da23a7e45c5cefa4749685daa41db)
* **api:** add get single tenant subscription endpoint [2ce8193](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2ce8193f660a9bd7c6fdbebb9ce0461fc17be024)
* **api:** add invoice line item with price ID endpoint [abfea49](https://github.com/PhoenixSolutionsGroup/omnibase/commit/abfea49e4fbacb5b13a2fa5e3d6919ae4b890208)
* **cli:** add environment variable expansion for webhook URLs [c62dedd](https://github.com/PhoenixSolutionsGroup/omnibase/commit/c62dedd58f0bb99bd3dbd8b290a485b8dc19186f)
* **dashboard:** add subscription pricing configuration [260feb3](https://github.com/PhoenixSolutionsGroup/omnibase/commit/260feb3832bb172435690b736b9ebf135604817c)
* **dashboard:** rewrite provisioning form for new deployment options API [839d225](https://github.com/PhoenixSolutionsGroup/omnibase/commit/839d225cfe7d3f426a6dec79786dc2036fa53486)
* **payments:** consolidate provider pricing configs and add deployment tracking [d2b45c4](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d2b45c461189d14d109040ff3391b8e129193e14)
* **permissions:** add tenant owner role management permissions [46fa406](https://github.com/PhoenixSolutionsGroup/omnibase/commit/46fa40642988a1329029d6890ab534f24b98a852)
* **stripe:** support multiple webhooks with pull and cleanup [f8dea9d](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8dea9d31909be9541203a873a0aa9a92f737b99)

## v0.2.2 [#v022]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Freact%400.2.2) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/react@0.2.0...@omnibase/react@0.2.2)

**Bug Fixes**

* **react:** update Session type import to use @ory/client [233673c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/233673c9dd41811bddd9ea106214652fdc7be74e)

## v0.2.1 [#v021]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Freact%400.2.1) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/react@0.2.0...@omnibase/react@0.2.1)

**Bug Fixes**

* **react:** update Session type import to use @ory/client [233673c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/233673c9dd41811bddd9ea106214652fdc7be74e)

## v0.2.0 [#v020]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/framework/react/CHANGELOG.md)

**Minor Changes**

- 065f048: Added Protected Route component to enforce auth sessions

**Patch Changes**

- Updated dependencies [2971db8]
  - @omnibase/core-js@0.6.0

# Roadmap (/roadmap)

See what's planned for Omnibase. Features are subject to change based on community feedback.

## Open Source [#open-source]

<Steps>
<Step>
### Email Service [#email-service]

Send emails directly via the Omnibase REST API. Integrate transactional emails into your applications without third-party services.
</Step>

<Step>
### Redis Service [#redis-service]

Built-in Redis support for caching, sessions, and real-time features. Managed alongside your database with zero configuration.
</Step>

<Step>
### Database Events [#database-events]

Subscribe to real-time database changes. Get notified when tables, columns, or rows are created, updated, or deleted. Perfect for building reactive applications.
</Step>
</Steps>

## Managed Hosting [#managed-hosting]

<Steps>
<Step>
### GitHub Branch Sync [#github-branch-sync]

Automatic database branching synced with your GitHub branches. Each PR gets its own isolated database environment for testing.
</Step>

<Step>
### Custom Email Domains [#custom-email-domains]

Send emails from your own domain. Full DNS configuration and SPF/DKIM setup included for maximum deliverability.
</Step>
</Steps>

# Self-Hosting (/self-hosting)

<Callout type="info">
**Coming Soon**

Comprehensive self-hosting documentation is in progress. Check back soon for detailed guides on:

- Docker Compose setup
- Environment configuration
- Production deployment options
- Scaling and high availability
</Callout>

In the meantime, Omnibase is designed to be self-hostable from day one.

# Shadcn Changelog (/shadcn)

**Latest: v0.10.0**

[Read the Shadcn v0.10.0 docs](/shadcn/0.10.0)

All Shadcn releases are listed below, newest first. Each version links to its docs, or to its GitHub release when the docs for that version are no longer published. See the [changelog for every package](/changelog).

## v0.10.0 [#v0100]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.10.0) · 2026-11-27 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.9.1...shadcn-v0.10.0)

**Bug Fixes**

* dark mode auth page [ff1cef5](https://github.com/PhoenixSolutionsGroup/omnibase/commit/ff1cef5439e82b44dab227e1399ad4de6af406b6)
* tenant-switch bg color [39720ed](https://github.com/PhoenixSolutionsGroup/omnibase/commit/39720ed25cce38d8650d029fd31f0cfba5529c2a)

**Features**

* add icons to oidc [5a875d0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/5a875d053aef58ee51829c38db99d501d23e4e3e)
* **stripe:** depricate stripe endpoints for new stripe proxy  ([#210](https://github.com/PhoenixSolutionsGroup/omnibase/issues/210)) [2d6d400](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2d6d400564bdc6e00ea3a8d4d4cfa0de79621bc9)
* update colors to unify [265717b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/265717b56106f9e25ca57256c5bd8e39196e54ce)
* update registration form [0e66195](https://github.com/PhoenixSolutionsGroup/omnibase/commit/0e661956c7b500691660358dda5e93a817788af5)
* update sdk button and card ui [2cdd899](https://github.com/PhoenixSolutionsGroup/omnibase/commit/2cdd8995281256df1b01ba2d627925012624764b)
* update tenant select sdk ui [d8a580c](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d8a580c2e5b3f6301656f2087a66e080d744a156)

## v0.9.1 [#v091]

[Docs](/shadcn/0.9.1) · 2026-10-29 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.9.0...shadcn-v0.9.1)

**Bug Fixes**

* **release:** stamp core-js version before packing npm packages [bcf117e](https://github.com/PhoenixSolutionsGroup/omnibase/commit/bcf117ec838e5c5b797a0222ac75180e9aa46b1b)

## v0.9.0 [#v090]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.9.0) · 2026-10-11 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.2...shadcn-v0.9.0)

**Features**

* add "tree" mode for role-creator [88fa038](https://github.com/PhoenixSolutionsGroup/omnibase/commit/88fa038df6c59dd5a4bc60380363015ee3f02818)

## v0.8.2 [#v082]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.2) · 2026-09-16 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.1...shadcn-v0.8.2)

**Bug Fixes**

* **shadcn:** trim identifier before password login [d928ae6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d928ae628db527ff20d698ec1c7f9ebdbae1f253)

## v0.8.1 [#v081]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.1) · 2026-07-24 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.8.0...shadcn-v0.8.1)

**Bug Fixes**

* Dashboard Patches ([#48](https://github.com/PhoenixSolutionsGroup/omnibase/issues/48)) [9c62ebb](https://github.com/PhoenixSolutionsGroup/omnibase/commit/9c62ebb14fbff33704be291e98dc40acad1ae476)

## v0.8.0 [#v080]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.8.0) · 2026-02-06 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.2...shadcn-v0.8.0)

**Features**

* **shadcn:** add PermissionsSelectorTree component [e749bf0](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e749bf0e5ef3e3a5c3313887d11c3947bf977db4)

## v0.7.2 [#v072]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.2) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.1...shadcn-v0.7.2)

**Bug Fixes**

* **release:** use find instead of glob for .d.ts file check [38ea742](https://github.com/PhoenixSolutionsGroup/omnibase/commit/38ea742fd2735cce8b6dfeeeba26946a7f0f66f1)

## v0.7.1 [#v071]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.1) · 2026-01-15 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.7.0...shadcn-v0.7.1)

**Bug Fixes**

* **release:** build TypeScript declarations before npm publish [45298b6](https://github.com/PhoenixSolutionsGroup/omnibase/commit/45298b6d4b3ddc464760a3361f694ed56526ce2f)

## v0.7.0 [#v070]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/shadcn-v0.7.0) · 2026-01-14 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/shadcn-v0.6.2...shadcn-v0.7.0)

**Bug Fixes**

* **release:** add repository field for npm provenance [d042f55](https://github.com/PhoenixSolutionsGroup/omnibase/commit/d042f55a39e996e6dbc172ffe102de200b81db0d)
* **release:** filter commits by package path in changelogs [35721a1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/35721a19019add4dbf4f64c74ad1c1c6226b0087)
* **release:** remove --provenance flag and use npm token auth [5309948](https://github.com/PhoenixSolutionsGroup/omnibase/commit/53099480197916568874da3a982b55ce0c752a45)
* **release:** use bun publish to resolve workspace dependencies [4885ee1](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4885ee132f9f8735feba5e2d0c55cd8e9773631a)
* **release:** use npm publish with OIDC provenance for trusted publishing [f837221](https://github.com/PhoenixSolutionsGroup/omnibase/commit/f8372211e9d77ee1d7f2059cf1fbe76733b76104)

**Features**

* **sdk/shadcn:** add create tenant option and error form component [4a4724b](https://github.com/PhoenixSolutionsGroup/omnibase/commit/4a4724bef846f57bf617800dba682f007876bc51)

## v0.6.2 [#v062]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.2) · 2026-01-02 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.6.0...@omnibase/shadcn@0.6.2)

**Note:** Version bump only for package @omnibase/shadcn

## v0.6.1 [#v061]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.1) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.6.0...@omnibase/shadcn@0.6.1)

**Note:** Version bump only for package @omnibase/shadcn

## v0.6.0 [#v060]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/releases/tag/%40omnibase%2Fshadcn%400.6.0) · 2026-01-01 · [Compare changes](https://github.com/PhoenixSolutionsGroup/omnibase/compare/@omnibase/shadcn@0.5.9...@omnibase/shadcn@0.6.0)

**Features**

* **shadcn:** add permissions selector component and refactor role creator [e3c3e9a](https://github.com/PhoenixSolutionsGroup/omnibase/commit/e3c3e9a1eef2aca9368368dedc578c9c4aa4fb9a)

## v0.5.10 [#v0510]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Fixed workspace dep issue

## v0.5.9 [#v059]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Updated role creation and added Permissions selector component

## v0.5.8 [#v058]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Fixed Workspace Dep Issue

## v0.5.7 [#v057]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- Updated role-creator for better UX

## v0.4.3 [#v043]

[GitHub release](https://github.com/PhoenixSolutionsGroup/omnibase/blob/main/sdk/component/shadcn/CHANGELOG.md)

**Patch Changes**

- 5b645b7: Added `login_url` to RegistrationForm and `register_url` to LoginForm to easily switch between