Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 27 additions & 84 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,99 +1,42 @@
<div align="center">
<img src="frontend/static/n2api-logo.svg" alt="N2API logo" width="112" height="112" />
<h1>N2API</h1>
<p>Personal AI API/account gateway for self-hosted use.</p>
<p><strong>N Sources, One API.</strong></p>
<p>A self-hosted AI API gateway for API-key upstreams.</p>
<p>
<a href="https://github.com/KnowSky404/N2API/wiki">Documentation</a> ·
<a href="https://github.com/KnowSky404/N2API/wiki/Getting-Started">Getting started</a> ·
<a href="https://github.com/KnowSky404/N2API/releases">Releases</a>
</p>
</div>

N2API is a personal AI API/account gateway for self-hosted use. It provides a
single OpenAI-compatible entry point for API-key-compatible upstreams, with a compact administration interface for
accounts, routing, client keys, and request logs.

N2API is inspired by sub2api's practical workflow, but it is a new
implementation focused on personal use rather than platform billing or merchant
operations.
N2API brings multiple API-key upstreams behind one OpenAI-compatible endpoint,
with a compact admin UI for accounts, routing, client keys, and request logs.
It is inspired by sub2api's workflow and independently implemented for personal
self-hosting.

## Features

- API-key upstream accounts.
- OpenAI-compatible `/v1/models`, `/v1/responses`, and
`/v1/chat/completions` routes.
- Routing pools, model policies, fallback chains, and sticky sessions.
- Provider health checks, local rate and concurrency guards, and request logs.
- PostgreSQL-backed configuration with encrypted provider credentials.
- Static SvelteKit admin UI served by the Go backend.
- Docker Compose deployment for `linux/amd64` and `linux/arm64`.
- OpenAI-compatible `/v1/models`, `/v1/responses`, and `/v1/chat/completions`, with streaming support.
- Routing pools, model policies, explicit fallback chains, and sticky sessions.
- Account health checks, rate and concurrency limits, client-key budgets, and request logs.
- PostgreSQL-backed configuration and encrypted credentials.
- Go backend with a SvelteKit + Tailwind CSS admin UI; Docker Compose deployment on `linux/amd64` and `linux/arm64`.

## Quick Start

Requirements: Docker Engine with Docker Compose v2, Git, Make, and Bash.

```bash
git clone https://github.com/KnowSky404/N2API.git
cd N2API
cp .env.example .env
```

Replace every `change-me` value in `.env`. At minimum, configure a strong
`POSTGRES_PASSWORD`, `N2API_ADMIN_PASSWORD`, and `N2API_ENCRYPTION_SECRET`, then
start the stack:

```bash
make dev
```

Open `http://localhost:3000` and sign in with the admin credentials from
`.env`. Keep the command open during development; Ctrl-C removes the containers
and network while preserving the database and backups. Services do not restart
automatically. Use `make dev-check` for one-shot verification and
`make dev-stop` for abandoned detached containers. See the
[development lifecycle](docs/development.md) for cleanup and remote access.

