Compare commits

...

4 commits

Author SHA1 Message Date
ZTatman
e64315f68d fix(setup): pre-fill public base URL and require it in the wizard
An empty firebreak_public_base_url only works while the person filling in
the wizard happens to be browsing the same origin Forgejo redirects back
to, so it can look fine during local setup and still be wrong in
production. It also leaves share URLs relative, since there is no
externally resolvable origin to build them from.

The setup page already derived the request's base URL to display the OAuth
callback hint, but persisted "" instead, so the field and the hint could
disagree. Pass the derived value through as the field's value and mark the
input required, dropping the hint that told users to leave it blank on
localhost.
2026-10-05 15:58:47 -04:00
ZTatman
82d50bff59 feat(links): add repository commit listing endpoint
Expose GET /links/repositories/{repo}/commits, resolving {owner}
server-side from the session's linked Forgejo identity like the sibling
branches route.

Take the ref as a query parameter instead of a path segment: branch names
contain slashes (docs/readme, feature/learn-public-links), which a single
path param cannot capture without a path converter. As a query param,
`ref` may also default to main.

Dropping the path default and declaring `repo` were both required for the
module to import: FastAPI asserts that path parameters have no defaults,
and an undeclared path param raised NameError at call time.
2026-10-05 15:45:26 -04:00
ZTatman
984b382758 fix(forgejo): query commits by sha and normalize Commit payload
Forgejo's commits endpoint filters on `sha`, not `branch`. Sending
`?branch=<name>` was silently ignored and the API returned the default
branch's commits for every ref, so branch resolution appeared to work
while always yielding the same list.

Rename the parameter to `ref` (a branch, tag, or sha) and send it as
`sha`, documenting that the slot name is Forgejo's choice while the value
is a caller-supplied git ref.

The flat commits payload is GitHub-shaped (`sha`, `commit.message`,
`html_url`, `created`) while the nested branch commit uses `id`,
`message`, `url`, and `timestamp`. Give each Commit field an
AliasChoices/AliasPath covering both shapes so one model serves the
/branches and /commits endpoints, then map commits through it instead of
returning raw dicts under a `list[Commit]` annotation.

Also annotate get_branches' limit/page to match get_commits.
2026-10-05 15:45:22 -04:00
ZTatman
5f839a47b6 refactor(auth): drop per-request session write, keep last_seen_at for sliding window 2026-10-05 15:09:02 -04:00
5 changed files with 69 additions and 22 deletions

View file

