Browse documentation
Fountain handbook

Extension backend

Build an extension backend with the Fountain Go SDK: serve HTTP on the private socket, read the host's authority for each request, store data and stay within proxy limits.

On this page

Set up the SDK

The Go SDK is the module forgejo.org/extension-sdk, in the sdk/ directory of the Fountain source. Use the copy from the same release tag as the forge you target, for example from the release's fountain-V-source.tar.gz, and point your module at it:

go mod init example.com/hello
go mod edit -require=forgejo.org/extension-sdk@v0.0.0 \
  -replace=forgejo.org/extension-sdk=../fountain/sdk
go mod tidy

The SDK is MIT-licensed and imports nothing from the forge itself.

Serve the application

extensions.Serve starts an HTTP server on the socket the host provides and then joins the host's process handshake. It returns when the host stops the backend.

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	extensions "forgejo.org/extension-sdk"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /context", func(w http.ResponseWriter, r *http.Request) {
		authority, err := extensions.RequestContext(r)
		if err != nil {
			http.Error(w, "missing native authority", http.StatusUnauthorized)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(authority)
	})
	if err := extensions.Serve(extensions.Application{HTTP: mux}); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

extensions.Application has four fields:

Field Purpose
HTTP Required. Handles your page and panel API requests and streams.
AuthorizeContribution Optional authorizer; register it exactly when the manifest declares native.contribution.authorize.
Policies Optional map of policy handlers by ID; must match the manifest's policies.
Lifecycle Optional lifecycle handler; register it exactly when the manifest declares native.extension.lifecycle.

The host refuses to start a backend whose registration does not match its manifest.

How the host runs the backend

The host starts the executable with the package directory as its working directory and a minimal environment. Nothing else from the forge's environment is passed through.

Variable Value
FORGEJO_EXTENSION_SOCKET Unix socket the SDK listens on
FORGEJO_EXTENSION_DATA The private data directory, also returned by extensions.DataDir()
FORGEJO_EXTENSION_CALLBACK_SOCKET Socket for native callbacks, present when a declared capability needs them
HOME The private data directory
TMPDIR A private per-process runtime directory under .runtime/ in the package directory
PATH The forge's PATH

The handshake must complete within 10 seconds and the backend must report ready within 2 seconds after that. The handshake uses standard output, so never write to stdout; send diagnostics to stderr and keep credentials out of them.

Requests and authority

A page's API lives under its apiBase, for example /-/native/pages/hello/home/api/ for a global page, with /user/settings, /admin or /{owner}/{repo} in front for the other scopes. Panels use /-/native/panels/ID/PANEL/api/. The host strips that prefix: a browser call to request('context') arrives at your handler as GET /context, with the original query string.

Call extensions.RequestContext(r) on every request. It returns the host's authority for that request:

Field Meaning
ExtensionID Your package ID
InstanceID The running backend process instance
SessionGeneration The browser session generation
Contribution ID, Kind (page or panel), Scope and Action (the lower-case HTTP method)
Actor ID (a decimal string), Username and SiteAdmin
Repository On repository pages: ID, Owner, Name and the actor's current Permission

Treat the authority as valid for that request only, and key stored data by the authoritative IDs, never by values from the browser. Enforce your own rules per endpoint: being able to open a read page does not make every operation appropriate for a reader. The private admission inside the authority is left out when you encode it as JSON, so it is safe to return the authority to browser code.

Native reads

authority.Native() returns a client for current native data, checked by the host against the request's admission and the live session:

Method Needs capability
CurrentActor(ctx) native.actor.read
Repository(ctx, id) native.repository.read
SearchOwnedRepositories(ctx, query, cursor, limit) native.repositories.owned.search
OrganizationOwner(ctx, organization) native.organization.ownership
PublicSSHKeys(ctx) native.user.public_keys.read

Authority also has methods for issues, pull requests, reviews, checks, source and preparation snapshots, and for submitting operations on the person's behalf. They are listed with their capabilities in Background collaboration and the Capabilities reference.

Request limits

Limit Value
Methods GET, HEAD, POST, PUT, PATCH, DELETE
Request headers forwarded Accept, Accept-Language, Content-Type, Origin, Sec-Fetch-Site, plus the host's authority headers
Deadline 30 seconds per request
Request body 8 MiB
Response body 8 MiB, buffered completely before it is sent to the browser
Response headers kept Status and Content-Type; the host adds Cache-Control: no-store and X-Content-Type-Options: nosniff
Refused responses Redirects, informational statuses and text/event-stream, which reach the browser as 502

Cookies, Authorization and other browser headers are never forwarded. Mutating requests must carry exactly one Origin that matches the forge's ROOT_URL. Paths with . or .. segments, empty segments, backslashes, control characters or encoded separators are refused before they reach your backend.

Streams

A WebSocket request to the same API path is relayed to your backend as a WebSocket. Accept it in your HTTP handler with any Go WebSocket library; the bundled example uses github.com/coder/websocket.

  • The browser's origin must match ROOT_URL, and the host admits the stream from the live session.
  • Your handler receives the authority headers but no cookies, authorization or subprotocol headers.
  • Messages are limited to 32 KiB in each direction, and the forge relays at most 128 extension streams at once.
  • Every 15 seconds the host checks the session and the package and pings both ends; it closes the stream when access ends, the package stops or the forge shuts down.

Streams are not subject to the 30-second request deadline or the buffered response limit.

Store data

extensions.DataDir() returns your private data directory, .data/ID/ under the package directory. It is created with mode 0700 before the backend starts and survives disabling, replacement and removal. Partition it by actor or repository ID and write files atomically, for example by writing a temporary file and renaming it, as the bundled example does for its notes.

Policies

A package that lists forgejo.username in policies must register a handler under that ID. When the package is required, Fountain calls it before creating or renaming a personal account; see Required packages.

extensions.Serve(extensions.Application{
	HTTP: mux,
	Policies: map[string]extensions.PolicyHandler{
		extensions.PolicyForgejoUsername: func(ctx context.Context, req extensions.PolicyRequest) (extensions.PolicyDecision, error) {
			if strings.HasPrefix(req.Username, "svc-") {
				return extensions.PolicyDecision{Allowed: false, ReasonCode: "reserved_prefix"}, nil
			}
			return extensions.PolicyDecision{Allowed: true}, nil
		},
	},
})

PolicyRequest carries Operation (create or rename), Username and, for renames, UserID. Returning an error counts as unavailable, and the account change is refused.

Continue

Add work that runs without a browser with Background collaboration.