The development Compose file explicitly accepts its HTTP public origin,
container wildcard bind, and plaintext private-network database topology;
published-image deployments remain fail-closed until those risks are selected
individually. See the [operator manual](docs/manual.md#host-binding-modes) for
release loopback, LAN, IPv6, dual-stack, and Docker-network-only bindings.

Production deployments must set `N2API_IMAGE` to a readable CalVer tag plus its
exact manifest digest. The release Compose stack applies separate bounded
application and PostgreSQL resources, and optional Compose overrides mount
core and metrics secrets from regular files. Use the repository-local
[`./ops/n2api` workflow](docs/agent-operations.md) for discovery, preflight,
plan/apply deployment, backup, upgrade, verification, and guarded rollback. The
[complete manual](docs/manual.md#deploy-a-published-image) retains lower-level
Compose details for diagnosis and owner-controlled fallback.

## Basic Setup

1. Add an API-key upstream on **Provider accounts**.
2. Test the account and enable the models it can serve.
3. Create a routing pool and add the provider account to it.
4. Create a client key on **API Keys** and bind it to the routing pool.
5. Use `http://localhost:3000/v1` as the OpenAI-compatible base URL and the
client key as the bearer token.

OAuth upstreams and fingerprint simulation have been removed. Existing OAuth
accounts remain archived in the database and must be replaced with API-key
upstreams in routing pools. Downstream Codex CLI clients remain supported via
API keys. See the [upgrade scope](docs/specs/2026-11-09-api-key-only-upstreams.md).
Follow [Getting started](https://github.com/KnowSky404/N2API/wiki/Getting-Started)
for local startup, account setup, and your first client connection. For a VPS,
use the [production operations guide](https://github.com/KnowSky404/N2API/wiki/Operations).

## Documentation

The [documentation index](docs/README.md) is the entry point for the N2API
manual. It includes detailed deployment, upgrade, provider-account, routing,
gateway-limit, request-log, and downstream Codex CLI guidance.

- [N2API manual](docs/manual.md)
- [Agent-native production operations](docs/agent-operations.md)
- [Brand assets](docs/brand/README.md)
- [UI design source of truth](DESIGN.md)

The `docs/` directory is intentionally the home for detailed documentation so
it can later be published as a standalone documentation site.

## Project Scope
- [Wiki](https://github.com/KnowSky404/N2API/wiki) — setup, deployment, routing, clients, and troubleshooting.
- [Complete manual](https://github.com/KnowSky404/N2API/wiki/Manual) — configuration and gateway behavior.
- [Development guide](https://github.com/KnowSky404/N2API/wiki/Development) — local sessions, tests, and cleanup.
- [Documentation sources](docs/README.md) · [Operator runbook source](docs/agent-operations.md) · [UI design](DESIGN.md).

N2API V1 uses a Go backend, PostgreSQL, and a Bun + SvelteKit + Tailwind CSS
admin UI. Docker Compose is the primary deployment path. V1 does not include
public registration, payment, recharge, balance, merchant, or platform billing
features, and it does not require Redis or SQLite.
N2API supports API-key upstreams only; OAuth upstreams and fingerprint simulation
are retired. It targets personal use, without public registration, payments,
recharge balances, or platform billing. PostgreSQL is required; Redis and SQLite
are not used.
42 changes: 32 additions & 10 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# N2API Documentation

This directory is the home of the N2API manual and project documentation. The
root project README stays focused on a short introduction and the basic startup
path; detailed usage and operations guidance belongs here.
Read the [N2API Wiki](https://github.com/KnowSky404/N2API/wiki) for setup,
configuration, and operations. The root README is a short project overview;
this directory holds the version-controlled documentation sources.

## Start Here

- [Quick start](../README.md#quick-start)
- [Basic setup](../README.md#basic-setup)
- [Wiki home](wiki/Home.md)
- [Quick start and basic setup](wiki/Getting-Started.md)
- [Agent-native production operations](agent-operations.md)
- [Complete manual](manual.md)
- [Development resource lifecycle](development.md)
Expand Down Expand Up @@ -51,9 +51,31 @@ completed feature delivery. New cross-cutting reliability and operations work
is tracked under `specs/` and `plans/`; the historical records remain available
for implementation context and are not a second active roadmap.

## Documentation Site Direction
## Wiki Maintenance

The Markdown files under `docs/` use repository-relative links and keep
user-facing manuals separate from implementation records. This provides a
stable content root for a future Pages documentation site without coupling the
repository README to a specific static-site generator.
Edit these sources through the normal worktree, review, and PR workflow.
After merging, publish the following files from the merged revision to the
separate `N2API.wiki.git` repository:

| Repository source | Wiki file |
| --- | --- |
| `docs/wiki/Home.md` | `Home.md` |
| `docs/wiki/Getting-Started.md` | `Getting-Started.md` |
| `docs/wiki/_Sidebar.md` | `_Sidebar.md` |
| `docs/manual.md` | `Manual.md` |
| `docs/agent-operations.md` | `Operations.md` |
| `docs/development.md` | `Development.md` |
| `docs/release-checklist.md` | `Release-Checklist.md` |
| `docs/repository-protections.md` | `Repository-Protections.md` |
| `docs/restore-drill-record.md` | `Restore-Drill-Record.md` |

When copying a manual, rewrite relative Markdown links to the corresponding
Wiki page names above without the `.md` extension, preserving heading anchors.
Link other repository files to their absolute GitHub URLs. Keep code examples
unchanged. Preserve unrelated Wiki pages, commit only the listed pages, and
publish with a normal push. Verify the published pages and links from a fresh
clone. The Wiki describes `main`; release users should also check their image's
source revision and release notes.

Implementation specifications, plans, and acceptance records remain in the
repository. Do not treat publication as new runtime or production evidence.
2 changes: 1 addition & 1 deletion docs/agent-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ from fixture evidence, local tests, or GitHub CI alone.

The following remain external owner gates: target-host authorization, release
approval, exact published-image and supply-chain evidence, real-backup custody,
real-backup restore records, reverse-proxy/TLS validation, real OAuth/provider
real-backup restore records, reverse-proxy/TLS validation, real API-key provider
traffic, and any manual database recovery decision.

## Scenario A: First Deployment On A New Host
Expand Down
7 changes: 3 additions & 4 deletions docs/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -1387,9 +1387,9 @@ Replace their routing-pool memberships with API-key upstreams before use.
- `/v1/models` returns `200` with an empty model list for an unbound API key. A model-routed POST made with that key fails closed with `503` and the error code `routing_pool_required`. For a bound key, `all` exposes every currently routable configured model in the routing-pool fallback chain, while `selected` exposes the routable intersection of the key's selected models.
- `/v1/models` never widens beyond the key's configured routing-pool fallback chain.
- Routing diagnostics can preview scheduler fallback without sending traffic. In Selection preview, choose a **Routing pool** to inspect its bound routing path. Leaving the pool unset runs an unscoped admin diagnostic across provider accounts; it does not represent access available to an unbound API key. Set **Excluded account IDs** to a comma-separated list such as `7, 8` to simulate those provider accounts being unavailable; excluded accounts remain visible as blocked candidates with the reason `account excluded`. Routing preview also shows each candidate's active concurrency and effective account cap; candidates at a positive cap are marked **Concurrency full**. Each schedulable preview candidate includes a **Schedule reason** as diagnostic text with its pool/global priority tier, scheduling preference tier, recent-error tier, least-recently-used tie-breaker, account ID, and sticky decision; this explains the current rank and does not change scheduler behavior. Runtime concurrency is not a proportional weight: concurrency-full accounts are excluded and the gateway requests another selection, returning `429` only when no eligible account can accept the request.
- If one enabled account cannot refresh a token or fails before streaming starts, N2API tries another eligible account that supports the same requested model.
- If one enabled account fails before streaming starts, N2API tries another eligible account that supports the same requested model.
- Once upstream streaming has started, N2API preserves that stream and does not retry against another account.
- OAuth access tokens, refresh tokens, id tokens, and short-lived PKCE verifier records are encrypted before being stored. Browser/request fingerprints are stored only as hashes.
- Provider API keys are encrypted before being stored. Historical OAuth credentials and retired fingerprint records are retained for backup compatibility only.

## Gateway Runtime Limits

Expand Down Expand Up @@ -1515,8 +1515,7 @@ Request Log CSV and JSONL exports stream the currently applied filters over an e
API upstream accounts and `OPENAI_API_BASE_URL` require HTTPS by default so
upstream API keys are not sent over plaintext HTTP. Set
`N2API_ALLOW_HTTP_API_UPSTREAMS=true` only for trusted local or private HTTP
upstreams that you control. This setting does not permit HTTP OpenAI OAuth
authorization or token endpoints.
upstreams that you control.

For sticky session routing, clients can send `session_id` in the POST body. If a client needs a header instead, prefer `X-N2API-Session-ID` through reverse proxies; `session_id` remains supported but contains an underscore and may be dropped by default proxy settings. If N2API is behind Nginx and clients send the `session_id` header, set `underscores_in_headers on;` in the relevant `http` or `server` block. A body `session_id` overrides either header.

Expand Down
70 changes: 70 additions & 0 deletions docs/wiki/Getting-Started.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Getting Started

Use a local development session to try N2API. For a persistent VPS deployment,
follow [Production operations](https://github.com/KnowSky404/N2API/wiki/Operations); the development stack does not
restart automatically.

## Start Locally

Requirements: Docker Engine with Docker Compose v2, Git, Make, and Bash.

```bash
git clone https://github.com/KnowSky404/N2API.git
cd N2API
cp .env.example .env
```

Replace every `change-me` value in `.env`. Set a strong
`POSTGRES_PASSWORD`, an `N2API_ADMIN_PASSWORD` of at least 12 bytes, and a
different `N2API_ENCRYPTION_SECRET` of at least 32 bytes. Review the
[startup configuration rules](https://github.com/KnowSky404/N2API/wiki/Manual#startup-configuration-safety).

```bash
make dev
```

Open `http://localhost:3000` on the development machine and sign in with the
admin credentials from `.env`. From another machine, use the server's reachable
hostname and configured port. Follow the
[remote access and binding guidance](https://github.com/KnowSky404/N2API/wiki/Development#development-sessions) before
exposing the service.

Keep the command open while using N2API. Ctrl-C removes development containers,
the network, and the locally built application image while preserving the
database and backups. Use `make dev-check` for a one-shot rebuild/probe/teardown
and `make dev-stop` for abandoned detached containers. See the
[development lifecycle](https://github.com/KnowSky404/N2API/wiki/Development) for details.

## Configure Accounts And Routing

1. On **Provider accounts**, add an API-key upstream with its base URL and API key.
2. Configure and enable the models it supports, then test the account.
3. Create a routing pool and add the provider account.
4. On **API Keys**, create a client key and bind it to that routing pool.
5. Set your client's OpenAI-compatible base URL to `http://localhost:3000/v1`
and use the client key as its bearer token.

Replace the base URL when the client runs on another machine. A client key
without a routing pool has no model access. Model availability is the
intersection of the key's policy, pool and fallback chain, configured account
models, and account health. See [Provider accounts](https://github.com/KnowSky404/N2API/wiki/Manual#provider-accounts)
for the full routing rules.

The gateway supports `/v1/models`, `/v1/responses`, and
`/v1/chat/completions`. Check `GET /v1/models` with the client key before
sending model requests. For Codex, follow the
[client configuration](https://github.com/KnowSky404/N2API/wiki/Manual#downstream-codex-cli).

## Deploy A Published Image

Use the repository-local `./ops/n2api` workflow for discovery, checks,
reviewed plans, deployment, backup, upgrades, verification, and guarded
application rollback. Start with [First deployment](https://github.com/KnowSky404/N2API/wiki/Operations#scenario-a-first-deployment-on-a-new-host).

Production uses an immutable `N2API_IMAGE` reference with a readable CalVer tag
and exact manifest digest. Review host bindings, HTTPS, database connectivity,
secrets, and backup custody before applying a plan. Application rollback does
not reverse database migrations; live database restoration remains manual.

The [complete manual](https://github.com/KnowSky404/N2API/wiki/Manual#deploy-a-published-image) contains lower-level
Compose details for diagnosis and owner-controlled fallback.
48 changes: 48 additions & 0 deletions docs/wiki/Home.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# N2API Wiki

**N Sources, One API.** N2API is a personal, self-hosted AI API gateway that
brings API-key upstreams behind an OpenAI-compatible endpoint.

Manage accounts, model availability, routing pools, fallback chains, client
keys, limits, and request logs from a compact web dashboard. The Go backend
serves a static SvelteKit + Tailwind CSS UI and stores configuration and
encrypted credentials in PostgreSQL. Docker Compose is the primary deployment
path, supporting `linux/amd64` and `linux/arm64`.

## Start Here

| Goal | Guide |
| --- | --- |
| Start locally and connect a client | [Getting started](https://github.com/KnowSky404/N2API/wiki/Getting-Started) |
| Deploy or upgrade a VPS instance | [Production operations](https://github.com/KnowSky404/N2API/wiki/Operations) |
| Configure networking, secrets, metrics, or alerts | [Complete manual](https://github.com/KnowSky404/N2API/wiki/Manual) |
| Configure accounts, pools, and client keys | [Provider accounts and routing](https://github.com/KnowSky404/N2API/wiki/Manual#provider-accounts) |
| Connect Codex CLI | [Downstream Codex CLI](https://github.com/KnowSky404/N2API/wiki/Manual#downstream-codex-cli) |
| Diagnose gateway errors and limits | [Gateway runtime limits](https://github.com/KnowSky404/N2API/wiki/Manual#gateway-runtime-limits) |
| Develop, test, or clean up a local session | [Development lifecycle](https://github.com/KnowSky404/N2API/wiki/Development) |
| Prepare a release | [Release checklist](https://github.com/KnowSky404/N2API/wiki/Release-Checklist) |
| Record a real-backup restore drill | [Restore drill record](https://github.com/KnowSky404/N2API/wiki/Restore-Drill-Record) |
| Review intended repository checks | [Repository protections](https://github.com/KnowSky404/N2API/wiki/Repository-Protections) |

## Scope And Compatibility

N2API is independently implemented and inspired by sub2api's workflow. It
targets personal self-hosting, without public registration, payments, recharge
balances, or platform billing. PostgreSQL is required; Redis and SQLite are
not used.

Upstream accounts use API keys. OAuth authorization, token refresh, and
fingerprint simulation are retired. Existing OAuth rows remain archived for
backup compatibility and cannot serve requests; replace their routing-pool
memberships with API-key accounts. Downstream Codex clients still connect
through a client API key. See the
[upgrade scope](https://github.com/KnowSky404/N2API/blob/main/docs/specs/2026-11-09-api-key-only-upstreams.md).

## Documentation Version

This Wiki describes the current `main` branch. A published image may predate
these changes; match its release notes and source revision before upgrading.

[Repository](https://github.com/KnowSky404/N2API) ·
[Releases](https://github.com/KnowSky404/N2API/releases) ·
[Documentation sources](https://github.com/KnowSky404/N2API/tree/main/docs)
12 changes: 12 additions & 0 deletions docs/wiki/_Sidebar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
**N2API**

- [Home](https://github.com/KnowSky404/N2API/wiki/Home)
- [Getting started](https://github.com/KnowSky404/N2API/wiki/Getting-Started)
- [Complete manual](https://github.com/KnowSky404/N2API/wiki/Manual)
- [Production operations](https://github.com/KnowSky404/N2API/wiki/Operations)
- [Development](https://github.com/KnowSky404/N2API/wiki/Development)
- [Release checklist](https://github.com/KnowSky404/N2API/wiki/Release-Checklist)
- [Restore drill record](https://github.com/KnowSky404/N2API/wiki/Restore-Drill-Record)
- [Repository protections](https://github.com/KnowSky404/N2API/wiki/Repository-Protections)

[Source repository](https://github.com/KnowSky404/N2API)
Loading