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
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
deploy/* text eol=lf
docker/entrypoint.sh text eol=lf
tests/e2e/*.sh text eol=lf
examples/nginx/*.conf text eol=lf
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ jobs:
- name: Validate compose file
run: docker compose -f docker/docker-compose.yml config --quiet

- name: Validate release compose file
run: docker compose -f deploy/docker-compose.yml config --quiet

- name: Build images
run: docker compose -f docker/docker-compose.yml build

Expand Down
51 changes: 51 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Release image

on:
push:
tags: ['v*.*.*']

permissions: {}

jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- name: Image name
id: image
env:
OWNER: ${{ github.repository_owner }}
TAG: ${{ github.ref_name }}
run: |
echo "name=ghcr.io/${OWNER,,}/telelogin" >> "$GITHUB_OUTPUT"
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v5
id: meta
with:
images: ${{ steps.image.outputs.name }}
flavor: latest=auto
tags: |
type=semver,pattern={{version}}
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.description=Telegram authentication with forward auth and OpenID Connect
org.opencontainers.image.licenses=Apache-2.0
org.opencontainers.image.version=${{ steps.image.outputs.version }}
- uses: docker/build-push-action@v6
with:
context: .
file: docker/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
60 changes: 60 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Changelog

All notable changes are documented here, following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
Versions follow semantic versioning.

## [2.0.0] - Unreleased

### Added

- Shared 30-day browser SSO sessions and forward auth for nginx, Traefik and Caddy.
- Operator CLI for apps, per-app allowlists, access policies and user invitations.
- Confidential OpenID Connect authorization code clients, PKCE S256, discovery, RS256 ID
tokens, JWKS and opaque access tokens for userinfo.
- Image release workflow for amd64/arm64 and image-only deployment files under `deploy/`.
- Integration guide, proxy examples, Authlib example and real proxy end-to-end checks.
- Stable public user identifiers, closed registration mode and configurable cookie domains.

### Changed

- Browser login uses a shared HttpOnly session cookie; raw API and JavaScript client remain available.
- Browser sessions appear in bot session management and participate in account deletion and revocation.
- Signing keys are persisted with concurrent first-start protection and durable publication.

**Breaking changes**

- Compose publishes the API port on `127.0.0.1` only; use a reverse proxy.
- Compose defaults `FORWARDED_ALLOW_IPS` to `*` for a proxy on the host. This is safe only
with the loopback binding or a private network restricted to trusted callers.
- `GET /` returns an HTML account page instead of JSON.
- `/login` uses the SSO cookie flow instead of storing API tokens in sessionStorage.
- `/health` now returns `{"status":"ok","version":"2.0.0"}`.

### Security

- API and SSO grants are separated; return URLs and app origins are validated per app.
- Browser POSTs enforce content types and same-origin checks; identity headers are encoded
and proxy examples remove spoofed headers.
- OIDC codes are single-use and client-bound; replay revokes associated access tokens.
- Private RSA keys use mode 0600; cookie domain checks use an offline public suffix snapshot.

### Upgrading from 1.x

1. Stop API and bot and back up your SQLite database, environment file and data volume.
2. Review the breaking changes above. Configure HTTPS and a reverse proxy, including
forwarded headers and blocking public access to internal endpoints. Update health-body consumers.
3. Keep `SECRET_KEY`, `INTERNAL_API_KEY`, bot credentials and your existing data volume.
For an existing Compose installation, keep its project name and volume mapping: moving
to `deploy/` changes the default project name and can create an empty volume. Set
`COMPOSE_PROJECT_NAME` to the old project name or explicitly map the existing volume.
4. Copy the release environment template and transfer existing settings; set `PUBLIC_URL`,
cookie settings and registration policy. Keep the generated OIDC key in the persistent
data volume and include it in backups. Do not regenerate existing secrets during upgrades.
5. Set `TELELOGIN_VERSION=2.0.0`, pull the image and start API and bot. Startup applies
idempotent schema migrations. Check `/health`, logs and a Telegram login.
6. Register apps and allow users as described in the integration guide. Update custom
browser integrations relying on `/login` tokens to use SSO or the raw API explicitly.
Legacy API tokens without a session id require a fresh login.

Rollback requires restoring the backup and the previous image together; do not assume
an older server supports the migrated schema.
37 changes: 37 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Contributing

Use Python 3.11+ and Node.js for the JavaScript client checks. From the checkout root:

```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements-dev.txt
cp .env.example .env
```

Configure the local bot credentials and secrets in `.env`. For development run
`.venv/bin/uvicorn src.app:app` and `.venv/bin/python -m src.bot` in separate terminals.

Run the proof command before submitting a PR:

```bash
.venv/bin/python -m pytest -q && .venv/bin/ruff check src tests && .venv/bin/python -W error::DeprecationWarning -m pytest -q
```

With Docker available, run each real proxy check:

```bash
tests/e2e/forward_auth.sh nginx
tests/e2e/forward_auth.sh traefik
tests/e2e/forward_auth.sh caddy
```

Preserve existing line endings: Python under `src/` and `tests/`, `docker/*.yml` and
`docker/env.example` use CRLF. Markdown, workflow YAML, shell scripts, proxy examples and
new `deploy/` files use LF. Follow `.gitattributes`; avoid whole-file newline churn.

PRs should describe the concrete problem, resulting behavior, relevant tests and any
limitations. Include regression coverage for behavior changes and update affected examples
and documentation. Never commit secrets, runtime databases or private keys. Maintainers
publish releases by tagging; a normal branch or PR does not run the release workflow.
Stable semantic version tags update `latest`; prerelease tags (for example `v2.1.0-rc.1`)
publish their version tag without moving `latest`.
149 changes: 110 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,82 @@
# TeleLogin

TeleLogin also protects apps with **forward auth**: one Telegram confirmation creates a reusable
browser session, and nginx, Traefik or Caddy supplies the app's verified identity. Per-app allowlists
(default) or `all` policies control access. See [Integration guide](docs/INTEGRATION.md) for both
shared-host/path-prefix and sibling-subdomain deployments, proxy snippets and the operator CLI.
OpenID Connect supports confidential clients with authorization code flow and PKCE S256.
TeleLogin provides Telegram-confirmed login through a self-hosted bot. Protect apps with
Mode 2 forward auth through nginx, Traefik or Caddy, connect standard clients with Mode 1
OpenID Connect, or build a custom UI with the raw API. Shared browser sessions and per-app
access policies let connected apps reuse one Telegram confirmation. Python 3.11+.

**Deployment change:** the development Compose API port now binds to `127.0.0.1` only. Configure a
local reverse proxy, or use a private Docker network with no published API port. `GET /` now serves
a browser account page instead of JSON. `/health` remains unchanged.
## Quick start

Run these commands from the root of this checkout with Docker Compose v2 installed.
The release image below becomes available when the maintainer publishes 2.0.0.
For a pre-release walkthrough, build it locally first:
`docker build -f docker/Dockerfile -t ghcr.io/downlevel/telelogin:2.0.0 .`.

1. Create a Telegram bot with **@BotFather**. Save its token and username (without `@`).
2. Generate the two server secrets:

```bash
docker run --rm ghcr.io/downlevel/telelogin:2.0.0 python -m src.admin gen-secrets
cp deploy/.env.example deploy/.env
```

Edit `deploy/.env`: fill `BOT_TOKEN`, `BOT_USERNAME`, `SECRET_KEY` and
`INTERNAL_API_KEY` with your values. Set `PUBLIC_URL` to your external HTTPS URL,
for example `https://auth.example.com` or `https://example.com/telelogin`.
Keep `SSO_COOKIE_SECURE=true`. For sibling apps, set `SSO_COOKIE_DOMAIN=example.com`
only if every subdomain is trusted. The domain must match your own deployment.
3. Start the services:

```bash
docker compose -f deploy/docker-compose.yml up -d
```

Configure your HTTPS proxy using the matching [integration example](docs/INTEGRATION.md).
The API listens on host loopback port 8000; a Docker proxy instead needs a shared private
network and no published API port (see the guide). Proxy the configured public URL to
the API, stripping any path prefix, and block internal endpoints.
4. Invite yourself (works with both open and closed registration):

```bash
docker compose -f deploy/docker-compose.yml exec api python -m src.admin user invite alice
```

The hosted `/login` page signs in existing users; it has no registration control.
Open the printed link and press Start in Telegram. Replace `alice` consistently with
your chosen username in these commands.
5. Register and authorize the first app:

```bash
docker compose -f deploy/docker-compose.yml exec api python -m src.admin app add myapp --name "My App"
docker compose -f deploy/docker-compose.yml exec api python -m src.admin app allow myapp alice
```

For a sibling app, register its actual origin too:

```bash
docker compose -f deploy/docker-compose.yml exec api python -m src.admin app origin add myapp https://app.example.com
```

6. Paste the nginx, Traefik or Caddy protection snippet from
[the integration guide](docs/INTEGRATION.md), using app id `myapp` and your actual
hostnames/upstream. Host proxy → `127.0.0.1:8000` (replace `8000` with `API_PORT`); proxy in Docker → `telelogin:8000` after joining the TeleLogin Compose network (`deploy_telelogin_network` by default).
For Docker, start with the [port-removal override and network setup](docs/INTEGRATION.md#docker-proxy-networking):

```bash
docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.docker-proxy.yml up -d
```

Keep the app reachable only through that proxy. Visit the app,
sign in and select the displayed number in Telegram.

For an optional OIDC app, use `app add` with `--redirect-uri` and configure the printed
client secret, discovery URL and `openid profile` scopes as described in
[Mode 1](docs/INTEGRATION.md#mode-1-openid-connect).

## Upgrading from 1.x

Read the [breaking changes and upgrade steps](CHANGELOG.md#upgrading-from-1x) before
starting 2.0.0, especially the existing volume mapping and proxy settings.

| Browser/SSO setting | Default | Purpose |
| --- | --- | --- |
Expand All @@ -29,9 +97,6 @@ a browser account page instead of JSON. `/health` remains unchanged.
| `/sso/logout` | POST JSON/form | Revoke browser session, clear cookie, redirect |



Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.11+.

## Features

- OpenID Connect discovery, RS256 ID tokens, opaque access tokens, and shared browser SSO.
Expand All @@ -49,40 +114,44 @@ Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.1
telelogin/
├── src/
│ ├── app.py # FastAPI application and lifespan
│ ├── bot.py # Telegram bot and notification HTTP server
│ ├── admin.py # Operator CLI
│ ├── bot.py # Telegram bot and notification server
│ ├── config.py # Validated environment settings
│ ├── database/
│ │ ├── base.py # Database interface
│ │ └── sqlite.py # Schema, migrations and atomic operations
│ ├── models/user.py # User model
│ ├── services/
│ │ ├── auth_service.py # Login and background notifications
│ │ ├── token_service.py # Persistent registration tokens
│ │ └── user_service.py # User operations
│ ├── utils/crypto.py # JWT signing and verification
│ ├── database/ # Schema, migrations and atomic operations
│ ├── models/ # User model
│ ├── services/ # Authentication, registration and user operations
│ ├── utils/ # API token signing and verification
│ └── web/
│ ├── dependencies.py # Application-scoped dependency providers
│ ├── routes.py # Authentication routes
│ ├── routes.py # Raw API
│ ├── sso.py # Browser sessions and forward auth
│ ├── oidc.py # OpenID Connect provider
│ ├── dependencies.py # Application-scoped providers
│ ├── schemas.py # Request/response validation
│ ├── security.py # Internal key checks and rate limiter
│ └── templates/index.html # Browser login page
├── tests/
│ ├── conftest.py # Environment and temporary database fixtures
│ ├── test_security.py # Phase 1 security regressions
│ └── test_phase2.py # Architecture and integration checks
├── docker/
│ ├── Dockerfile
│ ├── entrypoint.sh # Volume ownership migration and privilege drop
│ ├── docker-compose.yml
│ └── env.example
│ └── templates/index.html # Hosted login
├── deploy/
│ ├── docker-compose.yml # Release images
│ ├── docker-compose.docker-proxy.yml # Remove published port for Docker proxies
│ └── .env.example # Release configuration template
├── docker/ # Development Compose, Dockerfile and entrypoint
├── docs/INTEGRATION.md # Deployment and app integration guide
├── examples/
│ ├── curl_examples.md
│ └── js_client/ # JavaScript client and demo
├── .env.example
│ ├── nginx/ # Forward auth configurations
│ ├── traefik/ # Dynamic configuration and labels
│ ├── caddy/ # Forward auth Caddyfiles
│ ├── oidc_fastapi/ # Authlib client
│ ├── js_client/ # Raw API JavaScript client and demo
│ └── curl_examples.md
├── tests/ # Unit/integration tests and e2e/ proxy harness
├── .github/workflows/ # CI and tag-only image releases
├── .env.example # Local development configuration
├── .gitattributes
├── pyproject.toml
├── requirements.txt
├── requirements-dev.txt
├── CHANGELOG.md
├── SECURITY.md
├── CONTRIBUTING.md
├── README.md
└── LICENSE
```
Expand Down Expand Up @@ -175,7 +244,7 @@ Both templates declare all supported variables. Required secrets must be supplie
| --- | --- |
| GET / | Browser account page (HTML) |
| GET /login | Hosted browser login; optional app and rd parameters |
| GET /health | 200 {"status":"ok"} after a database query |
| GET /health | 200 {"status":"ok","version":"2.0.0"} after a database query |
| POST /register | {"username":"alice"}; returns Telegram registration link; duplicate username 400 |
| GET /.well-known/openid-configuration | OIDC discovery |
| GET /jwks.json | Public RSA signing key |
Expand Down Expand Up @@ -338,8 +407,10 @@ are present in both environment templates and Docker Compose.

GitHub Actions (`.github/workflows/ci.yml`) runs on every push to main and every pull
request: Ruff, the test suite on Python 3.11 and 3.12 (including the Node client
simulation and a warnings-as-errors pass), a compose validation, the image build and an
API smoke test (`/health`, `/auth/me` → 401).
simulation and a warnings-as-errors pass), development and deploy Compose validation,
the image build and an API smoke test (`/health`, `/auth/me` → 401). A separate e2e job
runs the real nginx, Traefik and Caddy forward-auth checks. Actionlint is a host review
check and is not run in CI.

```bash
.venv/bin/python -m pytest -q && .venv/bin/ruff check src tests && .venv/bin/python -W error::DeprecationWarning -m pytest -q
Expand Down
13 changes: 13 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Security policy

The supported version line is **2.x**. Use the latest available patch release.

Report vulnerabilities privately using this repository's GitHub **Security → Report a
vulnerability** (private vulnerability reporting / Security Advisories). Include affected
versions, reproduction steps and impact. Do not disclose credentials or exploit details in
public issues. If private reporting is unavailable, ask the maintainers to enable it without
posting vulnerability details.

Scope includes the TeleLogin server, Telegram bot and shipped integration examples.
Misconfigured deployments are out of scope, including exposed internal endpoints, untrusted
cookie subdomains, public backends bypassing the proxy, and trusting arbitrary forwarded headers.
Loading
Loading