{"modulePath":"github.com/FelineStateMachine/tinyrelay","version":"v0.0.0-20260923223823-92682824e566","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package tinygit\n\nPackage tinygit coordinates signed Nostr repository events with native Git object storage and smart HTTP. Signed events establish repository refs, metadata and maintainer authority.\n\nGitRelay stores bare repositories under Config.Root. Journal files under .tinyrelay/journal make event-to-ref transitions recoverable, while pending state files keep a signed ref announcement out of the visible repository until every advertised tip object is present. New creates the root, recovers journals and reloads repository metadata from the event store. Synchronization runs through Service.Tick or transport callbacks invoked by the caller.\n\nParseMetadata checks repository announcement and state shape without a store, signature check or host policy. Its Metadata result contains claims, not resolved repository authority. Use protocol/nostr.Validate for the separate wire, event ID and signature check. Neither check establishes maintainer authority, hosting permission or Git object availability, and the metadata parser does not claim full NIP or GRASP compliance.\n\nValidate and ValidateImported check signatures and metadata shape before resolving repository authority and applying host admission. A valid shape may still be denied by Config.Authorize or lack a current announcement. After the caller durably stores an admitted event, CommitAfterStore stages its Git transition. CommitAfterStoreNoNotify serves callers already holding the host publication fence. PromotePending completes a receive-pack repair and invokes OnPromote after state becomes visible.\n\nServeHTTP exposes Git smart HTTP for public and private repositories. Private requests pass through AuthorizeHTTP. GRASP-08 private peer traffic is limited to Config.PrivatePeers and is signed by HTTPAuth. GitSync and EventSync supply synchronization transports; the daemon supplies the relay client and WebSocket lifecycle.\n\nFor a standalone public host, OpenServer owns event persistence and exposes POST /events plus Git smart HTTP. It requires an owner public key, admits only that owner's public repositories and their announced maintainers, and rejects private announcements. Publish signed kind 30617 metadata first, then signed kind 30618 refs before pushing their objects. Receive-pack promotes pending refs; unsigned ref updates are rejected by the same native hook used by the embedded engine. GET /healthz reports process readiness.\n\nNew is the lower-level integration boundary. Supply an absolute Config.Root and an OpenStore result, or provide a Store implementation for an embedded host. Policy, Event and Store are public contracts; the standard SQLite adapter and the host's richer policy remain behind those contracts. Neither constructor starts the daemon, relay protocol, UI or replication workers. Native Git and a POSIX shell are required for smart HTTP and receive hooks.\n\n## Variables\n\n```go\nvar ErrDuplicate = gitstore.ErrDuplicate\n```\nErrDuplicate indicates that an event was already persisted.\n\n```go\nvar ErrIncomplete = errors.New(\"synchronization incomplete\")\n```\nErrIncomplete reports a synchronization pass that saved progress and has more history to fetch. The scheduler continues it soon without counting a failure.\n\n## Functions\n\n```go\nfunc RepairSources(r Repository) []string\n```\nRepairSources gives a daemon a deterministic source order for a missing object. Clone URLs are preferred, followed by relay URLs; callers must still pass each URL through AdmitSource and verify the object graph.\n\n## Types\n\n```go\ntype BackupObject struct {\n\tOID    string   `json:\"oid\"`\n\tType   string   `json:\"type\"`\n\tSize   int      `json:\"size\"`\n\tChunks []string `json:\"chunks\"`\n}\n```\nBackupObject is one validated Git object and its compressed content chunks.\n\n```go\ntype BackupRepository struct {\n\tKey         string            `json:\"key\"`\n\tOwner       string            `json:\"owner\"`\n\tIdentifier  string            `json:\"identifier\"`\n\tAlternative bool              `json:\"alternative\"`\n\tObjects     []BackupObject    `json:\"objects\"`\n\tRefs        map[string]string `json:\"refs\"`\n}\n```\nBackupRepository contains the objects and refs for one imported repository.\n\n```go\ntype BrowseCommit struct {\n\tOID     string   `json:\"oid\"`\n\tParents []string `json:\"parents\"`\n\tAuthor  string   `json:\"author\"`\n\tTime    int64    `json:\"time\"`\n\tSubject string   `json:\"subject\"`\n}\n```\n\n```go\ntype BrowseEntry struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n\tMode string `json:\"mode\"`\n\tType string `json:\"type\"`\n\tOID  string `json:\"oid\"`\n\tSize int64  `json:\"size\"`\n}\n```\n\n```go\ntype BrowsePage struct {\n\tOwner      string   `json:\"owner\"`\n\tIdentifier string   `json:\"identifier\"`\n\tHead       string   `json:\"head\"`\n\tPrivate    bool     `json:\"private\"`\n\tClone      []string `json:\"clone\"`\n\tRelays     []string `json:\"relays\"`\n\t// Maintainers is filled by the host, which knows about agent grants.\n\tMaintainers []Maintainer      `json:\"maintainers,omitempty\"`\n\tRefs        map[string]string `json:\"refs\"`\n\tCommit      string            `json:\"commit\"`\n\tPath        string            `json:\"path\"`\n\tView        string            `json:\"view\"`\n\tEntries     []BrowseEntry     `json:\"entries\"`\n\tContent     string            `json:\"content\"`\n\tBinary      bool              `json:\"binary\"`\n\tTruncated   bool              `json:\"truncated\"`\n\tCommits     []BrowseCommit    `json:\"commits\"`\n\tDiff        string            `json:\"diff\"`\n\tNextOffset  int               `json:\"next_offset\"`\n}\n```\n\n```go\ntype BrowseRequest struct {\n\tOwner  string `json:\"owner\"`\n\tRepo   string `json:\"repo\"`\n\tRef    string `json:\"ref\"`\n\tPath   string `json:\"path\"`\n\tView   string `json:\"view\"`\n\tOffset int    `json:\"offset\"`\n\tLimit  int    `json:\"limit\"`\n}\n```\n\n```go\ntype CollaborationDiff struct {\n\tStatus    string `json:\"status\"`\n\tBase      string `json:\"base,omitempty\"`\n\tTip       string `json:\"tip,omitempty\"`\n\tMergeBase string `json:\"merge_base,omitempty\"`\n\tDiff      string `json:\"diff,omitempty\"`\n\tTruncated bool   `json:\"truncated,omitempty\"`\n\tReason    string `json:\"reason,omitempty\"`\n}\n```\nCollaborationDiff is the result of rendering a pull request's local Git objects. Status is \"ok\" when Diff is authoritative and \"diff\\_unavailable\" when one or both commits are not present locally.\n\n```go\ntype Config struct {\n\tStore     Store\n\tRoot      string\n\tPolicy    func() Policy\n\tAuthorize func(context.Context, Event, Repository) error\n\t// Maintainers extends maintainer checks with host-side authority. It is\n\t// consulted only after the owner and the maintainers tag.\n\tMaintainers MaintainerSource\n\t// AuthorizeHTTP is called for private repositories and for operators that\n\t// want signed/NIP-98 authorization at the Git HTTP boundary.\n\tAuthorizeHTTP func(context.Context, *http.Request, Repository) error\n\t// ServiceURL is used to reject recursive GRASP sources and to construct\n\t// advertised clone URLs. It is optional for an embedded relay.\n\tServiceURL string\n\t// PublicURL is the canonical HTTPS URL used in repository advertisements;\n\t// ServiceURL is used when PublicURL is empty.\n\tPublicURL string\n\t// EnableGRASP06 enables the alternative PR repository surface. It is kept\n\t// opt-in because publishing a capability creates an interoperability\n\t// promise beyond the base GRASP-01 HTTP endpoint.\n\tEnableGRASP06 bool\n\t// AllowMissingObjects is ignored.\n\t// Missing objects enter the durable pending path and stay hidden until\n\t// receive-pack or repair supplies every advertised tip.\n\tAllowMissingObjects bool\n\t// AllowPrivateRelays permits operator-controlled private DNS targets for\n\t// self-hosted networks. Public deployments should leave it disabled.\n\tAllowPrivateRelays bool\n\t// PrivatePeers are operator-configured GRASP-08 origins. Only these\n\t// sources may receive signed outbound Git requests.\n\tPrivatePeers []string\n\t// HTTPAuth signs requests to configured private peers. It is never used for\n\t// sources that are merely present in a repository announcement.\n\tHTTPAuth HTTPAuthSigner\n\t// GitSync and EventSync are operator-owned transport callbacks. Keeping\n\t// transport outside this package allows native websocket/NIP-77, HTTP, or\n\t// an internal queue without making GRASP depend on one client library.\n\tGitSync   func(context.Context, Repository) error\n\tEventSync func(context.Context, Repository) error\n\t// OnPromote is called after a pending state becomes object-complete and\n\t// visible. The host relay uses it to release event visibility/live fanout.\n\tOnPromote func(context.Context, string, Repository) error\n}\n```\nConfig supplies the event store, Git root, authorization and transport hooks.\n\n```go\ntype Event = nostr.Event\n```\nEvent is the signed Nostr wire event accepted by the Git engine. Clients sign events themselves; the server never needs their private keys.\n\n```go\ntype GitBackup struct {\n\tFormat       string             `json:\"format\"`\n\tRepositories []BackupRepository `json:\"repositories\"`\n}\n```\nGitBackup is the complete bind.ws/git-sqlite/1 import document.\n\n```go\nfunc ValidateGitBackup(input []byte) (GitBackup, error)\n```\nValidateGitBackup validates an import document without writing Git state.\n\n```go\ntype GitRelay struct {\n\t// contains filtered or unexported fields\n}\n```\nGitRelay coordinates signed repository events with native bare repositories.\n\n```go\nfunc New(cfg Config) (*GitRelay, error)\n```\n\n```go\nfunc (g *GitRelay) AdmitSource(raw string) (string, error)\n```\nAdmitSource enforces the source restrictions from GRASP's Git sync model. Only HTTPS sources are accepted; localhost, private IPs, credentials, query/fragment data, and this relay itself are rejected.\n\n```go\nfunc (g *GitRelay) Browse(ctx context.Context, q BrowseRequest) (BrowsePage, error)\n```\nBrowse only reads objects reachable from materialized, signed public refs. It never checks out a working tree, invokes a shell, or follows a symlink.\n\n```go\nfunc (g *GitRelay) BrowseRepository(owner, identifier string) (Repository, error)\n```\n\n```go\nfunc (g *GitRelay) Capabilities() []string\n```\nCapabilities returns only protocol surfaces that this instance can serve.\n\n```go\nfunc (g *GitRelay) CommitAfterStore(ctx context.Context, e event.Event, repo Repository) error\n```\nCommitAfterStore applies the Git-side transition after the caller has durably saved the event. It intentionally does not call Store.Save.\n\n```go\nfunc (g *GitRelay) CommitAfterStoreNoNotify(ctx context.Context, e event.Event, repo Repository) error\n```\nCommitAfterStoreNoNotify stages the Git transition without invoking the host fanout callback. Use this while already inside the relay publish fence; the durable work intent will release visibility afterward.\n\n```go\nfunc (g *GitRelay) ConfigurePrivatePeers(peers []string, signer HTTPAuthSigner)\n```\nConfigurePrivatePeers refreshes operator-controlled private transport after a tenant policy update without reopening the Git store.\n\n```go\nfunc (g *GitRelay) DeletePRRef(ctx context.Context, identity, ref string) error\n```\nDeletePRRef removes a temporary GRASP-06 ref before its Nostr metadata is deleted. Identity accepts the source coordinates used by delivery jobs: pr:\\\u003cowner\u003e:\\\u003cidentifier\u003e or 30617:\\\u003cowner\u003e:\\\u003cidentifier\u003e.\n\n```go\nfunc (g *GitRelay) ExpirePending(ctx context.Context, eventIDs []string) error\n```\nExpirePending removes the file and in-memory authorities for state events whose retained deadline has elapsed. The SQL event sweep calls this before deleting the corresponding event so a stale journal cannot promote it after a restart.\n\n```go\nfunc (g *GitRelay) FetchMissing(ctx context.Context, r Repository, sources []string, expected map[string]string) error\n```\nFetchMissing downloads only the expected refs from an admitted source. Git verifies pack checksums and object connectivity; refs are installed only after every expected object exists locally.\n\n```go\nfunc (g *GitRelay) GRASPService() *Service\n```\n\n```go\nfunc (g *GitRelay) ImportGitBackup(ctx context.Context, input []byte) error\n```\nImportGitBackup installs a validated backup into empty native repositories. It refuses pre-existing refs or repositories to avoid silently mixing namespaces; callers can stage an import into a fresh Git root and swap it.\n\n```go\nfunc (g *GitRelay) IsMaintainer(ctx context.Context, r Repository, pubkey string) bool\n```\nIsMaintainer reports whether pubkey may sign state and push refs for a repository: the owner, a key in the announcement's maintainers tag, or a key the configured MaintainerSource vouches for. Every maintainer check in this package goes through here so the host's answer applies uniformly.\n\n```go\nfunc (g *GitRelay) IsPending(eventID string) bool\n```\nIsPending lets the event admission/read layer hide a metadata event until its signed Git tips are verified locally.\n\n```go\nfunc (g *GitRelay) PRDiff(ctx context.Context, r Repository, base, tip string) CollaborationDiff\n```\nPRDiff renders a bounded diff from commits already present in the repository. It never fetches or resolves a remote ref. A supplied base is used only after it is verified as a local commit; when it is empty, Git's merge-base with the repository target is used.\n\n```go\nfunc (g *GitRelay) PromotePending(ctx context.Context, repo Repository) error\n```\nPromotePending verifies and exposes a previously accepted state event. It is useful for local receive-pack integrations; ServeHTTP invokes it after a smart push as well.\n\n```go\nfunc (g *GitRelay) PruneRef(ctx context.Context, repository, ref string) error\n```\nPruneRef removes an expired native Git ref before its retained metadata is deleted. repository may be the storage key or its identifier.\n\n```go\nfunc (g *GitRelay) Publish(ctx context.Context, e event.Event) error\n```\nPublish validates and admits a signed repository announcement or state before saving it and staging the Git transition. Enabled GRASP-06 events use their separate admission path.\n\n```go\nfunc (g *GitRelay) Reload(ctx context.Context) error\n```\nReload rebuilds repository and pending indexes after a restore has inserted events and native Git repositories on disk.\n\n```go\nfunc (g *GitRelay) RepairPullRequestObjects(ctx context.Context, hosted Repository, set PullRequestRepair) error\n```\nRepairPullRequestObjects fetches the commits named by a NIP-34 PR and its updates into the supplied hosted repository.\n\nUpdates are accepted only from the PR author and must point to the root PR. This prevents an unrelated event from supplying a ref to a hosted PR.\n\n```go\nfunc (g *GitRelay) Repositories() []Repository\n```\nRepositories returns detached snapshots. Callers must enforce tenant and repository read permissions before revealing these records.\n\n```go\nfunc (g *GitRelay) ServeHTTP(w http.ResponseWriter, req *http.Request)\n```\nServeHTTP exposes Git smart HTTP at /npub/\\\u003cidentifier\u003e.git and /prs/... . The subprocess boundary keeps pack parsing and object integrity in Git.\n\n```go\nfunc (g *GitRelay) StorageInventory(ctx context.Context, owner, identifier string) (map[string]any, error)\n```\nStorageInventory reports retained bytes for one accepted repository. It is deliberately derived from the local object store so the self-hosted result has no hosted fuel or quota fields.\n\n```go\nfunc (g *GitRelay) SupportedGRASPs() []string\n```\nSupportedGRASPs is the NIP-11-facing capability list. It deliberately mirrors Capabilities so callers cannot advertise preview protocols by hand.\n\n```go\nfunc (g *GitRelay) Validate(ctx context.Context, e event.Event) (Repository, error)\n```\nValidate checks the signature and metadata shape, resolves repository authority, then applies host admission. Shape failures precede host callbacks. The caller must associate the returned authority with its event transaction. Validate has no store side effects and does not require Git objects locally.\n\n```go\nfunc (g *GitRelay) ValidateEvent(e event.Event) error\n```\nValidateEvent checks the wire shape, canonical ID and signature, not repository metadata shape or host admission. Use ParseMetadata for the pure metadata check, or Validate for the complete admission boundary.\n\n```go\nfunc (g *GitRelay) ValidateImported(ctx context.Context, e event.Event) (Repository, error)\n```\nValidateImported admits metadata received through an explicitly synchronized relay. Local announcements continue through Validate.\n\n```go\nfunc (g *GitRelay) WriteSource(ctx context.Context, q BrowseRequest, dst io.Writer) error\n```\nWriteSource streams a published source blob directly to the destination.\n\n```go\ntype HTTPAuthSigner func(context.Context, string, string, string) (string, error)\n```\nHTTPAuthSigner returns the authorization header for a private peer request. GRASP-08 callers receive the repository root, GET and an empty payload hash; it is deliberately a callback so GitRelay never owns private keys.\n\n```go\ntype Maintainer struct {\n\tPubKey string `json:\"pubkey\"`\n\tRole   string `json:\"role\"`\n\tName   string `json:\"name,omitempty\"`\n}\n```\nMaintainer is one key that may sign repository state, push refs and change status. Role is \"owner\", \"maintainer\" for a key in the announcement's maintainers tag, or \"agent\" for a key the host vouches for under an agent grant; Name carries the grant's label when it has one.\n\n```go\ntype MaintainerSource interface {\n\tIsMaintainer(ctx context.Context, r Repository, pubkey string) bool\n}\n```\nMaintainerSource answers whether a key maintains a repository beyond the owner and the announcement's maintainers tag. The host relay supplies it so authority it records elsewhere, such as an agent grant, counts in every place this package checks maintainers.\n\n```go\ntype Metadata struct {\n\tKind        int\n\tAuthor      string\n\tIdentifier  string\n\tEventID     string\n\tPrivate     bool\n\tClone       []string\n\tRelays      []string\n\tMaintainers []string\n\tRefs        map[string]string\n\tHead        string\n}\n```\nMetadata contains the claims parsed from a repository announcement (kind 30617) or state (kind 30618). Author is the event's claimed signer, not a resolved repository owner. Announcement fields are not inherited by states. A Metadata value conveys neither signature validity nor hosting authority.\n\n```go\nfunc ParseMetadata(e nostr.Event) (Metadata, error)\n```\nParseMetadata checks and parses tinygit's supported repository metadata shape: identifier, state ref names and nonzero SHA-1 tips, and symbolic HEAD syntax. HEAD may name a branch or tag not present in Refs, including an unborn branch. Unknown tags and supported extension fields are ignored.\n\nThis is a pure shape/semantic check, not full NIP or GRASP compliance. It does not validate the event ID or signature, consult announcements or maintainers, authorize hosting, check clone or relay endpoints, or inspect Git objects. Use nostr.Validate separately before trusting Author. GitRelay.Validate and ValidateImported combine signature validation, this parser and host admission; missing Git objects remain a separate pending-state concern.\n\n```go\ntype Policy struct {\n\tOwner        string\n\tReads        string\n\tPrivatePeers []string\n\tFeatures     PolicyFeatures\n}\n```\nPolicy contains the policy values used by the Git engine. Hosts may keep a richer policy internally and adapt these values at the integration boundary.\n\n```go\nfunc DefaultPolicy(owner string) Policy\n```\nDefaultPolicy returns the defaults for an embedded engine.\n\n```go\nfunc (p Policy) PrivateServiceEnabled() bool\n```\n\n```go\ntype PolicyFeatures struct {\n\tGrasp   bool\n\tGrasp02 bool\n\tGrasp03 bool\n\tGrasp05 bool\n\tGrasp06 bool\n\tGrasp08 bool\n}\n```\nPolicyFeatures selects optional Git protocol capabilities.\n\n```go\ntype PullRequestRepair struct {\n\tRoot    event.Event\n\tUpdates []event.Event\n}\n```\nPullRequestRepair groups a PR with its later tip updates. The event store remains the authority for these events; this value only describes the Git objects that GRASP-02 should fetch for them.\n\n```go\ntype Repository struct {\n\tOwner       string\n\tIdentifier  string\n\tEventID     string\n\tPrivate     bool\n\tClone       []string\n\tRelays      []string\n\tMaintainers []string\n\tRefs        map[string]string\n\tHead        string\n\tAlternative bool\n}\n```\nRepository is the resolved authority and Git state for one hosted project.\n\n```go\ntype RepositorySyncStatus struct {\n\tAttemptedAt int64  `json:\"attempted_at\"`\n\tSucceededAt int64  `json:\"succeeded_at,omitempty\"`\n\tNextAt      int64  `json:\"next_at,omitempty\"`\n\tFingerprint string `json:\"fingerprint,omitempty\"`\n\tAttempts    int    `json:\"attempts\"`\n\tError       string `json:\"error,omitempty\"`\n}\n```\nRepositorySyncStatus is the durable status of one GRASP reconciliation job.\n\n```go\ntype Server struct {\n\t// contains filtered or unexported fields\n}\n```\nServer owns a Git engine and durable SQLite metadata, without a relay daemon, WebSocket service, UI or replication workers. POST /events accepts signed repository metadata. Other paths are handled by Git smart HTTP.\n\n```go\nfunc OpenServer(ctx context.Context, cfg ServerConfig) (*Server, error)\n```\nOpenServer opens the standalone host. Stop all HTTP requests before Close.\n\n```go\nfunc (s *Server) Close() error\n```\nClose releases metadata storage. The caller must first stop serving requests.\n\n```go\nfunc (s *Server) Publish(ctx context.Context, e Event) error\n```\nPublish validates and persists a signed announcement (30617) or ref state (30618). Repeated events retry the Git transition after a partial failure.\n\n```go\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\n\n```go\ntype ServerConfig struct {\n\tDataDir   string\n\tOwner     string\n\tPublicURL string\n}\n```\nServerConfig configures the standalone public Git host. Use a dedicated DataDir, not a running tinyrelay tenant's database or Git directory.\n\n```go\ntype Service struct {\n\t// contains filtered or unexported fields\n}\n```\nService is the durable GRASP scheduler boundary. Tick is safe to call from a daemon ticker and runs one pass over the currently accepted repositories. Callback progress is persisted so a restart does not lose the last pass.\n\n```go\nfunc (s *Service) SyncStatus(ctx context.Context) (SyncStatus, error)\n```\n\n```go\nfunc (s *Service) Tick(ctx context.Context) error\n```\n\n```go\ntype Store interface {\n\t// Query returns matching events by descending timestamp, then ascending ID,\n\t// excluding expired, hidden and pending events without applying reader ACLs.\n\t// now is the Unix expiry cutoff. A positive limit caps the result; f.Limit\n\t// can impose a smaller cap. With neither limit, all matches are returned.\n\tQuery(context.Context, nostr.Filter, int64, int) ([]Event, error)\n\t// Save durably records e using now for storage timestamps. Duplicate events\n\t// return ErrDuplicate.\n\tSave(context.Context, Event, int64) error\n\t// Latest returns the newest addressable event for kind, pubkey and d.\n\t// Ties use the lowest event ID. This includes expired, hidden and pending\n\t// rows so recovery can check durable state independently of read visibility.\n\tLatest(context.Context, int, string, string) (Event, bool, error)\n\t// Exists reports whether id is present with the requested kind.\n\tExists(context.Context, string, int) (bool, error)\n\t// Close releases resources owned by the store.\n\tClose() error\n}\n```\nStore is the persistence contract required by GitRelay. Implementations may use any durable or in-memory representation of Nostr events. The caller owns the store; New never closes it.\n\n```go\nfunc OpenStore(ctx context.Context, path string) (Store, error)\n```\nOpenStore opens the standard SQLite event schema behind the public Store contract. The caller owns the returned store and must close it.\n\n```go\ntype SyncStatus struct {\n\tAt           int64                           `json:\"at\"`\n\tLastKey      string                          `json:\"last_key\"`\n\tRepositories map[string]RepositorySyncStatus `json:\"repositories,omitempty\"`\n}\n```\nSyncStatus is a read-only snapshot suitable for relay status pages.\n\n","path":"github.com/FelineStateMachine/tinyrelay/tinygit","name":"tinygit","synopsis":"Package tinygit coordinates signed Nostr repository events with native Git object storage and smart HTTP.","isRedistributable":true}