@ -71,11 +71,10 @@ async def lookup_session(
sess = result.scalar_one_or_none()
if sess is None:
return None
# Track activity whenever a valid cookie is used, then refresh the related
# user so route handlers can safely access sess.user.
sess.last_seen_at = now
await db.commit()
await db.refresh(sess, attribute_names=["user"])
# sess.user is eagerly loaded via selectinload and the sessionmaker uses
# expire_on_commit=False, so it stays accessible without a refresh. last_seen_at
# is intentionally not updated here to keep auth reads free of writes; it is
# reserved for a future sliding-window expiry feature.
return sess

View file

@ -32,10 +32,27 @@ class Repo(BaseModel):
class Commit(BaseModel):
"""A commit, normalized across Forgejo's two payload shapes.
``/branches`` nests a trimmed commit keyed ``id``/``timestamp``/``url``,
while ``/commits`` returns a flat GitHub-style object keyed
``sha``/``commit.message``/``html_url``/``created``. Each field therefore
accepts either shape.
"""
id: str = Field(validation_alias=AliasChoices("sha", "id"))
message: str
url: str
created_at: datetime = Field(validation_alias="timestamp")
message: str = Field(
validation_alias=AliasChoices("message", AliasPath("commit", "message"))
)
url: str = Field(validation_alias=AliasChoices("html_url", "url"))
created_at: datetime = Field(
validation_alias=AliasChoices(
"timestamp",
"created_at",
"created",
AliasPath("commit", "committer", "date"),
)
)
class Branch(BaseModel):
@ -64,8 +81,8 @@ async def get_branches(
owner: str,
repo: str,
*,
limit=10,
page=1,
limit: int = 10,
page: int = 1,
) -> list[Branch]:
"""Get the branches of a repository from the Forgejo API.
Args:
@ -94,7 +111,7 @@ async def get_commits(
owner: str,
repo: str,
*,
branch: str,
ref: str,
limit: int = 10,
page: int = 1,
) -> list[Commit]:
@ -104,7 +121,7 @@ async def get_commits(
access_token: The Forgejo API token.
owner: The owner of the repository.
repo: The name of the repository.
branch: The branch to list commits for.
ref: The branch name, commit sha, or tag to list commits for.
limit: The maximum number of commits to return.
page: The page number to return.
@ -113,13 +130,12 @@ async def get_commits(
"""
commits = await get(
app_settings,
f"/api/v1/repos/{owner}/{repo}/commits?branch={branch}&limit={limit}&page={page}",
f"/api/v1/repos/{owner}/{repo}/commits?sha={ref}&limit={limit}&page={page}",
access_token,
)
if not commits:
return []
return commits
# return [Commit.model_validate(c) for c in commits]
return [Commit.model_validate(c) for c in commits]
async def post(app_settings: AppSettings, path: str, data: dict) -> dict:

View file

@ -1,7 +1,7 @@
from datetime import datetime
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Path, status
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
from pydantic import BaseModel, EmailStr
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@ -94,3 +94,32 @@ async def get_repository_branches(
app_settings, access_token, owner, repo, limit=limit, page=page
)
return branches
@router.get("/repositories/{repo}/commits")
async def get_repository_commits(
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
access_token: Annotated[str, Depends(get_forgejo_token)],
db: Annotated[AsyncSession, Depends(get_db)],
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
ref: Annotated[str, Query(description="Branch name, commit sha, or tag")] = "main",
limit: int = 10,
page: int = 1,
):
# Derive {owner} path param from users linked identity provider server-side
stmt = select(LinkedIdentity).where(
LinkedIdentity.user_id == sess.user_id, LinkedIdentity.provider == "forgejo"
)
result = await db.execute(stmt)
identity = result.scalar_one_or_none()
if identity is None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="No linked identity for forgejo was found. Please sign-in and try again.",
)
owner = identity.provider_username
commits = await forgejo.get_commits(
app_settings, access_token, owner, repo, ref=ref, limit=limit, page=page
)
return commits

View file

@ -61,9 +61,11 @@ async def setup_page(
"reconfiguring": existing is not None and has_users,
"forgejo_base_url": existing.forgejo_base_url if existing else "",
"forgejo_oauth_client_id": existing.forgejo_oauth_client_id if existing else "",
"firebreak_public_base_url": existing.firebreak_public_base_url
if existing
else "",
# Pre-fill with the request's own base URL so the field is never
# accidentally left blank: an empty value only works while the caller
# is browsing the same origin that Forgejo redirects back to, and any
# generated share link needs an externally resolvable address.
"firebreak_public_base_url": public_base,
"oauth_callback_url": f"{public_base}/auth/callback/forgejo",
}
return templates.TemplateResponse(request, "setup.html", ctx)

View file

@ -112,16 +112,17 @@
<label for="firebreak_public_base_url"
class="block text-xs font-semibold uppercase tracking-[0.05em] text-[#f7f2e8]/50 mb-1.5">
Public Base URL
<span class="ml-1 normal-case tracking-normal font-normal text-[#f7f2e8]/30">(optional)</span>
</label>
<input type="url"
id="firebreak_public_base_url"
name="firebreak_public_base_url"
class="block w-full rounded-md border border-[#f7f2e8]/14 bg-[#1f2226] px-3 py-2.5 text-sm text-[#f7f2e8] placeholder:text-[#f7f2e8]/30 focus:border-[#f7f2e8]/30 focus:outline-none focus:ring-2 focus:ring-[#f7f2e8]/10"
placeholder="https://share.example.com"
required
value="{{ firebreak_public_base_url }}" />
<p class="mt-1.5 text-xs text-[#f7f2e8]/30">
Your production domain for OAuth redirects. Leave blank on localhost &mdash; Firebreak will use <code class="font-mono text-[#f7f2e8]/40">http://localhost:8000</code> automatically.
The address Forgejo redirects back to after sign-in, and the origin
share links point at. Pre-filled from how you reached this page
&mdash; change it to your real domain once Firebreak is deployed.
</p>
</div>
<button type="submit" class="btn btn-primary w-full mt-2">