progmaweb
The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.
Clonegit clone https://git.progmasoft.com/progmaweb
Serve git.progmasoft.com from the Next.js site instead of cgit
- Commit
1228332e2584adba4725efb69b5e8ce9a4a7de77- Author
- Leitwolf11 ·
- Parents
2bddd37ebc67
Changes
README.md | 2 + apps/api-tests/AccountApiFactory.cs | 9 +- apps/api-tests/GitTests.cs | 276 ++++++++ apps/api/Git/GitCatalog.cs | 133 ++++ apps/api/Git/GitEndpoints.cs | 336 ++++++++++ apps/api/Git/GitReader.cs | 477 ++++++++++++++ apps/api/Program.cs | 20 + apps/api/appsettings.json | 2 +- apps/web/app/git/GitFrame.tsx | 127 ++++ apps/web/app/git/GitViews.tsx | 168 +++++ apps/web/app/git/[repo]/commit/[sha]/page.tsx | 118 ++++ apps/web/app/git/[repo]/log/page.tsx | 68 ++ apps/web/app/git/[repo]/page.tsx | 90 +++ apps/web/app/git/[repo]/refs/page.tsx | 99 +++ apps/web/app/git/[repo]/tree/page.tsx | 55 ++ apps/web/app/git/git.css | 210 ++++++ apps/web/app/git/layout.tsx | 12 + apps/web/app/git/page.tsx | 50 ++ apps/web/app/git/params.ts | 23 + apps/web/app/robots.ts | 3 +- apps/web/app/sitemap.ts | 3 + apps/web/e2e/fake-git-api.mjs | 131 ++++ apps/web/e2e/pages.ts | 6 + apps/web/lib/git-messages.ts | 235 +++++++ apps/web/lib/git.server.ts | 143 ++++ apps/web/playwright.config.ts | 24 +- apps/web/proxy.ts | 7 + apps/web/tests/sites.test.mjs | 29 + docs/ACCOUNT-API.md | 4 +- docs/ARCHITECTURE.md | 13 +- ops/README.md | 54 +- ops/git/catalog.json | 39 ++ ops/git/cgitrc | 67 -- ops/git/git-mirror.sh | 3 - ops/git/include/footer.html | 6 - ops/git/include/head.html | 2 - ops/git/include/header.html | 19 - ops/git/nginx/git.conf | 62 +- ops/git/repositories | 2 +- ops/git/selinux/progmasoft_cgit.te | 18 - ops/git/selinux/progmasoft_githttp.te | 18 + ops/git/static/icon.svg | 7 - ops/git/static/progmasoft-git.css | 730 --------------------- .../hardening.conf | 7 +- .../processes.conf | 4 +- .../nginx.conf | 2 +- 46 files changed, 2985 insertions(+), 928 deletions(-) diff --git a/README.md b/README.md index d46e053..dbf4801 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ the ASP.NET Core API. issuer, the pages people sign in and consent on, and the Progmasoft Console. See [Progmasoft OAuth](docs/OAUTH.md). - `product.progmasoft.com` serves the product catalog, and `license.progmasoft.com` the Progmasoft Source License. - `agencelandmcp.progmasoft.com` serves the Agenceland MCP Marketplace, which lists no server and takes no uploads. +- `git.progmasoft.com` serves the read-only mirrors of the repositories: pages from Next.js, raw files and archives from + the API, clones from git-http-backend. The same Nginx file also answers `viget.progmasoft.com` with 410 Gone, sends `catch3.progmasoft.com` to `catch3.uk`, and serves the Maven repository on `maven.progmasoft.com`; [Operations](ops/README.md) describes those and the other diff --git a/apps/api-tests/AccountApiFactory.cs b/apps/api-tests/AccountApiFactory.cs index ae98e88..65f602d 100644 --- a/apps/api-tests/AccountApiFactory.cs +++ b/apps/api-tests/AccountApiFactory.cs @@ -25,7 +25,8 @@ internal sealed class AccountApiFactory( string? accountDatabase = null, string environment = "Testing", string? accountStore = null, - bool oauthKeys = true) : WebApplicationFactory<Program> + bool oauthKeys = true, + string? gitDirectory = null) : WebApplicationFactory<Program> { private readonly string keyDirectory = Path.Combine(Path.GetTempPath(), "progmaweb-oauth-keys-" + Guid.NewGuid().ToString("N")); @@ -52,7 +53,11 @@ internal sealed class AccountApiFactory( builder.UseSetting("OAuth:AuthorizeHost", AuthorizeHost); builder.UseSetting("OAuth:ConsoleHost", ConsoleHost); builder.UseSetting("AllowedHosts", - $"localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;{OAuthHost};{AuthorizeHost};{ConsoleHost}"); + $"localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;{OAuthHost};{AuthorizeHost};{ConsoleHost};git.progmasoft.com"); + // The mirrors of git.progmasoft.com: a directory of the test, or one that does not exist. + string git = gitDirectory ?? Path.Combine(Path.GetTempPath(), "progmaweb-no-git-" + Guid.NewGuid().ToString("N")); + builder.UseSetting("Git:MirrorsPath", Path.Combine(git, "mirrors")); + builder.UseSetting("Git:CatalogPath", Path.Combine(git, "catalog.json")); if (oauthKeys && environment == "Production") { Directory.CreateDirectory(keyDirectory); diff --git a/apps/api-tests/GitTests.cs b/apps/api-tests/GitTests.cs new file mode 100644 index 0000000..e6736b7 --- /dev/null +++ b/apps/api-tests/GitTests.cs @@ -0,0 +1,276 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +using System.Diagnostics; +using System.Net; +using System.Text.Json; +using Microsoft.Extensions.Options; +using Progmasoft.Progmaweb.Api.Git; + +namespace Progmasoft.Progmaweb.Api.Tests; + +/// <summary>A bare mirror made for the tests: two commits on main, a branch with a slash and a tag.</summary> +public sealed class GitFixture : IDisposable +{ + public GitFixture() + { + Directory.CreateDirectory(Path.Combine(Root, "mirrors")); + string work = Path.Combine(Root, "work"); + Directory.CreateDirectory(Path.Combine(work, "src")); + Git(work, "init", "--quiet", "--initial-branch=main"); + File.WriteAllText(Path.Combine(work, "README.md"), "# Sample\n"); + File.WriteAllText(Path.Combine(work, "src", "main.c"), "int main(void) { return 0; }\n"); + File.WriteAllBytes(Path.Combine(work, "logo.bin"), [0x89, 0x50, 0x00, 0x01, 0x02]); + Git(work, "add", "--all"); + Git(work, "commit", "--quiet", "-m", "First\n\nThe body."); + First = Git(work, "rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Combine(work, "src", "main.c"), "int main(void) { return 1; }\n"); + Git(work, "commit", "--quiet", "--all", "-m", "Second"); + Second = Git(work, "rev-parse", "HEAD").Trim(); + Git(work, "tag", "-a", "sample-1.0.0", "-m", "Release", First); + Git(work, "branch", "feature/slash", First); + Git(Root, "clone", "--quiet", "--bare", work, Path.Combine(Root, "mirrors", "sample.git")); + File.WriteAllText(Path.Combine(Root, "catalog.json"), """ + { "sections": [ + { "name": "Samples", "repositories": [ + { "name": "sample", "description": "A sample." }, + { "name": "absent", "description": "Listed, but not mirrored." } ] } ] } + """); + } + + public string Root { get; } = Path.Combine(Path.GetTempPath(), "progmaweb-git-" + Guid.NewGuid().ToString("N")); + + public string First { get; } + + public string Second { get; } + + public string Mirror => Path.Combine(Root, "mirrors", "sample.git"); + + internal IOptions<GitOptions> Options => Microsoft.Extensions.Options.Options.Create(new GitOptions + { + MirrorsPath = Path.Combine(Root, "mirrors"), + CatalogPath = Path.Combine(Root, "catalog.json"), + GitPath = "git" + }); + + public void Dispose() => Directory.Delete(Root, recursive: true); + + private static string Git(string directory, params string[] arguments) + { + ProcessStartInfo start = new("git") { WorkingDirectory = directory, RedirectStandardOutput = true }; + foreach (string argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.Environment["GIT_AUTHOR_NAME"] = "Sample Author"; + start.Environment["GIT_AUTHOR_EMAIL"] = "author@example.com"; + start.Environment["GIT_COMMITTER_NAME"] = "Sample Author"; + start.Environment["GIT_COMMITTER_EMAIL"] = "author@example.com"; + start.Environment["GIT_CONFIG_GLOBAL"] = "/dev/null"; + using Process process = Process.Start(start)!; + string output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + Assert.Equal(0, process.ExitCode); + return output; + } +} + +/// <summary>git.progmasoft.com: what the API reads from a mirror, and what it refuses.</summary> +public sealed class GitTests(GitFixture fixture) : IClassFixture<GitFixture> +{ + private static CancellationToken Cancellation => TestContext.Current.CancellationToken; + + private GitReader Reader => new(fixture.Options); + + [Theory] + [InlineData("main", true)] + [InlineData("feature/slash", true)] + [InlineData("tazel-0.1.0", true)] + [InlineData("-n", false)] + [InlineData("--output=/tmp/x", false)] + [InlineData("main..HEAD", false)] + [InlineData("a//b", false)] + [InlineData("/main", false)] + [InlineData("main/", false)] + [InlineData("x.lock", false)] + [InlineData(".hidden", false)] + [InlineData("a/.hidden", false)] + [InlineData("HEAD@{1}", false)] + [InlineData("main~1", false)] + [InlineData("", false)] + public void OnlyPlainBranchAndTagNamesAreReferences(string name, bool expected) => + Assert.Equal(expected, GitReader.IsRefName(name)); + + [Theory] + [InlineData("", true)] + [InlineData("src/main.c", true)] + [InlineData("a b/c", true)] + [InlineData("../etc/passwd", false)] + [InlineData("src/../../x", false)] + [InlineData("src//main.c", false)] + [InlineData("./src", false)] + [InlineData("src/\nmain", false)] + public void APathStaysInsideTheTree(string path, bool expected) => Assert.Equal(expected, GitReader.IsTreePath(path)); + + [Fact] + public void ACommitIsAFullIdentifier() + { + Assert.True(GitReader.IsCommitId(fixture.First)); + Assert.True(GitReader.IsCommitId(new string('a', 64))); + Assert.False(GitReader.IsCommitId(fixture.First[..12])); + Assert.False(GitReader.IsCommitId(fixture.First.ToUpperInvariant())); + Assert.False(GitReader.IsCommitId("HEAD")); + } + + [Fact] + public async Task BranchesTagsAndCommitsResolveAndNothingElseDoes() + { + GitReader git = Reader; + Assert.Equal("main", await git.DefaultBranchAsync(fixture.Mirror, Cancellation)); + Assert.Equal(fixture.Second, await git.ResolveAsync(fixture.Mirror, "main", Cancellation)); + Assert.Equal(fixture.First, await git.ResolveAsync(fixture.Mirror, "feature/slash", Cancellation)); + // An annotated tag resolves to its commit. + Assert.Equal(fixture.First, await git.ResolveAsync(fixture.Mirror, "sample-1.0.0", Cancellation)); + Assert.Equal(fixture.First, await git.ResolveAsync(fixture.Mirror, fixture.First, Cancellation)); + foreach (string other in new[] { "HEAD", "main~1", "--all", "missing", new string('0', 40) }) + { + Assert.Null(await git.ResolveAsync(fixture.Mirror, other, Cancellation)); + } + } + + [Fact] + public async Task TreesBlobsLogsCommitsAndRefsReadTheMirror() + { + GitReader git = Reader; + IReadOnlyList<GitTreeEntry> root = await git.TreeAsync(fixture.Mirror, fixture.Second, "", Cancellation); + Assert.Equal(["src", "README.md", "logo.bin"], root.Select(entry => entry.Name)); + Assert.Equal("tree", root[0].Kind); + Assert.Equal(9, root[1].Size); + Assert.Equal("tree", await git.KindAsync(fixture.Mirror, fixture.Second, "src", Cancellation)); + Assert.Equal("blob", await git.KindAsync(fixture.Mirror, fixture.Second, "src/main.c", Cancellation)); + Assert.Null(await git.KindAsync(fixture.Mirror, fixture.Second, "nothing", Cancellation)); + + (byte[] bytes, bool isTruncated) = await git.BlobAsync(fixture.Mirror, fixture.Second, "src/main.c", 10, Cancellation); + Assert.Equal("int main(v"u8.ToArray(), bytes); + Assert.True(isTruncated); + + (IReadOnlyList<GitLogEntry> commits, bool hasMore) = await git.LogAsync(fixture.Mirror, fixture.Second, "", 0, Cancellation); + Assert.Equal(["Second", "First"], commits.Select(entry => entry.Subject)); + Assert.Equal("Sample Author", commits[0].Author); + Assert.False(hasMore); + (commits, _) = await git.LogAsync(fixture.Mirror, fixture.Second, "README.md", 0, Cancellation); + Assert.Equal(["First"], commits.Select(entry => entry.Subject)); + + GitCommitDetails details = await git.CommitAsync(fixture.Mirror, fixture.Second, Cancellation); + Assert.Equal([fixture.First], details.Parents); + Assert.Contains("-int main(void) { return 0; }", details.Diff, StringComparison.Ordinal); + Assert.Contains("+int main(void) { return 1; }", details.Diff, StringComparison.Ordinal); + GitCommitDetails first = await git.CommitAsync(fixture.Mirror, fixture.First, Cancellation); + Assert.Equal("First\n\nThe body.", first.Message); + Assert.Empty(first.Parents); + + (IReadOnlyList<GitRef> branches, IReadOnlyList<GitRef> tags) = await git.RefsAsync(fixture.Mirror, Cancellation); + Assert.Equal(["feature/slash", "main"], branches.Select(branch => branch.Name).Order()); + GitRef tag = Assert.Single(tags); + Assert.Equal("sample-1.0.0", tag.Name); + Assert.Equal(fixture.First, tag.Commit); + } + + [Fact] + public async Task AnArchiveIsAGzipOfTheCommit() + { + using MemoryStream archive = new(); + await Reader.ArchiveAsync(fixture.Mirror, fixture.Second, "sample-main/", archive, Cancellation); + byte[] bytes = archive.ToArray(); + Assert.True(bytes.Length > 20); + Assert.Equal([0x1f, 0x8b], bytes[..2]); + } + + [Fact] + public void TheCatalogShowsOnlyMirroredRepositories() + { + GitCatalog catalog = new(fixture.Options); + Assert.NotNull(catalog.Find("sample")); + Assert.Null(catalog.Find("absent")); + Assert.Null(catalog.Find("../sample")); + Assert.Null(catalog.Find("sample.git")); + Assert.Equal("Samples", Assert.Single(catalog.Sections()).Name); + } + + [Fact] + public void TheInstalledCatalogNamesWhatIsMirrored() + { + string ops = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "ops", "git"); + string[] mirrored = + [ + .. File.ReadAllLines(Path.Combine(ops, "repositories")) + .Select(line => line.Trim()) + .Where(line => line.Length > 0 && !line.StartsWith('#')) + .Order(StringComparer.Ordinal) + ]; + using JsonDocument catalog = JsonDocument.Parse(File.ReadAllText(Path.Combine(ops, "catalog.json"))); + string[] shown = + [ + .. catalog.RootElement.GetProperty("sections").EnumerateArray() + .SelectMany(section => section.GetProperty("repositories").EnumerateArray()) + .Select(repository => repository.GetProperty("name").GetString()!) + .Order(StringComparer.Ordinal) + ]; + Assert.Equal(mirrored, shown); + } + + [Fact] + public async Task TheEndpointsAnswerOnTheGitHostAndLoopbackOnly() + { + await using AccountApiFactory factory = new(gitDirectory: fixture.Root); + using HttpClient loopback = factory.CreateClient(); + HttpResponseMessage listing = await loopback.GetAsync(new Uri("/api/v1/git/repositories/", UriKind.Relative), Cancellation); + Assert.Equal(HttpStatusCode.OK, listing.StatusCode); + Assert.Contains("\"sample\"", await listing.Content.ReadAsStringAsync(Cancellation), StringComparison.Ordinal); + + HttpResponseMessage tree = await loopback.GetAsync( + new Uri("/api/v1/git/repositories/sample/tree?path=logo.bin", UriKind.Relative), Cancellation); + using (JsonDocument blob = JsonDocument.Parse(await tree.Content.ReadAsStringAsync(Cancellation))) + { + Assert.True(blob.RootElement.GetProperty("isBinary").GetBoolean()); + Assert.Equal(JsonValueKind.Null, blob.RootElement.GetProperty("text").ValueKind); + } + + HttpResponseMessage raw = await loopback.GetAsync( + new Uri("/api/v1/git/repositories/sample/raw?path=logo.bin", UriKind.Relative), Cancellation); + Assert.Equal("application/octet-stream", raw.Content.Headers.ContentType?.MediaType); + Assert.Equal("attachment", raw.Content.Headers.ContentDisposition?.DispositionType); + raw = await loopback.GetAsync(new Uri("/api/v1/git/repositories/sample/raw?path=README.md", UriKind.Relative), Cancellation); + Assert.Equal("text/plain", raw.Content.Headers.ContentType?.MediaType); + Assert.Equal("# Sample\n", await raw.Content.ReadAsStringAsync(Cancellation)); + + foreach (string refused in new[] + { + "/api/v1/git/repositories/absent", + "/api/v1/git/repositories/sample/tree?path=../x", + "/api/v1/git/repositories/sample/tree?ref=--all", + "/api/v1/git/repositories/sample/commits/HEAD", + "/api/v1/git/repositories/sample/raw?path=src", + "/api/v1/git/repositories/sample/log?page=-1" + }) + { + HttpResponseMessage response = await loopback.GetAsync(new Uri(refused, UriKind.Relative), Cancellation); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + using HttpClient gitHost = factory.CreateClient(new() { BaseAddress = new Uri("https://git.progmasoft.com") }); + Assert.Equal(HttpStatusCode.OK, (await gitHost.GetAsync(new Uri("/api/v1/git/repositories/sample/archive", UriKind.Relative), Cancellation)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await gitHost.GetAsync(new Uri("/api/v1/accounts/me", UriKind.Relative), Cancellation)).StatusCode); + + using HttpClient account = factory.CreateClient(new() { BaseAddress = new Uri("https://account.progmasoft.com") }); + Assert.Equal(HttpStatusCode.NotFound, (await account.GetAsync(new Uri("/api/v1/git/repositories/", UriKind.Relative), Cancellation)).StatusCode); + } + + [Theory] + [InlineData("dir/report v2.pdf", "report_v2.pdf")] + [InlineData("a\"b", "a_b")] + [InlineData("", "file")] + public void ADownloadIsNamedWithSafeCharactersOnly(string path, string expected) => + Assert.Equal(expected, GitEndpoints.SafeFileName(path)); +} diff --git a/apps/api/Git/GitCatalog.cs b/apps/api/Git/GitCatalog.cs new file mode 100644 index 0000000..e79a82a --- /dev/null +++ b/apps/api/Git/GitCatalog.cs @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.Extensions.Options; + +namespace Progmasoft.Progmaweb.Api.Git; + +/// <summary>Where the read-only mirrors of git.progmasoft.com are and how they are read.</summary> +internal sealed class GitOptions +{ + /// <summary>The section of the configuration.</summary> + public const string Section = "Git"; + + /// <summary>The host the mirrors are shown on.</summary> + public string Host { get; set; } = "git.progmasoft.com"; + + /// <summary>The directory of the bare mirrors, <c><name>.git</c> each.</summary> + public string MirrorsPath { get; set; } = "/srv/git/mirrors"; + + /// <summary>The catalog: the sections, the repositories in them and their descriptions.</summary> + public string CatalogPath { get; set; } = "/etc/git-mirror/catalog.json"; + + /// <summary>The Git program.</summary> + public string GitPath { get; set; } = "/usr/bin/git"; +} + +/// <summary>One repository of the catalog.</summary> +/// <param name="Name">Its name, the same on GitHub and in the mirrors.</param> +/// <param name="Description">What it is.</param> +internal sealed record GitCatalogRepository(string Name, string Description); + +/// <summary>One section of the catalog.</summary> +/// <param name="Name">Its heading.</param> +/// <param name="Repositories">Its repositories, in the order shown.</param> +internal sealed record GitCatalogSection(string Name, IReadOnlyList<GitCatalogRepository> Repositories); + +/// <summary>The repositories git.progmasoft.com shows, read from the catalog file.</summary> +/// <remarks> +/// The file is <c>ops/git/catalog.json</c>, installed beside the list <c>git-mirror</c> reads; a repository that is in +/// the catalog but has no mirror is not shown. The file is read again when it changes. +/// </remarks> +/// <param name="options">Where the catalog is.</param> +internal sealed partial class GitCatalog(IOptions<GitOptions> options) +{ + private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; + + private readonly Lock gate = new(); + + private (DateTime Written, IReadOnlyList<GitCatalogSection> Sections)? cached; + + /// <summary>Whether a text is a repository name: what GitHub allows, without a leading dot.</summary> + [GeneratedRegex("^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$", RegexOptions.CultureInvariant)] + private static partial Regex NamePattern(); + + /// <summary>Whether a text is a repository name.</summary> + /// <param name="name">The text.</param> + /// <returns><see langword="true"/> when it is one.</returns> + public static bool IsName(string name) => NamePattern().IsMatch(name) && !name.EndsWith(".git", StringComparison.Ordinal); + + /// <summary>The sections, with only the repositories that have a mirror.</summary> + /// <returns>The sections; empty when there is no catalog.</returns> + public IReadOnlyList<GitCatalogSection> Sections() + { + string path = options.Value.CatalogPath; + DateTime written = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; + lock (gate) + { + if (cached is { } known && known.Written == written) + { + return known.Sections; + } + + IReadOnlyList<GitCatalogSection> sections = written == DateTime.MinValue ? [] : Read(path); + cached = (written, sections); + return sections; + } + } + + /// <summary>One repository by name, when the catalog has it and its mirror exists.</summary> + /// <param name="name">The name.</param> + /// <returns>The repository and the path of its mirror, or <see langword="null"/>.</returns> + public (GitCatalogRepository Repository, string MirrorPath)? Find(string name) + { + if (!IsName(name)) + { + return null; + } + + foreach (GitCatalogSection section in Sections()) + { + foreach (GitCatalogRepository repository in section.Repositories) + { + if (string.Equals(repository.Name, name, StringComparison.Ordinal)) + { + string mirror = MirrorOf(repository.Name); + return Directory.Exists(mirror) ? (repository, mirror) : null; + } + } + } + + return null; + } + + /// <summary>The path of a repository's mirror.</summary> + /// <param name="name">A valid name.</param> + /// <returns>The path.</returns> + public string MirrorOf(string name) => Path.Combine(options.Value.MirrorsPath, name + ".git"); + + private static IReadOnlyList<GitCatalogSection> Read(string path) + { + using FileStream stream = File.OpenRead(path); + GitCatalogFile file = JsonSerializer.Deserialize<GitCatalogFile>(stream, JsonOptions) + ?? throw new InvalidDataException($"{path} is empty."); + foreach (GitCatalogSection section in file.Sections) + { + foreach (GitCatalogRepository repository in section.Repositories) + { + if (!IsName(repository.Name)) + { + throw new InvalidDataException($"{path} names a repository '{repository.Name}' that is not a name."); + } + } + } + + return file.Sections; + } + + /// <summary>The shape of the catalog file.</summary> + /// <param name="Sections">The sections.</param> + private sealed record GitCatalogFile(IReadOnlyList<GitCatalogSection> Sections); +} diff --git a/apps/api/Git/GitEndpoints.cs b/apps/api/Git/GitEndpoints.cs new file mode 100644 index 0000000..c5cd629 --- /dev/null +++ b/apps/api/Git/GitEndpoints.cs @@ -0,0 +1,336 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +using System.Text; +using Microsoft.Extensions.Options; + +namespace Progmasoft.Progmaweb.Api.Git; + +/// <summary>A repository in a listing.</summary> +/// <param name="Name">Its name.</param> +/// <param name="Description">What it is.</param> +/// <param name="Homepage">Where it is developed, on GitHub.</param> +/// <param name="CloneUrl">Where it is cloned from.</param> +/// <param name="DefaultBranch">Its default branch.</param> +/// <param name="UpdatedAt">When its default branch last changed.</param> +internal sealed record GitRepositoryResponse( + string Name, + string Description, + string Homepage, + string CloneUrl, + string? DefaultBranch, + DateTimeOffset? UpdatedAt); + +/// <summary>A section of the listing.</summary> +/// <param name="Name">Its heading.</param> +/// <param name="Repositories">Its repositories.</param> +internal sealed record GitSectionResponse(string Name, IReadOnlyList<GitRepositoryResponse> Repositories); + +/// <summary>What is at a path of a commit.</summary> +/// <param name="Reference">The branch, tag or commit the request named.</param> +/// <param name="Commit">The commit it resolved to.</param> +/// <param name="Path">The path; empty for the root.</param> +/// <param name="Kind"><c>tree</c> or <c>blob</c>.</param> +/// <param name="Entries">The entries of a tree; null for a blob.</param> +/// <param name="Size">The size of a blob; null for a tree.</param> +/// <param name="IsBinary">Whether the blob is not text; a binary blob carries no text.</param> +/// <param name="Text">The text of a blob up to <see cref="GitReader.MaxTextBytes"/>.</param> +/// <param name="IsTruncated">Whether the text was cut.</param> +internal sealed record GitTreeResponse( + string Reference, + string Commit, + string Path, + string Kind, + IReadOnlyList<GitTreeEntry>? Entries, + long? Size, + bool IsBinary, + string? Text, + bool IsTruncated); + +/// <summary>The read-only mirrors of git.progmasoft.com, for the pages of the Progmasoft site.</summary> +/// <remarks> +/// The pages are rendered by Next.js on the same host, which calls these endpoints on loopback. Two of them reach the +/// browser through Nginx: the raw files and the archives. Clones are served by git-http-backend, not here. +/// </remarks> +internal static class GitEndpoints +{ + /// <summary>The prefix of every endpoint.</summary> + public const string Prefix = "/api/v1/git"; + + /// <summary>Maps the endpoints.</summary> + /// <param name="app">The application.</param> + public static void MapGitEndpoints(this WebApplication app) + { + RouteGroupBuilder api = app.MapGroup(Prefix + "/repositories").RequireRateLimiting("git"); + api.MapGet("/", ListAsync); + api.MapGet("/{name}", ShowAsync); + api.MapGet("/{name}/refs", RefsAsync); + api.MapGet("/{name}/tree", TreeAsync); + api.MapGet("/{name}/log", LogAsync); + api.MapGet("/{name}/commits/{commit}", CommitAsync); + api.MapGet("/{name}/raw", RawAsync); + api.MapGet("/{name}/archive", ArchiveAsync); + } + + private static string Homepage(string name) => $"https://github.com/Progmasoft/{name}"; + + private static string CloneUrl(IOptions<GitOptions> options, string name) => $"https://{options.Value.Host}/{name}"; + + private static async Task<IResult> ListAsync( + GitCatalog catalog, + GitReader git, + IOptions<GitOptions> options, + CancellationToken cancellationToken) + { + List<GitSectionResponse> sections = []; + foreach (GitCatalogSection section in catalog.Sections()) + { + List<GitRepositoryResponse> repositories = []; + foreach (GitCatalogRepository repository in section.Repositories) + { + if (catalog.Find(repository.Name) is not { } found) + { + continue; + } + + repositories.Add(await DescribeAsync(git, options, found.Repository, found.MirrorPath, cancellationToken)); + } + + if (repositories.Count > 0) + { + sections.Add(new GitSectionResponse(section.Name, repositories)); + } + } + + return Results.Ok(sections); + } + + private static async Task<GitRepositoryResponse> DescribeAsync( + GitReader git, + IOptions<GitOptions> options, + GitCatalogRepository repository, + string mirror, + CancellationToken cancellationToken) + { + string? branch = await git.DefaultBranchAsync(mirror, cancellationToken); + DateTimeOffset? updated = null; + if (branch is not null && await git.ResolveAsync(mirror, branch, cancellationToken) is { } head) + { + (IReadOnlyList<GitLogEntry> commits, _) = await git.LogAsync(mirror, head, "", 0, cancellationToken); + updated = commits.Count > 0 ? commits[0].Date : null; + } + + return new GitRepositoryResponse( + repository.Name, repository.Description, Homepage(repository.Name), CloneUrl(options, repository.Name), branch, updated); + } + + private static async Task<IResult> ShowAsync( + string name, + GitCatalog catalog, + GitReader git, + IOptions<GitOptions> options, + CancellationToken cancellationToken) => + catalog.Find(name) is { } found + ? Results.Ok(await DescribeAsync(git, options, found.Repository, found.MirrorPath, cancellationToken)) + : Results.NotFound(); + + private static async Task<IResult> RefsAsync( + string name, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (catalog.Find(name) is not { } found) + { + return Results.NotFound(); + } + + (IReadOnlyList<GitRef> branches, IReadOnlyList<GitRef> tags) = await git.RefsAsync(found.MirrorPath, cancellationToken); + return Results.Ok(new { branches, tags }); + } + + /// <summary>Finds the mirror, the commit a reference names (the default branch without one) and checks a path.</summary> + private static async Task<(string Mirror, string Reference, string Commit, string Path)?> LocateAsync( + string name, + string? reference, + string? path, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + string trimmed = (path ?? "").Trim('/'); + if (catalog.Find(name) is not { } found || !GitReader.IsTreePath(trimmed)) + { + return null; + } + + string? named = string.IsNullOrEmpty(reference) + ? await git.DefaultBranchAsync(found.MirrorPath, cancellationToken) + : reference; + if (named is null || await git.ResolveAsync(found.MirrorPath, named, cancellationToken) is not { } commit) + { + return null; + } + + return (found.MirrorPath, named, commit, trimmed); + } + + private static async Task<IResult> TreeAsync( + string name, + string? @ref, + string? path, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at) + { + return Results.NotFound(); + } + + string? kind = await git.KindAsync(at.Mirror, at.Commit, at.Path, cancellationToken); + if (kind == "tree") + { + IReadOnlyList<GitTreeEntry> entries = await git.TreeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); + return Results.Ok(new GitTreeResponse(at.Reference, at.Commit, at.Path, "tree", entries, null, false, null, false)); + } + + if (kind != "blob") + { + return Results.NotFound(); + } + + long size = await git.SizeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); + (byte[] bytes, bool isTruncated) = await git.BlobAsync(at.Mirror, at.Commit, at.Path, GitReader.MaxTextBytes, cancellationToken); + bool isBinary = IsBinary(bytes); + return Results.Ok(new GitTreeResponse( + at.Reference, at.Commit, at.Path, "blob", null, size, isBinary, isBinary ? null : Encoding.UTF8.GetString(bytes), isTruncated)); + } + + /// <summary>Whether bytes are not text: a NUL in the first 8000, as Git decides.</summary> + internal static bool IsBinary(ReadOnlySpan<byte> bytes) => bytes[..Math.Min(bytes.Length, 8000)].Contains((byte)0); + + private static async Task<IResult> LogAsync( + string name, + string? @ref, + string? path, + int? page, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (page is < 0 or > 10_000 + || await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at) + { + return Results.NotFound(); + } + + (IReadOnlyList<GitLogEntry> commits, bool hasMore) = + await git.LogAsync(at.Mirror, at.Commit, at.Path, page ?? 0, cancellationToken); + return Results.Ok(new { reference = at.Reference, commit = at.Commit, path = at.Path, page = page ?? 0, commits, hasMore }); + } + + private static async Task<IResult> CommitAsync( + string name, + string commit, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (!GitReader.IsCommitId(commit) + || catalog.Find(name) is not { } found + || await git.ResolveAsync(found.MirrorPath, commit, cancellationToken) is not { } resolved) + { + return Results.NotFound(); + } + + return Results.Ok(await git.CommitAsync(found.MirrorPath, resolved, cancellationToken)); + } + + private static async Task<IResult> RawAsync( + string name, + string? @ref, + string? path, + HttpContext context, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (await LocateAsync(name, @ref, path, catalog, git, cancellationToken) is not { } at + || at.Path.Length == 0 + || await git.KindAsync(at.Mirror, at.Commit, at.Path, cancellationToken) != "blob") + { + return Results.NotFound(); + } + + long size = await git.SizeAsync(at.Mirror, at.Commit, at.Path, cancellationToken); + if (size > GitReader.MaxRawBytes) + { + return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + (byte[] bytes, _) = await git.BlobAsync(at.Mirror, at.Commit, at.Path, GitReader.MaxRawBytes, cancellationToken); + // Raw files are never rendered by the browser: text is plain text, anything else is a download, and the + // content security policy of the API allows nothing to run. + context.Response.Headers.ContentDisposition = IsBinary(bytes) + ? $"attachment; filename=\"{SafeFileName(at.Path)}\"" + : "inline"; + return Results.Bytes(bytes, IsBinary(bytes) ? "application/octet-stream" : "text/plain; charset=utf-8"); + } + + private static async Task ArchiveAsync( + string name, + string? @ref, + HttpContext context, + GitCatalog catalog, + GitReader git, + CancellationToken cancellationToken) + { + if (await LocateAsync(name, @ref, "", catalog, git, cancellationToken) is not { } at) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + + string label = SafeFileName(at.Reference.Replace('/', '-')); + string prefix = $"{name}-{label}"; + context.Response.ContentType = "application/gzip"; + context.Response.Headers.ContentDisposition = $"attachment; filename=\"{prefix}.tar.gz\""; + await git.ArchiveAsync(at.Mirror, at.Commit, prefix + "/", context.Response.Body, cancellationToken); + } + + /// <summary>The last segment of a path with only safe characters, for a Content-Disposition file name.</summary> + internal static string SafeFileName(string path) + { + string last = path[(path.LastIndexOf('/') + 1)..]; + string safe = new([.. last.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' or '+' ? c : '_')]); + return safe.Length == 0 ? "file" : safe; + } +} + +/// <summary>Keeps the Git endpoints on git.progmasoft.com and loopback, and everything else off that host.</summary> +/// <param name="next">The rest of the pipeline.</param> +/// <param name="options">The host of the mirrors.</param> +internal sealed class GitHostFilter(RequestDelegate next, IOptions<GitOptions> options) +{ + /// <summary>Answers 404 for a Git path on another host, or another path on the Git host.</summary> + /// <param name="context">The request.</param> + /// <returns>A task that completes when the request has been answered.</returns> + public Task InvokeAsync(HttpContext context) + { + PathString path = context.Request.Path; + string host = context.Request.Host.Host; + bool isGitPath = path.StartsWithSegments(GitEndpoints.Prefix, StringComparison.OrdinalIgnoreCase); + bool isHealth = path.StartsWithSegments("/health", StringComparison.OrdinalIgnoreCase); + bool isGitHost = string.Equals(host, options.Value.Host, StringComparison.OrdinalIgnoreCase); + bool isLoopback = host is "127.0.0.1" or "localhost" or "::1" or "[::1]"; + bool allowed = isGitHost ? isGitPath || isHealth : !isGitPath || isLoopback; + if (allowed) + { + return next(context); + } + + context.Response.StatusCode = StatusCodes.Status404NotFound; + return Task.CompletedTask; + } +} diff --git a/apps/api/Git/GitReader.cs b/apps/api/Git/GitReader.cs new file mode 100644 index 0000000..e36665f --- /dev/null +++ b/apps/api/Git/GitReader.cs @@ -0,0 +1,477 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.Extensions.Options; + +namespace Progmasoft.Progmaweb.Api.Git; + +/// <summary>A branch or a tag.</summary> +/// <param name="Name">Its short name.</param> +/// <param name="Commit">The commit it names.</param> +/// <param name="Date">When that commit was made, or the tag was created.</param> +/// <param name="Subject">The first line of its message.</param> +internal sealed record GitRef(string Name, string Commit, DateTimeOffset Date, string Subject); + +/// <summary>One commit of a log.</summary> +/// <param name="Commit">Its identifier.</param> +/// <param name="Author">Its author's name.</param> +/// <param name="Date">When it was authored.</param> +/// <param name="Subject">The first line of its message.</param> +internal sealed record GitLogEntry(string Commit, string Author, DateTimeOffset Date, string Subject); + +/// <summary>One entry of a tree.</summary> +/// <param name="Name">Its name in the tree.</param> +/// <param name="Kind"><c>tree</c>, <c>blob</c>, <c>link</c> or <c>submodule</c>.</param> +/// <param name="Size">The size of a blob in bytes; null otherwise.</param> +internal sealed record GitTreeEntry(string Name, string Kind, long? Size); + +/// <summary>A commit with its message and changes.</summary> +/// <param name="Commit">Its identifier.</param> +/// <param name="Parents">Its parents.</param> +/// <param name="Author">Its author's name.</param> +/// <param name="AuthorDate">When it was authored.</param> +/// <param name="Committer">Its committer's name.</param> +/// <param name="CommitDate">When it was committed.</param> +/// <param name="Message">Its whole message.</param> +/// <param name="Diff">The patch against its first parent, or the whole tree for a root commit.</param> +/// <param name="IsDiffTruncated">Whether the patch was cut at <see cref="GitReader.MaxDiffBytes"/>.</param> +internal sealed record GitCommitDetails( + string Commit, + IReadOnlyList<string> Parents, + string Author, + DateTimeOffset AuthorDate, + string Committer, + DateTimeOffset CommitDate, + string Message, + string Diff, + bool IsDiffTruncated); + +/// <summary>Reads a bare mirror with the Git program.</summary> +/// <remarks> +/// <para> +/// Every argument comes from a resolved commit identifier, a validated name or a validated path, and is passed as +/// one element of the argument list, never through a shell; options end before anything a request gave. Git runs +/// without the system and global configuration, without a terminal, and for at most <see cref="Timeout"/>. +/// </para> +/// <para> +/// The mirrors belong to the user that fetches them, so this reader trusts them through <c>safe.directory</c> for +/// its own runs only, as git-http-backend does in the Nginx configuration. +/// </para> +/// </remarks> +/// <param name="options">Where Git is.</param> +internal sealed partial class GitReader(IOptions<GitOptions> options) +{ + /// <summary>How long one run of Git may take.</summary> + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15); + + /// <summary>The largest file shown as text in a page.</summary> + public const int MaxTextBytes = 1024 * 1024; + + /// <summary>The largest patch shown in a page.</summary> + public const int MaxDiffBytes = 512 * 1024; + + /// <summary>The largest file served raw.</summary> + public const long MaxRawBytes = 32L * 1024 * 1024; + + /// <summary>Commits per page of a log.</summary> + public const int LogPageSize = 50; + + /// <summary>A full commit identifier, SHA-1 or SHA-256.</summary> + [GeneratedRegex("^(?:[0-9a-f]{40}|[0-9a-f]{64})$", RegexOptions.CultureInvariant)] + private static partial Regex CommitPattern(); + + /// <summary>The characters a branch or tag name of these repositories may have.</summary> + [GeneratedRegex("^[A-Za-z0-9._+/-]{1,200}$", RegexOptions.CultureInvariant)] + private static partial Regex RefPattern(); + + /// <summary>Whether a text is a full commit identifier.</summary> + /// <param name="text">The text.</param> + /// <returns><see langword="true"/> when it is one.</returns> + public static bool IsCommitId(string text) => CommitPattern().IsMatch(text); + + /// <summary>Whether a text may name a branch or a tag: Git's rules, as far as a request needs them.</summary> + /// <param name="name">The text.</param> + /// <returns><see langword="true"/> when it may.</returns> + public static bool IsRefName(string name) => + RefPattern().IsMatch(name) + && !name.StartsWith('-') + && !name.StartsWith('/') + && !name.EndsWith('/') + && !name.EndsWith(".lock", StringComparison.Ordinal) + && !name.Contains("..", StringComparison.Ordinal) + && !name.Contains("//", StringComparison.Ordinal) + && !name.Split('/').Any(part => part.StartsWith('.')); + + /// <summary>Whether a text is a path inside a tree: segments without <c>.</c>, <c>..</c> or control characters.</summary> + /// <param name="path">The path, without a leading or trailing slash; empty for the root.</param> + /// <returns><see langword="true"/> when it is one.</returns> + public static bool IsTreePath(string path) => + path.Length == 0 + || (path.Length <= 4096 + && path.Split('/').All(part => part.Length > 0 && part != "." && part != ".." && !part.Any(char.IsControl))); + + /// <summary>The default branch of a mirror.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>Its name, or <see langword="null"/> when HEAD names no branch.</returns> + public async Task<string?> DefaultBranchAsync(string mirror, CancellationToken cancellationToken) + { + GitResult result = await RunAsync(mirror, ["symbolic-ref", "--quiet", "--short", "HEAD"], cancellationToken); + return result.Ok ? result.Text.Trim() : null; + } + + /// <summary>Resolves a branch, a tag or a full commit identifier to a commit.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="reference">What a request named.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The commit, or <see langword="null"/> when the reference names none.</returns> + public async Task<string?> ResolveAsync(string mirror, string reference, CancellationToken cancellationToken) + { + string[] candidates = IsCommitId(reference) + ? [reference] + : IsRefName(reference) ? [$"refs/heads/{reference}", $"refs/tags/{reference}"] : []; + foreach (string candidate in candidates) + { + GitResult result = await RunAsync( + mirror, + ["rev-parse", "--verify", "--quiet", "--end-of-options", candidate + "^{commit}"], + cancellationToken); + if (result.Ok) + { + return result.Text.Trim(); + } + } + + return null; + } + + /// <summary>The branches and the tags of a mirror, the newest first.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The branches and the tags.</returns> + public async Task<(IReadOnlyList<GitRef> Branches, IReadOnlyList<GitRef> Tags)> RefsAsync( + string mirror, + CancellationToken cancellationToken) + { + GitResult result = await RunAsync( + mirror, + [ + "for-each-ref", "--sort=-creatordate", + "--format=%(refname)%00%(if)%(*objectname)%(then)%(*objectname)%(else)%(objectname)%(end)%00%(creatordate:iso-strict)%00%(contents:subject)%1e", + "refs/heads", "refs/tags" + ], + cancellationToken); + List<GitRef> branches = []; + List<GitRef> tags = []; + foreach (string record in Records(result.Text)) + { + string[] fields = record.Split('\0'); + if (fields.Length < 4) + { + continue; + } + + if (fields[0].StartsWith("refs/heads/", StringComparison.Ordinal)) + { + branches.Add(new GitRef(fields[0]["refs/heads/".Length..], fields[1], Date(fields[2]), fields[3])); + } + else if (fields[0].StartsWith("refs/tags/", StringComparison.Ordinal)) + { + tags.Add(new GitRef(fields[0]["refs/tags/".Length..], fields[1], Date(fields[2]), fields[3])); + } + } + + return (branches, tags); + } + + /// <summary>The kind of the object at a path of a commit.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="path">A valid tree path.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns><c>tree</c>, <c>blob</c>, or <see langword="null"/> when nothing is there.</returns> + public async Task<string?> KindAsync(string mirror, string commit, string path, CancellationToken cancellationToken) + { + GitResult result = await RunAsync(mirror, ["cat-file", "-t", "--end-of-options", $"{commit}:{path}"], cancellationToken); + return result.Ok ? result.Text.Trim() : null; + } + + /// <summary>The entries of a tree: directories first, then by name.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="path">A valid tree path that names a tree.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The entries.</returns> + public async Task<IReadOnlyList<GitTreeEntry>> TreeAsync( + string mirror, + string commit, + string path, + CancellationToken cancellationToken) + { + GitResult result = await RunAsync(mirror, ["ls-tree", "-l", "-z", "--end-of-options", $"{commit}:{path}"], cancellationToken); + List<GitTreeEntry> entries = []; + foreach (string line in result.Text.Split('\0', StringSplitOptions.RemoveEmptyEntries)) + { + // <mode> SP <type> SP <object> SP+ <size> TAB <name> + int tab = line.IndexOf('\t', StringComparison.Ordinal); + if (tab < 0) + { + continue; + } + + string[] meta = line[..tab].Split(' ', StringSplitOptions.RemoveEmptyEntries); + string name = line[(tab + 1)..]; + string kind = meta[0] switch + { + "040000" => "tree", + "120000" => "link", + "160000" => "submodule", + _ => "blob" + }; + long? size = kind is "blob" or "link" && long.TryParse(meta[^1], CultureInfo.InvariantCulture, out long bytes) + ? bytes + : null; + entries.Add(new GitTreeEntry(name, kind, size)); + } + + return [.. entries.OrderBy(entry => entry.Kind == "tree" ? 0 : 1).ThenBy(entry => entry.Name, StringComparer.Ordinal)]; + } + + /// <summary>The size of a blob.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="path">A valid tree path that names a blob.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The size in bytes.</returns> + public async Task<long> SizeAsync(string mirror, string commit, string path, CancellationToken cancellationToken) + { + GitResult result = await RunAsync(mirror, ["cat-file", "-s", "--end-of-options", $"{commit}:{path}"], cancellationToken); + return long.Parse(result.Text.Trim(), CultureInfo.InvariantCulture); + } + + /// <summary>The content of a blob, up to a limit.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="path">A valid tree path that names a blob.</param> + /// <param name="limit">The most bytes to read.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The bytes, and whether there were more.</returns> + public async Task<(byte[] Bytes, bool IsTruncated)> BlobAsync( + string mirror, + string commit, + string path, + long limit, + CancellationToken cancellationToken) + { + GitResult result = await RunAsync(mirror, ["cat-file", "blob", "--end-of-options", $"{commit}:{path}"], cancellationToken, limit); + return (result.Bytes, result.IsTruncated); + } + + /// <summary>A page of the log of a commit, of a path in it when one is given.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="path">A valid tree path, or empty for the whole tree.</param> + /// <param name="page">The page, from zero.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>The commits of the page, and whether another page follows.</returns> + public async Task<(IReadOnlyList<GitLogEntry> Commits, bool HasMore)> LogAsync( + string mirror, + string commit, + string path, + int page, + CancellationToken cancellationToken) + { + List<string> arguments = + [ + "log", "--format=%H%x00%an%x00%aI%x00%s%x1e", + $"--skip={page * LogPageSize}", $"--max-count={LogPageSize + 1}", "--end-of-options", commit + ]; + if (path.Length > 0) + { + arguments.AddRange(["--", path]); + } + + GitResult result = await RunAsync(mirror, arguments, cancellationToken); + List<GitLogEntry> commits = []; + foreach (string record in Records(result.Text)) + { + string[] fields = record.Split('\0'); + if (fields.Length >= 4) + { + commits.Add(new GitLogEntry(fields[0], fields[1], Date(fields[2]), fields[3])); + } + } + + bool hasMore = commits.Count > LogPageSize; + return (hasMore ? commits[..LogPageSize] : commits, hasMore); + } + + /// <summary>A commit, its message and its patch.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="cancellationToken">Cancels the runs.</param> + /// <returns>The commit.</returns> + public async Task<GitCommitDetails> CommitAsync(string mirror, string commit, CancellationToken cancellationToken) + { + GitResult header = await RunAsync( + mirror, + ["show", "-s", "--format=%H%x00%P%x00%an%x00%aI%x00%cn%x00%cI%x00%B", "--end-of-options", commit], + cancellationToken); + string[] fields = header.Text.Split('\0', 7); + GitResult diff = await RunAsync( + mirror, + ["diff-tree", "--patch", "--stat", "--no-color", "--no-ext-diff", "--find-renames", "--root", "--no-commit-id", "--end-of-options", commit], + cancellationToken, + MaxDiffBytes); + return new GitCommitDetails( + fields[0], + fields[1].Split(' ', StringSplitOptions.RemoveEmptyEntries), + fields[2], + Date(fields[3]), + fields[4], + Date(fields[5]), + fields[6].TrimEnd(), + Encoding.UTF8.GetString(diff.Bytes), + diff.IsTruncated); + } + + /// <summary>Writes a gzip-compressed tar archive of a commit.</summary> + /// <param name="mirror">The path of the mirror.</param> + /// <param name="commit">A resolved commit.</param> + /// <param name="prefix">The directory every file is put in, such as <c>tazel-main/</c>.</param> + /// <param name="output">Where the archive goes.</param> + /// <param name="cancellationToken">Cancels the run.</param> + /// <returns>A task that completes when the archive is written.</returns> + public async Task ArchiveAsync(string mirror, string commit, string prefix, Stream output, CancellationToken cancellationToken) + { + using Process process = Start(mirror, ["archive", "--format=tar.gz", $"--prefix={prefix}", "--end-of-options", commit]); + using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromMinutes(2)); + try + { + Task<string> errors = process.StandardError.ReadToEndAsync(timeout.Token); + await process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); + await process.WaitForExitAsync(timeout.Token); + if (process.ExitCode != 0) + { + throw new IOException($"git archive exited with {process.ExitCode}: {(await errors).Trim()}"); + } + } + finally + { + Stop(process); + } + } + + /// <summary>The result of one run.</summary> + /// <param name="Ok">Whether Git exited with 0.</param> + /// <param name="Bytes">What it wrote, up to the limit.</param> + /// <param name="IsTruncated">Whether it wrote more than the limit.</param> + private sealed record GitResult(bool Ok, byte[] Bytes, bool IsTruncated) + { + public string Text => Encoding.UTF8.GetString(Bytes); + } + + private async Task<GitResult> RunAsync( + string mirror, + IReadOnlyList<string> arguments, + CancellationToken cancellationToken, + long limit = 16 * 1024 * 1024) + { + using Process process = Start(mirror, arguments); + using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(Timeout); + try + { + Task drain = process.StandardError.ReadToEndAsync(timeout.Token); + using MemoryStream bytes = new(); + byte[] buffer = new byte[81920]; + bool isTruncated = false; + Stream stdout = process.StandardOutput.BaseStream; + int read; + while ((read = await stdout.ReadAsync(buffer, timeout.Token)) > 0) + { + long room = limit - bytes.Length; + if (read > room) + { + bytes.Write(buffer, 0, (int)Math.Max(room, 0)); + isTruncated = true; + break; + } + + bytes.Write(buffer, 0, read); + } + + if (isTruncated) + { + Stop(process); + return new GitResult(true, bytes.ToArray(), true); + } + + await process.WaitForExitAsync(timeout.Token); + await drain; + return new GitResult(process.ExitCode == 0, bytes.ToArray(), false); + } + finally + { + Stop(process); + } + } + + private Process Start(string mirror, IReadOnlyList<string> arguments) + { + ProcessStartInfo start = new(options.Value.GitPath) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = false, + UseShellExecute = false, + WorkingDirectory = mirror + }; + foreach (string argument in (string[])["-c", $"safe.directory={mirror}", "-c", "core.quotePath=false", "--git-dir", mirror, "--no-pager"]) + { + start.ArgumentList.Add(argument); + } + + foreach (string argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.Environment.Clear(); + start.Environment["PATH"] = "/usr/bin:/bin"; + start.Environment["LANG"] = "C.UTF-8"; + start.Environment["GIT_CONFIG_NOSYSTEM"] = "1"; + start.Environment["GIT_CONFIG_GLOBAL"] = "/dev/null"; + start.Environment["GIT_TERMINAL_PROMPT"] = "0"; + start.Environment["GIT_NO_REPLACE_OBJECTS"] = "1"; + return Process.Start(start) ?? throw new InvalidOperationException("Git did not start."); + } + + private static void Stop(Process process) + { + try + { + if (!process.HasExited) + { + process.Kill(); + } + } + catch (InvalidOperationException) + { + // It exited between the check and the kill. + } + } + + private static IEnumerable<string> Records(string text) => + text.Split('\u001e').Select(record => record.TrimStart('\n')).Where(record => record.Length > 0); + + private static DateTimeOffset Date(string text) => + DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset date) + ? date + : DateTimeOffset.UnixEpoch; +} diff --git a/apps/api/Program.cs b/apps/api/Program.cs index 4653d77..927e870 100644 --- a/apps/api/Program.cs +++ b/apps/api/Program.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.HttpOverrides; using Progmasoft.Progmaweb.Api.Accounts; +using Progmasoft.Progmaweb.Api.Git; using Progmasoft.OAuth; using Progmasoft.Progmaweb.Api.Security; @@ -86,6 +87,19 @@ builder.Services.AddRateLimiter(options => Window = TimeSpan.FromMinutes(1) }); }); + // git.progmasoft.com: every page is a few runs of Git; the limit keeps a crawler from starving the host. + options.AddPolicy("git", context => + { + string partition = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; + return RateLimitPartition.GetSlidingWindowLimiter(partition, _ => new SlidingWindowRateLimiterOptions + { + AutoReplenishment = true, + PermitLimit = 600, + QueueLimit = 0, + SegmentsPerWindow = 6, + Window = TimeSpan.FromMinutes(1) + }); + }); options.AddPolicy("account-auth", context => { string partition = context.Connection.RemoteIpAddress?.ToString() ?? "unknown"; @@ -101,6 +115,9 @@ builder.Services.AddRateLimiter(options => }); builder.Services.Configure<ForwardedHeadersOptions>(ForwardedHeadersPolicy.Configure); +builder.Services.Configure<GitOptions>(builder.Configuration.GetSection(GitOptions.Section)); +builder.Services.AddSingleton<GitCatalog>(); +builder.Services.AddSingleton<GitReader>(); builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize = 16 * 1024); @@ -128,6 +145,8 @@ app.UseHttpsRedirection(); app.UseMiddleware<SecurityHeadersMiddleware>(); // Before authentication, where OpenIddict answers its own endpoints: OAuth only on its host, and nothing else there. app.UseMiddleware<OAuthHostFilter>(); +// The mirrors of git.progmasoft.com only there and on loopback, where Next.js renders their pages. +app.UseMiddleware<GitHostFilter>(); // Single-page applications call the token endpoints from the browser; see OAuth/Api/OAuthCors.cs. app.UseMiddleware<Progmasoft.OAuth.Api.OAuthCors>(); app.UseAuthentication(); @@ -144,6 +163,7 @@ app.MapGet("/api/v1/status", () => Results.Ok(new })); app.MapAccountEndpoints(); app.MapProgmasoftOAuth(); +app.MapGitEndpoints(); app.Run(); diff --git a/apps/api/appsettings.json b/apps/api/appsettings.json index 4ddc9e9..3f2983c 100644 --- a/apps/api/appsettings.json +++ b/apps/api/appsettings.json @@ -5,7 +5,7 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;credentials.progmasoft.com;authorize.progmasoft.com;console.progmasoft.com", + "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;credentials.progmasoft.com;authorize.progmasoft.com;console.progmasoft.com;git.progmasoft.com", "AccountSessions": { "LifetimeHours": 720, "CookieName": "__Secure-ProgmasoftSession", diff --git a/apps/web/app/git/GitFrame.tsx b/apps/web/app/git/GitFrame.tsx new file mode 100644 index 0000000..cb36120 --- /dev/null +++ b/apps/web/app/git/GitFrame.tsx @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import Link from "next/link"; +import type { ReactNode } from "react"; +import { Footer } from "@/components/Footer"; +import { SiteHeader } from "@/components/SiteHeader"; +import { getGitMessages } from "@/lib/git-messages"; +import type { GitRepository } from "@/lib/git.server"; +import type { Locale } from "@/lib/localization"; + +/** The views of a repository, for its navigation. */ +export type GitView = "summary" | "tree" | "log" | "refs" | "commit"; + +/** An address of git.progmasoft.com with its query, empty values left out. */ +export function gitHref( + path: string, + query: Record<string, string | number | undefined> = {}, +): string { + const parameters = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) { + if (value !== undefined && value !== "" && value !== 0) { + parameters.set(key, String(value)); + } + } + const search = parameters.toString(); + return search ? `${path}?${search}` : path; +} + +/** A date as the language writes it. */ +export function gitDate(locale: Locale, date: string | null): string { + if (!date) { + return ""; + } + return new Intl.DateTimeFormat(locale, { + dateStyle: "medium", + timeZone: "UTC", + }).format(new Date(date)); +} + +/** A size in bytes, KiB or MiB. */ +export function gitSize(bytes: number | null): string { + if (bytes === null) { + return ""; + } + if (bytes < 1024) { + return `${bytes} B`; + } + return bytes < 1024 * 1024 + ? `${(bytes / 1024).toFixed(1)} KiB` + : `${(bytes / 1024 / 1024).toFixed(1)} MiB`; +} + +/** The frame of every page of git.progmasoft.com. */ +export function GitFrame({ + locale, + repository, + view, + reference, + children, +}: Readonly<{ + locale: Locale; + /** The repository of the page, or nothing for the listing. */ + repository?: GitRepository; + view?: GitView; + /** The branch or tag the page shows, when it is not the default. */ + reference?: string; + children: ReactNode; +}>) { + const text = getGitMessages(locale); + const base = repository ? `/${repository.name}` : ""; + const ref = + reference && reference !== repository?.defaultBranch + ? reference + : undefined; + return ( + <div className="pm-page"> + <SiteHeader locale={locale} /> + <main> + <section className="pm-hero"> + <div className="pm-shell pm-product-hero"> + <p className="eyebrow"> + <Link href="/">{text.title}</Link> + </p> + <h1>{repository ? repository.name : text.title}</h1> + <p className="pm-lede"> + {repository ? repository.description : text.description} + </p> + {repository ? ( + <> + <nav className="pm-git-nav" aria-label={text.repository}> + <a + href={gitHref(base, { ref })} + aria-current={view === "summary" ? "page" : undefined} + > + {text.files} + </a> + <a + href={gitHref(`${base}/log`, { ref })} + aria-current={view === "log" ? "page" : undefined} + > + {text.log} + </a> + <a + href={`${base}/refs`} + aria-current={view === "refs" ? "page" : undefined} + > + {text.refs} + </a> + <a href={repository.homepage}>{text.developedOn}</a> + </nav> + <p className="pm-git-clone"> + <span>{text.clone}</span> + <code>git clone {repository.cloneUrl}</code> + </p> + </> + ) : null} + </div> + </section> + <section className="pm-section"> + <div className="pm-shell pm-git">{children}</div> + </section> + </main> + <Footer locale={locale} /> + </div> + ); +} diff --git a/apps/web/app/git/GitViews.tsx b/apps/web/app/git/GitViews.tsx new file mode 100644 index 0000000..545a4b2 --- /dev/null +++ b/apps/web/app/git/GitViews.tsx @@ -0,0 +1,168 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { getGitMessages } from "@/lib/git-messages"; +import type { GitLogEntry, GitRepository, GitTree } from "@/lib/git.server"; +import type { Locale } from "@/lib/localization"; +import { gitDate, gitHref, gitSize } from "./GitFrame"; + +/** The reference to keep in links: none for the default branch. */ +export function keptRef( + repository: GitRepository, + reference: string, +): string | undefined { + return reference === repository.defaultBranch ? undefined : reference; +} + +/** The path of a tree as links, from the root. */ +export function GitBreadcrumbs({ + locale, + repository, + reference, + path, +}: Readonly<{ + locale: Locale; + repository: GitRepository; + reference: string; + path: string; +}>) { + const text = getGitMessages(locale); + const ref = keptRef(repository, reference); + const parts = path ? path.split("/") : []; + return ( + <p className="pm-git-path"> + <span className="pm-git-ref">{reference}</span> + <a href={gitHref(`/${repository.name}`, { ref })}>{text.root}</a> + {parts.map((part, index) => { + const at = parts.slice(0, index + 1).join("/"); + return ( + <span key={at}> + {" / "} + {index === parts.length - 1 ? ( + <span>{part}</span> + ) : ( + <a href={gitHref(`/${repository.name}/tree`, { ref, path: at })}> + {part} + </a> + )} + </span> + ); + })} + </p> + ); +} + +/** The entries of a tree, or the text of a file. */ +export function GitTreeView({ + locale, + repository, + tree, +}: Readonly<{ locale: Locale; repository: GitRepository; tree: GitTree }>) { + const text = getGitMessages(locale); + const ref = keptRef(repository, tree.reference); + const raw = gitHref(`/${repository.name}/raw`, { + ref: tree.commit, + path: tree.path, + }); + if (tree.kind === "blob") { + return ( + <section className="pm-git-block"> + <p className="pm-git-meta"> + {gitSize(tree.size)} · <a href={raw}>{text.raw}</a> ·{" "} + <a + href={gitHref(`/${repository.name}/log`, { ref, path: tree.path })} + > + {text.log} + </a> + </p> + {tree.isBinary ? ( + <p>{text.binary}</p> + ) : ( + <pre className="pm-git-file"> + <code>{tree.text}</code> + </pre> + )} + {tree.isTruncated ? ( + <p className="pm-git-meta">{text.truncated}</p> + ) : null} + </section> + ); + } + const kindWords = { + tree: text.directory, + link: text.link, + submodule: text.submodule, + blob: "", + }; + return ( + <section className="pm-git-block"> + <h2>{text.files}</h2> + <div className="pm-git-scroll"> + <table className="pm-git-table"> + <thead> + <tr> + <th scope="col">{text.name}</th> + <th scope="col">{text.size}</th> + </tr> + </thead> + <tbody> + {(tree.entries ?? []).map((entry) => { + const at = tree.path ? `${tree.path}/${entry.name}` : entry.name; + return ( + <tr key={entry.name}> + <td> + {entry.kind === "submodule" ? ( + <span>{entry.name}</span> + ) : ( + <a + href={gitHref(`/${repository.name}/tree`, { + ref, + path: at, + })} + > + {entry.name} + {entry.kind === "tree" ? "/" : ""} + </a> + )} + </td> + <td> + {entry.kind === "blob" + ? gitSize(entry.size) + : kindWords[entry.kind]} + </td> + </tr> + ); + })} + </tbody> + </table> + </div> + </section> + ); +} + +/** A list of commits. */ +export function GitCommitList({ + locale, + repository, + commits, +}: Readonly<{ + locale: Locale; + repository: GitRepository; + commits: GitLogEntry[]; +}>) { + return ( + <ol className="pm-git-commits"> + {commits.map((entry) => ( + <li key={entry.commit}> + <a href={`/${repository.name}/commit/${entry.commit}`}> + {entry.subject || entry.commit.slice(0, 12)} + </a> + <p className="pm-git-meta"> + <code>{entry.commit.slice(0, 12)}</code> · {entry.author} ·{" "} + <time dateTime={entry.date}>{gitDate(locale, entry.date)}</time> + </p> + </li> + ))} + </ol> + ); +} diff --git a/apps/web/app/git/[repo]/commit/[sha]/page.tsx b/apps/web/app/git/[repo]/commit/[sha]/page.tsx new file mode 100644 index 0000000..e7bec78 --- /dev/null +++ b/apps/web/app/git/[repo]/commit/[sha]/page.tsx @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getGitMessages } from "@/lib/git-messages"; +import { gitCommit, gitRepository } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import { GitFrame, gitDate, gitHref } from "../../../GitFrame"; + +type Props = { params: Promise<{ repo: string; sha: string }> }; + +export async function generateMetadata({ params }: Props): Promise<Metadata> { + const { repo, sha } = await params; + return { + title: `${sha.slice(0, 12)} · ${repo} · Progmasoft Git`, + robots: { index: false, follow: true }, + }; +} + +/** The class of a line of a patch, for its color. */ +function lineClass(line: string): string | undefined { + if (line.startsWith("+++") || line.startsWith("---")) { + return "pm-git-diff-file"; + } + if (line.startsWith("@@")) { + return "pm-git-diff-hunk"; + } + if (line.startsWith("+")) { + return "pm-git-diff-add"; + } + return line.startsWith("-") ? "pm-git-diff-remove" : undefined; +} + +/** git.progmasoft.com/<repo>/commit/<sha>: a commit and its changes. */ +export default async function CommitPage({ params }: Props) { + const { repo, sha } = await params; + const locale = await getLocale(); + const text = getGitMessages(locale); + const repository = await gitRepository(repo); + const commit = repository ? await gitCommit(repo, sha) : null; + if (!repository || !commit) { + notFound(); + } + const [subject, ...body] = commit.message.split("\n"); + const lines = commit.diff.split("\n"); + return ( + <GitFrame locale={locale} repository={repository} view="commit"> + <section className="pm-git-block"> + <h2>{subject}</h2> + {body.join("\n").trim() ? ( + <pre className="pm-git-message">{body.join("\n").trim()}</pre> + ) : null} + <dl className="pm-git-facts"> + <dt>{text.commit}</dt> + <dd> + <code>{commit.commit}</code> + </dd> + <dt>{text.author}</dt> + <dd> + {commit.author} ·{" "} + <time dateTime={commit.authorDate}> + {gitDate(locale, commit.authorDate)} + </time> + </dd> + {commit.committer !== commit.author ? ( + <> + <dt>{text.committer}</dt> + <dd>{commit.committer}</dd> + </> + ) : null} + {commit.parents.length > 0 ? ( + <> + <dt>{text.parents}</dt> + <dd> + {commit.parents.map((parent, index) => ( + <span key={parent}> + {index > 0 ? ", " : null} + <a href={`/${repository.name}/commit/${parent}`}> + <code>{parent.slice(0, 12)}</code> + </a> + </span> + ))} + </dd> + </> + ) : null} + </dl> + <p> + <a href={gitHref(`/${repository.name}`, { ref: commit.commit })}> + {text.files} + </a>{" "} + ·{" "} + <a + href={gitHref(`/${repository.name}/archive`, { + ref: commit.commit, + })} + > + {text.archive} + </a> + </p> + </section> + <section className="pm-git-block"> + <h2>{text.changes}</h2> + <pre className="pm-git-diff"> + {lines.map((line, index) => ( + <span key={index} className={lineClass(line)}> + {line} + {"\n"} + </span> + ))} + </pre> + {commit.isDiffTruncated ? ( + <p className="pm-git-meta">{text.diffTruncated}</p> + ) : null} + </section> + </GitFrame> + ); +} diff --git a/apps/web/app/git/[repo]/log/page.tsx b/apps/web/app/git/[repo]/log/page.tsx new file mode 100644 index 0000000..646b577 --- /dev/null +++ b/apps/web/app/git/[repo]/log/page.tsx @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getGitMessages } from "@/lib/git-messages"; +import { gitLog, gitRepository } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import { GitFrame, gitHref } from "../../GitFrame"; +import { GitBreadcrumbs, GitCommitList, keptRef } from "../../GitViews"; +import { one, pageOf, type RepositoryProps } from "../../params"; + +export async function generateMetadata({ + params, +}: RepositoryProps): Promise<Metadata> { + const { repo } = await params; + const text = getGitMessages(await getLocale()); + return { + title: `${text.log} · ${repo} · Progmasoft Git`, + robots: { index: false, follow: true }, + }; +} + +/** git.progmasoft.com/<repo>/log?ref=&path=&page=: the commits, newest first. */ +export default async function LogPage({ + params, + searchParams, +}: RepositoryProps) { + const { repo } = await params; + const query = await searchParams; + const locale = await getLocale(); + const text = getGitMessages(locale); + const page = pageOf(one(query, "page")); + const repository = await gitRepository(repo); + const log = repository + ? await gitLog(repo, one(query, "ref"), one(query, "path"), page) + : null; + if (!repository || !log) { + notFound(); + } + const ref = keptRef(repository, log.reference); + const at = (to: number) => + gitHref(`/${repository.name}/log`, { ref, path: log.path, page: to }); + return ( + <GitFrame + locale={locale} + repository={repository} + view="log" + reference={log.reference} + > + <GitBreadcrumbs + locale={locale} + repository={repository} + reference={log.reference} + path={log.path} + /> + <GitCommitList + locale={locale} + repository={repository} + commits={log.commits} + /> + <nav className="pm-git-pages" aria-label={text.log}> + {page > 0 ? <a href={at(page - 1)}>{text.newer}</a> : null} + {log.hasMore ? <a href={at(page + 1)}>{text.older}</a> : null} + </nav> + </GitFrame> + ); +} diff --git a/apps/web/app/git/[repo]/page.tsx b/apps/web/app/git/[repo]/page.tsx new file mode 100644 index 0000000..e727c33 --- /dev/null +++ b/apps/web/app/git/[repo]/page.tsx @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getGitMessages } from "@/lib/git-messages"; +import { gitLog, gitRepository, gitTree } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import { GitFrame, gitHref } from "../GitFrame"; +import { + GitBreadcrumbs, + GitCommitList, + GitTreeView, + keptRef, +} from "../GitViews"; +import { one, type RepositoryProps } from "../params"; + +export async function generateMetadata({ + params, +}: RepositoryProps): Promise<Metadata> { + const { repo } = await params; + const repository = await gitRepository(repo); + return repository + ? { + title: `${repository.name} · Progmasoft Git`, + description: repository.description, + alternates: { + canonical: `https://git.progmasoft.com/${repository.name}`, + }, + } + : {}; +} + +/** git.progmasoft.com/<repo>: the files of a branch and its last commits. */ +export default async function RepositoryPage({ + params, + searchParams, +}: RepositoryProps) { + const { repo } = await params; + const ref = one(await searchParams, "ref"); + const locale = await getLocale(); + const text = getGitMessages(locale); + const repository = await gitRepository(repo); + const tree = repository ? await gitTree(repo, ref) : null; + if (!repository || !tree) { + notFound(); + } + const log = await gitLog(repo, tree.commit); + return ( + <GitFrame + locale={locale} + repository={repository} + view="summary" + reference={tree.reference} + > + <GitBreadcrumbs + locale={locale} + repository={repository} + reference={tree.reference} + path="" + /> + <GitTreeView locale={locale} repository={repository} tree={tree} /> + <section className="pm-git-block"> + <h2>{text.recentCommits}</h2> + <GitCommitList + locale={locale} + repository={repository} + commits={(log?.commits ?? []).slice(0, 10)} + /> + <p> + <a + href={gitHref(`/${repository.name}/log`, { + ref: keptRef(repository, tree.reference), + })} + > + {text.log} + </a>{" "} + ·{" "} + <a + href={gitHref(`/${repository.name}/archive`, { + ref: tree.reference, + })} + > + {text.archive} + </a> + </p> + </section> + </GitFrame> + ); +} diff --git a/apps/web/app/git/[repo]/refs/page.tsx b/apps/web/app/git/[repo]/refs/page.tsx new file mode 100644 index 0000000..e3023b7 --- /dev/null +++ b/apps/web/app/git/[repo]/refs/page.tsx @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getGitMessages } from "@/lib/git-messages"; +import { type GitRef, gitRefs, gitRepository } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import type { Locale } from "@/lib/localization"; +import { GitFrame, gitDate, gitHref } from "../../GitFrame"; +import type { RepositoryProps } from "../../params"; + +export async function generateMetadata({ + params, +}: RepositoryProps): Promise<Metadata> { + const { repo } = await params; + const text = getGitMessages(await getLocale()); + return { + title: `${text.refs} · ${repo} · Progmasoft Git`, + robots: { index: false, follow: true }, + }; +} + +function RefTable({ + locale, + name, + heading, + refs, +}: Readonly<{ + locale: Locale; + name: string; + heading: string; + refs: GitRef[]; +}>) { + const text = getGitMessages(locale); + return ( + <section className="pm-git-block"> + <h2>{heading}</h2> + <div className="pm-git-scroll"> + <table className="pm-git-table"> + <thead> + <tr> + <th scope="col">{text.name}</th> + <th scope="col">{text.commit}</th> + <th scope="col">{text.date}</th> + </tr> + </thead> + <tbody> + {refs.map((ref) => ( + <tr key={ref.name}> + <td> + <a href={gitHref(`/${name}`, { ref: ref.name })}> + {ref.name} + </a> + </td> + <td> + <a href={`/${name}/commit/${ref.commit}`}>{ref.subject}</a> + </td> + <td> + <time dateTime={ref.date}>{gitDate(locale, ref.date)}</time> + </td> + </tr> + ))} + </tbody> + </table> + </div> + </section> + ); +} + +/** git.progmasoft.com/<repo>/refs: the branches and the tags. */ +export default async function RefsPage({ params }: RepositoryProps) { + const { repo } = await params; + const locale = await getLocale(); + const text = getGitMessages(locale); + const repository = await gitRepository(repo); + const refs = repository ? await gitRefs(repo) : null; + if (!repository || !refs) { + notFound(); + } + return ( + <GitFrame locale={locale} repository={repository} view="refs"> + <RefTable + locale={locale} + name={repository.name} + heading={text.branches} + refs={refs.branches} + /> + {refs.tags.length > 0 ? ( + <RefTable + locale={locale} + name={repository.name} + heading={text.tags} + refs={refs.tags} + /> + ) : null} + </GitFrame> + ); +} diff --git a/apps/web/app/git/[repo]/tree/page.tsx b/apps/web/app/git/[repo]/tree/page.tsx new file mode 100644 index 0000000..266d498 --- /dev/null +++ b/apps/web/app/git/[repo]/tree/page.tsx @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { gitRepository, gitTree } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import { GitFrame } from "../../GitFrame"; +import { GitBreadcrumbs, GitTreeView } from "../../GitViews"; +import { one, type RepositoryProps } from "../../params"; + +export async function generateMetadata({ + params, + searchParams, +}: RepositoryProps): Promise<Metadata> { + const { repo } = await params; + const path = one(await searchParams, "path") ?? ""; + return { + title: `${path || repo} · ${repo} · Progmasoft Git`, + robots: { index: false, follow: true }, + }; +} + +/** git.progmasoft.com/<repo>/tree?path=&ref=: a directory or a file. */ +export default async function TreePage({ + params, + searchParams, +}: RepositoryProps) { + const { repo } = await params; + const query = await searchParams; + const locale = await getLocale(); + const repository = await gitRepository(repo); + const tree = repository + ? await gitTree(repo, one(query, "ref"), one(query, "path")) + : null; + if (!repository || !tree) { + notFound(); + } + return ( + <GitFrame + locale={locale} + repository={repository} + view="tree" + reference={tree.reference} + > + <GitBreadcrumbs + locale={locale} + repository={repository} + reference={tree.reference} + path={tree.path} + /> + <GitTreeView locale={locale} repository={repository} tree={tree} /> + </GitFrame> + ); +} diff --git a/apps/web/app/git/git.css b/apps/web/app/git/git.css new file mode 100644 index 0000000..77e8816 --- /dev/null +++ b/apps/web/app/git/git.css @@ -0,0 +1,210 @@ +/* SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> */ +/* SPDX-License-Identifier: AGPL-3.0-or-later */ + +/* git.progmasoft.com: the mirrors, in the tokens of the rest of the site. */ + +.pm-git { + --mono: ui-monospace, "Cascadia Code", "SF Mono", Menlo, Consolas, monospace; + min-width: 0; +} + +.pm-git-block + .pm-git-block { + margin-top: 40px; +} + +.pm-git-block h2 { + margin: 0 0 16px; + font-size: 1.25rem; + overflow-wrap: anywhere; +} + +.pm-git-nav { + display: flex; + flex-wrap: wrap; + gap: 8px 20px; + margin-top: 20px; +} + +.pm-git-nav a { + display: inline-flex; + align-items: center; + min-height: 32px; +} + +.pm-git-nav a[aria-current="page"] { + font-weight: 700; + text-decoration: underline; +} + +.pm-git-clone { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + margin-top: 16px; +} + +.pm-git-clone code, +.pm-git-meta code, +.pm-git-facts code { + font-family: var(--mono); + font-size: 0.9em; + overflow-wrap: anywhere; +} + +.pm-git-clone code { + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 6px 10px; + background: var(--surface-muted); + user-select: all; +} + +.pm-git-repositories, +.pm-git-commits { + margin: 0; + padding: 0; + list-style: none; +} + +.pm-git-repositories li, +.pm-git-commits li { + border-top: 1px solid var(--line); + padding: 14px 0; +} + +.pm-git-repositories a, +.pm-git-commits a { + display: inline-block; + min-height: 24px; + font-weight: 600; + overflow-wrap: anywhere; +} + +.pm-git-repositories p, +.pm-git-commits p { + margin: 4px 0 0; +} + +.pm-git-meta { + color: var(--ink-650); + font-size: 0.9rem; +} + +.pm-git-path { + margin: 0 0 20px; + overflow-wrap: anywhere; +} + +.pm-git-ref { + display: inline-block; + margin-right: 12px; + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + padding: 2px 8px; + font-family: var(--mono); + font-size: 0.85rem; +} + +.pm-git-scroll { + overflow-x: auto; +} + +.pm-git-table { + width: 100%; + border-collapse: collapse; +} + +.pm-git-table th, +.pm-git-table td { + border-bottom: 1px solid var(--line); + padding: 8px 12px 8px 0; + text-align: left; + vertical-align: top; +} + +.pm-git-table td a { + display: inline-block; + min-height: 24px; + overflow-wrap: anywhere; +} + +.pm-git-table td:last-child { + color: var(--ink-650); + white-space: nowrap; +} + +.pm-git-file, +.pm-git-diff, +.pm-git-message { + overflow-x: auto; + margin: 0; + border: 1px solid var(--line); + border-radius: var(--radius-md); + padding: 16px; + background: var(--surface-muted); + font-family: var(--mono); + font-size: 13px; + line-height: 1.55; + tab-size: 4; +} + +.pm-git-message { + margin-bottom: 20px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.pm-git-diff span { + display: block; + min-width: max-content; +} + +.pm-git-diff-add { + background: rgb(22 130 93 / 14%); +} + +.pm-git-diff-remove { + background: rgb(180 35 24 / 12%); +} + +.pm-git-diff-hunk { + color: var(--blue-600); +} + +.pm-git-diff-file { + font-weight: 700; +} + +.pm-git-facts { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 6px 16px; + margin: 0 0 16px; +} + +.pm-git-facts dt { + color: var(--ink-650); +} + +.pm-git-facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +.pm-git-facts a { + display: inline-block; + min-height: 24px; +} + +.pm-git-pages { + display: flex; + gap: 24px; + margin-top: 24px; +} + +.pm-git-pages a { + display: inline-flex; + align-items: center; + min-height: 32px; +} diff --git a/apps/web/app/git/layout.tsx b/apps/web/app/git/layout.tsx new file mode 100644 index 0000000..631a32c --- /dev/null +++ b/apps/web/app/git/layout.tsx @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { ReactNode } from "react"; +import "../site.css"; +import "./git.css"; + +export default function GitLayout({ + children, +}: Readonly<{ children: ReactNode }>) { + return children; +} diff --git a/apps/web/app/git/page.tsx b/apps/web/app/git/page.tsx new file mode 100644 index 0000000..aacf45a --- /dev/null +++ b/apps/web/app/git/page.tsx @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Metadata } from "next"; +import { getGitMessages } from "@/lib/git-messages"; +import { gitSections } from "@/lib/git.server"; +import { getLocale } from "@/lib/locale.server"; +import { GitFrame, gitDate } from "./GitFrame"; + +export async function generateMetadata(): Promise<Metadata> { + const text = getGitMessages(await getLocale()); + return { + title: text.metadataTitle, + description: text.description, + alternates: { canonical: "https://git.progmasoft.com/" }, + }; +} + +/** git.progmasoft.com: the mirrored repositories, by section. */ +export default async function GitIndexPage() { + const locale = await getLocale(); + const text = getGitMessages(locale); + const sections = (await gitSections()) ?? []; + return ( + <GitFrame locale={locale}> + {sections.length === 0 ? <p>{text.noRepositories}</p> : null} + {sections.map((section) => ( + <section key={section.name} className="pm-git-block"> + <h2>{section.name}</h2> + <ul className="pm-git-repositories"> + {section.repositories.map((repository) => ( + <li key={repository.name}> + <a href={`/${repository.name}`}>{repository.name}</a> + <p>{repository.description}</p> + {repository.updatedAt ? ( + <p className="pm-git-meta"> + {text.updated}{" "} + <time dateTime={repository.updatedAt}> + {gitDate(locale, repository.updatedAt)} + </time> + </p> + ) : null} + </li> + ))} + </ul> + </section> + ))} + </GitFrame> + ); +} diff --git a/apps/web/app/git/params.ts b/apps/web/app/git/params.ts new file mode 100644 index 0000000..f130fe2 --- /dev/null +++ b/apps/web/app/git/params.ts @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +/** The parameters of a repository page. */ +export type RepositoryProps = { + params: Promise<{ repo: string }>; + searchParams: Promise<Record<string, string | string[] | undefined>>; +}; + +/** One query parameter as text; the first when it is given more than once. */ +export function one( + query: Record<string, string | string[] | undefined>, + key: string, +): string | undefined { + const value = query[key]; + return Array.isArray(value) ? value[0] : value; +} + +/** A page number of a log: a whole number from 0, or 0. */ +export function pageOf(text: string | undefined): number { + const page = Number(text ?? "0"); + return Number.isInteger(page) && page >= 0 && page <= 10000 ? page : 0; +} diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index 7c40f9f..085340b 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -22,7 +22,8 @@ export default async function robots(): Promise<MetadataRoute.Robots> { const sitemap = canonicalHost === "product.progmasoft.com" || canonicalHost === "license.progmasoft.com" || - canonicalHost === "agencelandmcp.progmasoft.com" + canonicalHost === "agencelandmcp.progmasoft.com" || + canonicalHost === "git.progmasoft.com" ? `https://${canonicalHost}/sitemap.xml` : "https://progmasoft.com/sitemap.xml"; return { diff --git a/apps/web/app/sitemap.ts b/apps/web/app/sitemap.ts index 8e49b02..da5cc25 100644 --- a/apps/web/app/sitemap.ts +++ b/apps/web/app/sitemap.ts @@ -15,6 +15,9 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> { ) .split(":", 1)[0] ?.toLowerCase(); + if (host === "git.progmasoft.com") { + return [{ url: "https://git.progmasoft.com/" }]; + } if (host === "agencelandmcp.progmasoft.com") { return [{ url: "https://agencelandmcp.progmasoft.com/" }]; } diff --git a/apps/web/e2e/fake-git-api.mjs b/apps/web/e2e/fake-git-api.mjs new file mode 100644 index 0000000..81a88a9 --- /dev/null +++ b/apps/web/e2e/fake-git-api.mjs @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +// The Git endpoints of the account API, answered from fixed data, so that the +// layout tests render the pages of git.progmasoft.com without mirrors. The +// data is long where pages could overflow: names, paths, subjects and lines. + +import { createServer } from "node:http"; + +const commit = "0123456789abcdef0123456789abcdef01234567"; +const parent = "89abcdef0123456789abcdef0123456789abcdef"; +const date = "2026-11-21T12:00:00+00:00"; +const repository = { + name: "example-with-a-rather-long-repository-name", + description: + "A repository with a long description, so that the listing and the header wrap the way a real one would.", + homepage: "https://github.com/Progmasoft/example", + cloneUrl: + "https://git.progmasoft.com/example-with-a-rather-long-repository-name", + defaultBranch: "main", + updatedAt: date, +}; +const long = "a-path-segment-that-is-long-enough-to-overflow-a-phone"; +const entries = [ + { name: "src", kind: "tree", size: null }, + { name: `${long}-directory`, kind: "tree", size: null }, + { name: "README.md", kind: "blob", size: 2048 }, + { name: `${long}-file.txt`, kind: "blob", size: 123456 }, + { name: "third_party", kind: "submodule", size: null }, +]; +const line = `int main(void) { return printf("%s\\n", "${long}${long}") > 0 ? 0 : 1; }`; +const commits = Array.from({ length: 12 }, (_, index) => ({ + commit: index === 0 ? commit : parent, + author: "Progmasoft", + date, + subject: `Change ${index}: a subject line long enough to wrap on a phone screen of 360 pixels`, +})); + +const routes = { + "/": [{ name: "Examples", repositories: [repository] }], + [`/${repository.name}`]: repository, + [`/${repository.name}/refs`]: { + branches: [ + { name: "main", commit, date, subject: commits[0].subject }, + { name: `feature/${long}`, commit: parent, date, subject: "Work" }, + ], + tags: [{ name: "example-1.0.0", commit, date, subject: "Release" }], + }, + [`/${repository.name}/log`]: { + reference: "main", + commit, + path: "", + page: 0, + commits, + hasMore: true, + }, + [`/${repository.name}/commits/${commit}`]: { + commit, + parents: [parent], + author: "Progmasoft", + authorDate: date, + committer: "Progmasoft", + commitDate: date, + message: `${commits[0].subject}\n\nThe body of the message, with a line that is long: ${long}${long}.`, + diff: [ + " src/main.c | 2 +-", + "", + "diff --git a/src/main.c b/src/main.c", + "--- a/src/main.c", + "+++ b/src/main.c", + "@@ -1 +1 @@", + `-${line}`, + `+${line}`, + ].join("\n"), + isDiffTruncated: false, + }, +}; + +function tree(path) { + if (path.endsWith(".c") || path.endsWith(".txt") || path.endsWith(".md")) { + return { + reference: "main", + commit, + path, + kind: "blob", + entries: null, + size: 2048, + isBinary: false, + text: Array.from({ length: 40 }, () => line).join("\n"), + isTruncated: false, + }; + } + return { + reference: "main", + commit, + path, + kind: "tree", + entries, + size: null, + isBinary: false, + text: null, + isTruncated: false, + }; +} + +const prefix = "/api/v1/git/repositories"; +const port = Number(process.env.FAKE_GIT_API_PORT ?? "3101"); + +createServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (url.pathname === "/health") { + response.end("Healthy"); + return; + } + const path = url.pathname.startsWith(prefix) + ? url.pathname.slice(prefix.length) || "/" + : null; + const body = + path === `/${repository.name}/tree` + ? tree(url.searchParams.get("path") ?? "") + : path === null + ? undefined + : routes[path]; + if (body === undefined) { + response.statusCode = 404; + response.end(); + return; + } + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(body)); +}).listen(port, "127.0.0.1"); diff --git a/apps/web/e2e/pages.ts b/apps/web/e2e/pages.ts index 9ac50d1..67ffd3a 100644 --- a/apps/web/e2e/pages.ts +++ b/apps/web/e2e/pages.ts @@ -21,6 +21,12 @@ export const layoutPages = [ "license.progmasoft.com/pm-spl/1.0/faq/", "license.progmasoft.com/pm-spl/1.0/categories/", "agencelandmcp.progmasoft.com/", + "git.progmasoft.com/", + "git.progmasoft.com/example-with-a-rather-long-repository-name", + "git.progmasoft.com/example-with-a-rather-long-repository-name/tree?path=src/main.c", + "git.progmasoft.com/example-with-a-rather-long-repository-name/log", + "git.progmasoft.com/example-with-a-rather-long-repository-name/refs", + "git.progmasoft.com/example-with-a-rather-long-repository-name/commit/0123456789abcdef0123456789abcdef01234567", ] as const; /** Every host name of the pages above. */ diff --git a/apps/web/lib/git-messages.ts b/apps/web/lib/git-messages.ts new file mode 100644 index 0000000..5e22011 --- /dev/null +++ b/apps/web/lib/git-messages.ts @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import type { Locale } from "./localization"; + +/** The words of git.progmasoft.com. */ +export interface GitMessages { + metadataTitle: string; + title: string; + description: string; + repository: string; + updated: string; + clone: string; + developedOn: string; + files: string; + name: string; + size: string; + recentCommits: string; + log: string; + refs: string; + branches: string; + tags: string; + branch: string; + commit: string; + author: string; + committer: string; + date: string; + parents: string; + changes: string; + raw: string; + archive: string; + older: string; + newer: string; + binary: string; + truncated: string; + diffTruncated: string; + directory: string; + link: string; + submodule: string; + root: string; + noRepositories: string; +} + +export const gitMessages: Record<Locale, GitMessages> = { + "en-US": { + metadataTitle: "Progmasoft Git", + title: "Progmasoft Git", + description: + "Read-only mirrors of the repositories of Progmasoft. Issues and pull requests are on GitHub.", + repository: "Repository", + updated: "Updated", + clone: "Clone", + developedOn: "Developed on GitHub", + files: "Files", + name: "Name", + size: "Size", + recentCommits: "Recent commits", + log: "Log", + refs: "Branches and tags", + branches: "Branches", + tags: "Tags", + branch: "Branch or tag", + commit: "Commit", + author: "Author", + committer: "Committer", + date: "Date", + parents: "Parents", + changes: "Changes", + raw: "Raw", + archive: "Download .tar.gz", + older: "Older commits", + newer: "Newer commits", + binary: "A binary file: it is not shown.", + truncated: "The file is longer than what is shown.", + diffTruncated: "The changes are longer than what is shown.", + directory: "directory", + link: "link", + submodule: "submodule", + root: "root", + noRepositories: "No repository is mirrored.", + }, + "de-DE": { + metadataTitle: "Progmasoft Git", + title: "Progmasoft Git", + description: + "Schreibgeschützte Spiegel der Repositories von Progmasoft. Issues und Pull Requests sind auf GitHub.", + repository: "Repository", + updated: "Aktualisiert", + clone: "Klonen", + developedOn: "Entwickelt auf GitHub", + files: "Dateien", + name: "Name", + size: "Größe", + recentCommits: "Letzte Commits", + log: "Verlauf", + refs: "Branches und Tags", + branches: "Branches", + tags: "Tags", + branch: "Branch oder Tag", + commit: "Commit", + author: "Autor", + committer: "Committer", + date: "Datum", + parents: "Eltern", + changes: "Änderungen", + raw: "Roh", + archive: ".tar.gz herunterladen", + older: "Ältere Commits", + newer: "Neuere Commits", + binary: "Eine Binärdatei: Sie wird nicht angezeigt.", + truncated: "Die Datei ist länger als das Angezeigte.", + diffTruncated: "Die Änderungen sind länger als das Angezeigte.", + directory: "Verzeichnis", + link: "Link", + submodule: "Submodul", + root: "Wurzel", + noRepositories: "Kein Repository wird gespiegelt.", + }, + "ru-RU": { + metadataTitle: "Progmasoft Git", + title: "Progmasoft Git", + description: + "Зеркала репозиториев Progmasoft только для чтения. Задачи и pull request — на GitHub.", + repository: "Репозиторий", + updated: "Обновлён", + clone: "Клонировать", + developedOn: "Разрабатывается на GitHub", + files: "Файлы", + name: "Имя", + size: "Размер", + recentCommits: "Последние коммиты", + log: "История", + refs: "Ветки и теги", + branches: "Ветки", + tags: "Теги", + branch: "Ветка или тег", + commit: "Коммит", + author: "Автор", + committer: "Коммиттер", + date: "Дата", + parents: "Родители", + changes: "Изменения", + raw: "Исходный файл", + archive: "Скачать .tar.gz", + older: "Более старые коммиты", + newer: "Более новые коммиты", + binary: "Двоичный файл: он не показывается.", + truncated: "Файл длиннее показанного.", + diffTruncated: "Изменения длиннее показанного.", + directory: "каталог", + link: "ссылка", + submodule: "подмодуль", + root: "корень", + noRepositories: "Нет ни одного зеркала.", + }, + "fr-FR": { + metadataTitle: "Progmasoft Git", + title: "Progmasoft Git", + description: + "Des miroirs en lecture seule des dépôts de Progmasoft. Les tickets et les pull requests sont sur GitHub.", + repository: "Dépôt", + updated: "Mis à jour", + clone: "Cloner", + developedOn: "Développé sur GitHub", + files: "Fichiers", + name: "Nom", + size: "Taille", + recentCommits: "Derniers commits", + log: "Historique", + refs: "Branches et tags", + branches: "Branches", + tags: "Tags", + branch: "Branche ou tag", + commit: "Commit", + author: "Auteur", + committer: "Committer", + date: "Date", + parents: "Parents", + changes: "Modifications", + raw: "Brut", + archive: "Télécharger .tar.gz", + older: "Commits plus anciens", + newer: "Commits plus récents", + binary: "Un fichier binaire : il n’est pas affiché.", + truncated: "Le fichier est plus long que ce qui est affiché.", + diffTruncated: + "Les modifications sont plus longues que ce qui est affiché.", + directory: "répertoire", + link: "lien", + submodule: "sous-module", + root: "racine", + noRepositories: "Aucun dépôt n’est mis en miroir.", + }, +}; + +export function getGitMessages(locale: Locale): GitMessages { + return gitMessages[locale]; +} + +/** Drops the trailing slash of every path but the root. */ +function trimmed(pathname: string): string { + return pathname.length > 1 && pathname.endsWith("/") + ? pathname.slice(0, -1) + : pathname; +} + +const repositoryName = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/; +const commitId = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/; + +/** + * The public pages of git.progmasoft.com and the internal routes that render + * them. Clones, raw files and archives never reach Next.js: Nginx sends them + * to git-http-backend and the API. + */ +export function gitRoute(pathname: string): string | null { + const path = trimmed(pathname); + if (path === "/") { + return "/git"; + } + const [, name, view, extra, ...rest] = path.split("/"); + if (!name || !repositoryName.test(name) || name.endsWith(".git")) { + return null; + } + if (view === undefined) { + return `/git/${name}`; + } + if (rest.length === 0 && extra === undefined) { + return view === "tree" || view === "log" || view === "refs" + ? `/git/${name}/${view}` + : null; + } + return view === "commit" && extra && commitId.test(extra) && rest.length === 0 + ? `/git/${name}/commit/${extra}` + : null; +} diff --git a/apps/web/lib/git.server.ts b/apps/web/lib/git.server.ts new file mode 100644 index 0000000..87cb39d --- /dev/null +++ b/apps/web/lib/git.server.ts @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later + +import "server-only"; + +/** A repository, as the API lists it. */ +export interface GitRepository { + name: string; + description: string; + homepage: string; + cloneUrl: string; + defaultBranch: string | null; + updatedAt: string | null; +} + +export interface GitSection { + name: string; + repositories: GitRepository[]; +} + +export interface GitRef { + name: string; + commit: string; + date: string; + subject: string; +} + +export interface GitTreeEntry { + name: string; + kind: "tree" | "blob" | "link" | "submodule"; + size: number | null; +} + +export interface GitTree { + reference: string; + commit: string; + path: string; + kind: "tree" | "blob"; + entries: GitTreeEntry[] | null; + size: number | null; + isBinary: boolean; + text: string | null; + isTruncated: boolean; +} + +export interface GitLogEntry { + commit: string; + author: string; + date: string; + subject: string; +} + +export interface GitLog { + reference: string; + commit: string; + path: string; + page: number; + commits: GitLogEntry[]; + hasMore: boolean; +} + +export interface GitCommit { + commit: string; + parents: string[]; + author: string; + authorDate: string; + committer: string; + commitDate: string; + message: string; + diff: string; + isDiffTruncated: boolean; +} + +/** The account API on loopback; the Git endpoints answer it there. */ +const origin = process.env.PROGMAWEB_API_ORIGIN ?? "http://127.0.0.1:5085"; + +/** + * Reads one Git endpoint. A 404 is "no such thing" and returns null; any other + * failure throws, so the page shows its error rather than an empty listing. + */ +async function read<T>( + path: string, + query: Record<string, string | undefined> = {}, +): Promise<T | null> { + const url = new URL(`/api/v1/git/repositories${path}`, origin); + for (const [key, value] of Object.entries(query)) { + if (value) { + url.searchParams.set(key, value); + } + } + const response = await fetch(url, { cache: "no-store" }); + if (response.status === 404) { + return null; + } + if (!response.ok) { + throw new Error(`The Git API answered ${response.status} for ${path}.`); + } + return (await response.json()) as T; +} + +export function gitSections(): Promise<GitSection[] | null> { + return read<GitSection[]>("/"); +} + +export function gitRepository(name: string): Promise<GitRepository | null> { + return read<GitRepository>(`/${encodeURIComponent(name)}`); +} + +export function gitRefs( + name: string, +): Promise<{ branches: GitRef[]; tags: GitRef[] } | null> { + return read(`/${encodeURIComponent(name)}/refs`); +} + +export function gitTree( + name: string, + ref?: string, + path?: string, +): Promise<GitTree | null> { + return read<GitTree>(`/${encodeURIComponent(name)}/tree`, { ref, path }); +} + +export function gitLog( + name: string, + ref?: string, + path?: string, + page?: number, +): Promise<GitLog | null> { + return read<GitLog>(`/${encodeURIComponent(name)}/log`, { + ref, + path, + page: page ? String(page) : undefined, + }); +} + +export function gitCommit( + name: string, + commit: string, +): Promise<GitCommit | null> { + return read<GitCommit>( + `/${encodeURIComponent(name)}/commits/${encodeURIComponent(commit)}`, + ); +} diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index 8f5568f..83d4da1 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -14,6 +14,7 @@ import { layoutHosts } from "./e2e/pages"; * request leaves the machine. */ const port = 3100; +const fakeApiPort = 3101; const hostRules = layoutHosts .map((host) => `MAP ${host} 127.0.0.1:${port}`) .join(", "); @@ -48,10 +49,21 @@ export default defineConfig({ }, { name: "desktop-1280", use: { viewport: { width: 1280, height: 800 } } }, ], - webServer: { - command: `pnpm exec next start --hostname 127.0.0.1 --port ${port}`, - url: `http://127.0.0.1:${port}/robots.txt`, - reuseExistingServer: !process.env.CI, - timeout: 120_000, - }, + webServer: [ + { + // The Git endpoints the pages of git.progmasoft.com read, from fixed data. + command: `node e2e/fake-git-api.mjs`, + url: `http://127.0.0.1:${fakeApiPort}/health`, + env: { FAKE_GIT_API_PORT: String(fakeApiPort) }, + reuseExistingServer: !process.env.CI, + timeout: 30_000, + }, + { + command: `pnpm exec next start --hostname 127.0.0.1 --port ${port}`, + url: `http://127.0.0.1:${port}/robots.txt`, + env: { PROGMAWEB_API_ORIGIN: `http://127.0.0.1:${fakeApiPort}` }, + reuseExistingServer: !process.env.CI, + timeout: 120_000, + }, + ], }); diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 3249856..38128f7 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -13,6 +13,7 @@ import { import { authorizeRoute, consoleRoute, issuerRoute } from "@/lib/credentials"; import { licenseRoute, productRoute } from "@/lib/sites"; import { mcpRoute } from "@/lib/mcp-messages"; +import { gitRoute } from "@/lib/git-messages"; import { contentSecurityPolicy, createNonce, @@ -64,6 +65,12 @@ const ownSites: OwnSite[] = [ route: licenseRoute, api: false, }, + { + hosts: hostsOf("git"), + root: "/git", + route: gitRoute, + api: false, + }, { hosts: hostsOf("agencelandmcp"), root: "/mcp", diff --git a/apps/web/tests/sites.test.mjs b/apps/web/tests/sites.test.mjs index 778ab57..7ac366d 100644 --- a/apps/web/tests/sites.test.mjs +++ b/apps/web/tests/sites.test.mjs @@ -13,6 +13,7 @@ import { } from "../lib/products.ts"; import { productRoute } from "../lib/sites.ts"; import { mcpMessages, mcpRoute } from "../lib/mcp-messages.ts"; +import { gitMessages, gitRoute } from "../lib/git-messages.ts"; function shape(value) { if (Array.isArray(value)) { @@ -90,3 +91,31 @@ test("the MCP Marketplace has its root alone, in every language", () => { assert.deepEqual(shape(mcpMessages[locale]), english, locale); } }); + +test("git.progmasoft.com has its listing and the views of each repository", () => { + const sha = "0123456789abcdef0123456789abcdef01234567"; + assert.equal(gitRoute("/"), "/git"); + assert.equal(gitRoute("/tazel"), "/git/tazel"); + assert.equal(gitRoute("/tazel/"), "/git/tazel"); + assert.equal(gitRoute("/tazel/tree"), "/git/tazel/tree"); + assert.equal(gitRoute("/tazel/log"), "/git/tazel/log"); + assert.equal(gitRoute("/tazel/refs"), "/git/tazel/refs"); + assert.equal(gitRoute(`/tazel/commit/${sha}`), `/git/tazel/commit/${sha}`); + for (const path of [ + "/tazel.git", + "/.hidden", + "/tazel/commit/HEAD", + "/tazel/commit", + `/tazel/commit/${sha}/extra`, + "/tazel/tree/src", + "/tazel/blame", + "/tazel/raw", + "/tazel/info/refs", + ]) { + assert.equal(gitRoute(path), null, path); + } + const english = shape(gitMessages["en-US"]); + for (const locale of supportedLocales) { + assert.deepEqual(shape(gitMessages[locale]), english, locale); + } +}); diff --git a/docs/ACCOUNT-API.md b/docs/ACCOUNT-API.md index eb6b529..f8a0c34 100644 --- a/docs/ACCOUNT-API.md +++ b/docs/ACCOUNT-API.md @@ -24,7 +24,8 @@ Every response carries `Cache-Control: no-store`. The same service also serves Progmasoft OAuth: `/connect/*` and `/.well-known/*`, and the JSON endpoints of its pages under `/api/v1/oauth` (`session`, `signin`, `signout`, `consent`, `allowed`, `applications`). They answer only on the -OAuth hosts and are described in [Progmasoft OAuth](OAUTH.md). +OAuth hosts and are described in [Progmasoft OAuth](OAUTH.md). The Git endpoints of git.progmasoft.com, +`/api/v1/git/repositories/...`, answer only there and on loopback; [Operations](../ops/README.md) describes them. ## Field rules @@ -164,6 +165,7 @@ The client address comes from `X-Forwarded-For`, which the service accepts from | `Authentication:Google:ClientSecret` | Google OAuth client secret | empty; Google sign-in is off | | `AllowedHosts` | host names the service answers | the apex, `www`, `account`, `credentials`, `authorize` and `console` hosts, and loopback (`appsettings.json`) | | `ConnectionStrings:Accounts` | the PostgreSQL database of accounts, sessions and OAuth | none; without it the store is in memory (development) | +| `Git:MirrorsPath`, `Git:CatalogPath`, `Git:Host` | the mirrors of git.progmasoft.com, their catalog, and the host | `/srv/git/mirrors`, `/etc/git-mirror/catalog.json`, `git.progmasoft.com` | | `OAuth:SigningKeyPath`, `OAuth:EncryptionKeyPath` | the keys that sign identity tokens and encrypt access tokens | see [Progmasoft OAuth](OAUTH.md) | | `ASPNETCORE_URLS` | listener address | `http://127.0.0.1:5085` in production | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5ff7395..592fb43 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -16,7 +16,7 @@ Both listen on loopback only. Nginx is the only public listener and terminates T browser | HTTPS v -Nginx (progmasoft.com, account., credentials., authorize., console., product., license., agencelandmcp.) +Nginx (progmasoft.com, account., credentials., authorize., console., product., license., agencelandmcp., git.) | | | pages: http://127.0.0.1:3010 | OAuth hosts only: /connect/*, /.well-known/* (issuer) v | and /api/* go straight to http://127.0.0.1:5085 @@ -27,7 +27,9 @@ ASP.NET Core API (apps/api) ``` On `credentials.progmasoft.com` Nginx sends `/connect/`, `/.well-known/` and `/api/` to the API; on -`authorize.progmasoft.com` `/connect/` and `/api/`; on `console.progmasoft.com` `/api/`. Every other path of those +`authorize.progmasoft.com` `/connect/` and `/api/`; on `console.progmasoft.com` `/api/`; on `git.progmasoft.com` +`/<repo>/raw` and `/<repo>/archive`, and the clone paths to git-http-backend. The pages of the git host read the Git +endpoints of the API on loopback, the only other place they answer. Every other path of those hosts, and every path of the other hosts, goes to Next.js, which forwards `/api/*` itself. ## Hosts @@ -45,6 +47,7 @@ One build serves every host. The host of a request, not a separate deployment, d | `product.progmasoft.com` | the product catalog: `/`, `/<product>`, `/categories`, `/languages`, `/releases` | `/products` | | `license.progmasoft.com` | the Progmasoft Source License 1.0 and its pages | `/license` | | `agencelandmcp.progmasoft.com` | the Agenceland MCP Marketplace: one page, no server listed, no uploads | `/mcp` | +| `git.progmasoft.com` | the read-only mirrors: the listing, and the files, log, branches, tags and commits of each | `/git` | Nginx alone answers three more names from the same file: `viget.progmasoft.com` with 410 Gone (ViGet was closed), `catch3.progmasoft.com` with a permanent redirect to `catch3.uk`, and `maven.progmasoft.com` with the static Maven @@ -59,10 +62,10 @@ hosts during development. 1. **Language parameter.** `?lang=<locale>` with a published locale stores the language cookie and redirects to the same URL without the parameter. See [Localization](LOCALIZATION.md). -2. **Sites of their own.** On the credentials, authorize, console, product, license and agencelandmcp hosts, a public path is +2. **Sites of their own.** On the credentials, authorize, console, product, license, agencelandmcp and git hosts, a public path is rewritten into the host's internal tree (the table above); a path the host does not have shows its not-found page. `/api/*` passes through on the credentials, authorize and console hosts only. -3. **Internal trees stay internal.** `/issuer`, `/authorize`, `/console`, `/products`, `/license` and `/mcp` on any other host +3. **Internal trees stay internal.** `/issuer`, `/authorize`, `/console`, `/products`, `/license`, `/mcp` and `/git` on any other host show the not-found page. 4. **Account root.** `/` on the account host is rewritten to the internal `/account` page, so the account landing page has the short URL. @@ -91,6 +94,8 @@ The host is read from `X-Forwarded-Host` first and `Host` second, without the po | `/`, `/<product>`, `/categories`, `/languages`, `/releases` (product host) | the product catalog | yes | | `/`, `/pm-spl/1.0/<page>` (license host) | the Progmasoft Source License | yes | | `/` (agencelandmcp host) | the Agenceland MCP Marketplace | yes | +| `/`, `/<repo>` (git host) | the mirrors and each repository | yes | +| `/<repo>/tree`, `/<repo>/log`, `/<repo>/refs`, `/<repo>/commit/<sha>` (git host) | files, log, branches and tags, a commit | no | `robots.txt` and `sitemap.xml` are generated per host: the product and license hosts list their own pages, every other host lists the apex homepage only. Nginx additionally sends `X-Robots-Tag: noindex` for the whole account host. diff --git a/ops/README.md b/ops/README.md index b238d19..6d444f0 100644 --- a/ops/README.md +++ b/ops/README.md @@ -319,34 +319,47 @@ The certificate of `progmasoft.com` must name `rustreg.progmasoft.com`. `git.progmasoft.com` shows read-only mirrors of the public repositories under development, such as `https://git.progmasoft.com/tazel`. GitHub stays where development happens: issues, pull requests and CI, and the source -links of the sites. Private and archived repositories are not mirrored. The files are in `ops/git`: +links of the sites. Private and archived repositories are not mirrored. + +The pages are the Next.js site (`apps/web/app/git`, host `git.progmasoft.com`, internal tree `/git`): the listing, and +for each repository its files (`/<name>`, `/<name>/tree?path=&ref=`), its log (`/<name>/log`), its branches and tags +(`/<name>/refs`) and its commits (`/<name>/commit/<sha>`). They read the API on loopback +(`/api/v1/git/repositories/...`, `apps/api/Git`), which runs `git` on the mirrors: every argument is a resolved commit, +a checked name or a checked path, options end before anything a request gave, and Git runs without the system and +global configuration for at most 15 seconds. Nginx sends `/<name>/raw` and `/<name>/archive` to the API, which answers +raw files as plain text or a download and archives as `.tar.gz`, and the clone paths to git-http-backend. The API +answers the Git endpoints only on this host and on loopback, and nothing else on this host. + +The files are in `ops/git`: | File | Installed as | | --- | --- | -| `cgitrc` | `/etc/cgitrc`: the repositories, their sections and descriptions, and the look | -| `include/head.html`, `header.html`, `footer.html` | `/etc/cgit/progmasoft/`: the header and footer of progmasoft.com | -| `static/progmasoft-git.css`, `static/icon.svg` | `/srv/git/www/static/`: the tokens and brand of `apps/web/app/globals.css` | +| `catalog.json` | `/etc/git-mirror/catalog.json`: the sections, the repositories and their descriptions, which the API reads | | `repositories` | `/etc/git-mirror/repositories`: what is mirrored, one name per line | | `git-mirror.sh` | `/usr/local/libexec/git-mirror`, labelled `bin_t` | | `systemd/git-mirror.service`, `.timer` | `/etc/systemd/system/`: every ten minutes, as `gitmirror` | -| `systemd/fcgiwrap@cgit.*.d/` | `/etc/systemd/system/`: cgit and git-http-backend as `cgit`, socket for `nginx` only | -| `selinux/progmasoft_cgit.te` | the module `progmasoft_cgit` | +| `systemd/fcgiwrap@githttp.*.d/` | `/etc/systemd/system/`: git-http-backend as `githttp`, socket for `nginx` only | +| `selinux/progmasoft_githttp.te` | the module `progmasoft_githttp` | | `nginx/git.conf` | `/etc/nginx/conf.d/git.conf` | -Packages: `git-core`, and `cgit` and `fcgiwrap` from EPEL; `checkpolicy` builds the module. +Packages: `git-core`, and `fcgiwrap` from EPEL; `checkpolicy` builds the module. `githttp` is a system user without a +shell or a home (`useradd --system --shell /sbin/nologin --no-create-home githttp`). The API reads the mirrors as +`progmaweb`; `ProtectSystem=strict` leaves `/srv` readable. - **Mirrors.** `git-mirror` fetches only branches and tags from `https://github.com/Progmasoft/<name>.git` (never the pull-request refs), prunes what GitHub removed, follows its default branch, and repacks into one pack with a bitmap when something changed, so a clone starts sending at once. It needs no credentials. A new repository needs a line in - `repositories` and a `repo.url` block in `cgitrc`. git-http-backend serves only the mirrors `git-mirror` marks with - `git-daemon-export-ok`; a mirror taken off `repositories` loses the mark and is deleted on the next run, so a - repository that becomes private or archived stops being cloned within ten minutes. + `repositories` and an entry in `catalog.json` (a test checks that both name the same repositories). git-http-backend + serves only the mirrors `git-mirror` marks with `git-daemon-export-ok`; a mirror taken off `repositories` loses the + mark and is deleted on the next run, so a repository that becomes private or archived stops being cloned within ten + minutes, and the API shows only repositories whose mirror exists. - **Read only.** Nginx answers 403 to `git-receive-pack` and to the dumb protocol; git-http-backend gets no user; the - mirrors belong to `gitmirror` and are read as `cgit`, trusted through `safe.directory` for that backend only. -- **SELinux.** `/srv/git/mirrors` is `git_sys_content_t` and `/var/cache/cgit` `git_rw_content_t` (package default). - `/usr/bin/fcgiwrap` is `httpd_exec_t`, so fcgiwrap runs in `httpd_t` and Nginx may connect to it, and - `git-http-backend` is `git_script_exec_t` like cgit, so both move into `git_script_t`. systemd's sandboxing sets - NoNewPrivileges; the module `progmasoft_cgit` allows exactly that one move under it. + mirrors belong to `gitmirror` and are read as `githttp` and `progmaweb`, each trusting them through `safe.directory` + for its own runs only. +- **SELinux.** `/srv/git/mirrors` is `git_sys_content_t`. `/usr/bin/fcgiwrap` is `httpd_exec_t`, so fcgiwrap runs in + `httpd_t` and Nginx may connect to it, and `git-http-backend` is `git_script_exec_t`, so it moves into + `git_script_t`. systemd's sandboxing sets NoNewPrivileges; the module `progmasoft_githttp` allows exactly that one + move under it. ```sh semanage fcontext -a -t git_sys_content_t '/srv/git/mirrors(/.*)?' @@ -357,12 +370,11 @@ Packages: `git-core`, and `cgit` and `fcgiwrap` from EPEL; `checkpolicy` builds semanage fcontext -a -t git_script_exec_t /usr/libexec/git-core/git-http-backend restorecon -RF /srv/git /usr/local/libexec/git-mirror /usr/sbin/fcgiwrap /usr/libexec/git-core/git-http-backend ``` - - `/srv/git/www/static` needs no rule of its own: the stock policy labels `/srv/*/www` `httpd_sys_content_t`. - **No Cloudflare proxy.** `git.progmasoft.com` is a DNS-only A record: through the proxy, a clone of a large repository (catch3, about 25 MB) never reached the client, while the origin served it in under a minute. The address of the server - is public through `mail.progmasoft.com` anyway; Nginx limits requests and connections per address itself. The record - is in `cloudflarectl/config.progmasoft.json`. -- **Look.** No README is rendered (cgit would include its HTML unfiltered) and no script runs: the content security - policy allows none, and Nginx removes the inline `onchange` handlers of cgit's menus, whose buttons do the same. + is public through `mail.progmasoft.com` anyway; Nginx limits requests and connections per address itself, and the + API limits its Git endpoints to 600 requests a minute per address. The record is in + `cloudflarectl/config.progmasoft.json`. +- **Look.** The pages are those of progmasoft.com: the same header, footer, languages and theme, and their content + security policy. A README is not rendered; files are shown as text. - **Certificate.** The certificate of `progmasoft.com` names `git.progmasoft.com` (webroot, `--expand`). diff --git a/ops/git/catalog.json b/ops/git/catalog.json new file mode 100644 index 0000000..946d975 --- /dev/null +++ b/ops/git/catalog.json @@ -0,0 +1,39 @@ +{ + "sections": [ + { + "name": "Tazel", + "repositories": [ + { + "name": "tazel", + "description": "A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files." + }, + { + "name": "tazelish", + "description": "Installs Tazel and chooses which version of it runs." + } + ] + }, + { + "name": "C++", + "repositories": [ + { + "name": "catch3", + "description": "Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results." + }, + { + "name": "progmasoft-cpp", + "description": "The C++ style guide of Progmasoft: naming, formatting, language rules, errors, ownership, ABI, testing and tooling." + } + ] + }, + { + "name": "Sites", + "repositories": [ + { + "name": "progmaweb", + "description": "The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API." + } + ] + } + ] +} diff --git a/ops/git/cgitrc b/ops/git/cgitrc deleted file mode 100644 index c9e8050..0000000 --- a/ops/git/cgitrc +++ /dev/null @@ -1,67 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -# SPDX-License-Identifier: AGPL-3.0-or-later - -# cgit of https://git.progmasoft.com: read-only mirrors of the public repositories of Progmasoft -# that are under development. Development happens on GitHub; git-mirror.timer fetches from there. -# Installed as /etc/cgitrc. - -root-title=Progmasoft Git -root-desc=Read-only mirrors of the repositories of Progmasoft. Issues and pull requests are on GitHub. -virtual-root=/ -remove-suffix=1 - -# The look of progmasoft.com: its stylesheet, header and footer. -css=/static/progmasoft-git.css -favicon=/static/icon.svg -logo= -head-include=/etc/cgit/progmasoft/head.html -header=/etc/cgit/progmasoft/header.html -footer=/etc/cgit/progmasoft/footer.html - -# Clones go to git-http-backend (smart HTTP, upload-pack only); cgit's own dumb HTTP stays off. -enable-http-clone=0 -clone-url=https://git.progmasoft.com/$CGIT_REPO_URL - -# No README is rendered: without a filter cgit would include its HTML as it is. -enable-index-owner=0 -enable-index-links=0 -enable-blame=0 -enable-commit-graph=0 -enable-log-filecount=1 -enable-log-linecount=0 -noplainemail=1 -max-stats= -snapshots=tar.gz -side-by-side-diffs=0 -robots=index, nofollow - -cache-root=/var/cache/cgit -cache-size=1000 - -section=Tazel -repo.url=tazel -repo.path=/srv/git/mirrors/tazel.git -repo.desc=A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files. -repo.homepage=https://github.com/Progmasoft/tazel - -repo.url=tazelish -repo.path=/srv/git/mirrors/tazelish.git -repo.desc=Installs Tazel and chooses which version of it runs. -repo.homepage=https://github.com/Progmasoft/tazelish - -section=C++ -repo.url=catch3 -repo.path=/srv/git/mirrors/catch3.git -repo.desc=Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results. -repo.homepage=https://github.com/Progmasoft/catch3 - -repo.url=progmasoft-cpp -repo.path=/srv/git/mirrors/progmasoft-cpp.git -repo.desc=The C++ style guide of Progmasoft: naming, formatting, language rules, errors, ownership, ABI, testing and tooling. -repo.homepage=https://github.com/Progmasoft/progmasoft-cpp - -section=Sites -repo.url=progmaweb -repo.path=/srv/git/mirrors/progmaweb.git -repo.desc=The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API. -repo.homepage=https://github.com/Progmasoft/progmaweb diff --git a/ops/git/git-mirror.sh b/ops/git/git-mirror.sh index b3f292e..3833869 100644 --- a/ops/git/git-mirror.sh +++ b/ops/git/git-mirror.sh @@ -50,9 +50,6 @@ for name in $names; do fi # git-http-backend serves only repositories with this file. touch "$repository/git-daemon-export-ok" - # cgit shows the age of the last change of a repository from this file. - git -C "$repository" for-each-ref --sort=-committerdate --count=1 \ - --format='%(committerdate:iso8601)' refs/heads > "$repository/info/web/last-modified" else echo "git-mirror: fetching $name failed" >&2 status=1 diff --git a/ops/git/include/footer.html b/ops/git/include/footer.html deleted file mode 100644 index 3e4f5f1..0000000 --- a/ops/git/include/footer.html +++ /dev/null @@ -1,6 +0,0 @@ -<footer class="site-footer"> - <div class="shell footer-bottom"> - <span>© 2026 Progmasoft</span> - <span>Mirrored from GitHub every ten minutes.</span> - </div> -</footer> diff --git a/ops/git/include/head.html b/ops/git/include/head.html deleted file mode 100644 index 73da116..0000000 --- a/ops/git/include/head.html +++ /dev/null @@ -1,2 +0,0 @@ -<meta name="viewport" content="width=device-width, initial-scale=1"> -<meta name="theme-color" content="#0066b8"> diff --git a/ops/git/include/header.html b/ops/git/include/header.html deleted file mode 100644 index 8b14244..0000000 --- a/ops/git/include/header.html +++ /dev/null @@ -1,19 +0,0 @@ -<header class="site-header"> - <div class="shell header-inner"> - <a class="brand" href="https://git.progmasoft.com/"> - <span class="brand-mark" aria-hidden="true"> - <span class="brand-tile brand-tile-slate"></span> - <span class="brand-tile brand-tile-teal"></span> - <span class="brand-tile brand-tile-violet"></span> - <span class="brand-tile brand-tile-orange"></span> - </span> - <strong class="brand-name">Progmasoft</strong> - <span class="brand-product">Git</span> - </a> - <nav class="primary-nav" aria-label="Primary"> - <a href="https://progmasoft.com/">Progmasoft</a> - <a class="button button-small" href="https://github.com/Progmasoft">GitHub</a> - </nav> - </div> -</header> -<p class="shell mirror-note">Read-only mirrors. Development, issues and pull requests are on GitHub.</p> diff --git a/ops/git/nginx/git.conf b/ops/git/nginx/git.conf index 6938a98..dbf20a3 100644 --- a/ops/git/nginx/git.conf +++ b/ops/git/nginx/git.conf @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> # SPDX-License-Identifier: AGPL-3.0-or-later -# https://git.progmasoft.com: cgit over read-only mirrors, and clones over smart HTTP with -# git-http-backend (upload-pack only). Installed as /etc/nginx/conf.d/git.conf. +# https://git.progmasoft.com: the pages of the read-only mirrors from the Next.js site of Progmaweb, +# raw files and archives from its API, and clones over smart HTTP with git-http-backend +# (upload-pack only). Installed as /etc/nginx/conf.d/git.conf. limit_req_zone $binary_remote_addr zone=git_pages:10m rate=10r/s; limit_req_zone $binary_remote_addr zone=git_clones:10m rate=1r/s; @@ -42,21 +43,8 @@ server { add_header X-Frame-Options "DENY" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; - # cgit writes no scripts; its diffstat bars set their width in style attributes. - add_header Content-Security-Policy "default-src 'none'; style-src-elem 'self'; style-src-attr 'unsafe-inline'; img-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always; - - location ^~ /static/ { - alias /srv/git/www/static/; - expires 1d; - add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; - add_header X-Content-Type-Options "nosniff" always; - add_header Content-Security-Policy "default-src 'none'; style-src 'self'" always; - } - - location = /robots.txt { - default_type text/plain; - return 200 "User-agent: *\nDisallow: /*/snapshot/\nDisallow: /*/log/\nDisallow: /*/diff/\nDisallow: /*/patch/\n"; - } + # Next.js gives every page its own content security policy with a nonce; the API gives raw files + # and archives one that allows nothing. # Pushing is never possible: no receive-pack, and the dumb protocol is off. location ~ ^/[A-Za-z0-9._-]+/git-receive-pack$ { @@ -76,14 +64,15 @@ server { } limit_req zone=git_clones burst=10 nodelay; - fastcgi_pass unix:/run/fcgiwrap/fcgiwrap-cgit.sock; + fastcgi_pass unix:/run/fcgiwrap/fcgiwrap-githttp.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME /usr/libexec/git-core/git-http-backend; fastcgi_param GIT_PROJECT_ROOT /srv/git/mirrors; # No GIT_HTTP_EXPORT_ALL: only mirrors git-mirror marks with git-daemon-export-ok are served. fastcgi_param PATH_INFO /$git_repo.git/$git_path; fastcgi_param REMOTE_USER ""; - # The mirrors belong to gitmirror and are read as cgit; only this backend trusts them. + # The mirrors belong to gitmirror and are read as the user of the fcgiwrap instance; only this + # backend trusts them. fastcgi_param GIT_CONFIG_COUNT 1; fastcgi_param GIT_CONFIG_KEY_0 safe.directory; fastcgi_param GIT_CONFIG_VALUE_0 /srv/git/mirrors/*; @@ -94,20 +83,29 @@ server { fastcgi_max_temp_file_size 2048m; } - location / { + # Raw files and archives come from the API; the name is a repository name, and the API checks + # it against the catalog. + location ~ ^/(?<git_name>[A-Za-z0-9_-][A-Za-z0-9._-]*)/(?<git_view>raw|archive)$ { limit_req zone=git_pages burst=40 nodelay; - # The menus of cgit (branch, diff options) submit themselves from inline handlers, which the - # policy above blocks; their buttons ("switch", "reload") do the same without a script. - sub_filter " onchange='this.form.submit();'" ""; - sub_filter_once off; + proxy_pass http://127.0.0.1:5085/api/v1/git/repositories/$git_name/$git_view$is_args$args; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_read_timeout 120s; + } - fastcgi_pass unix:/run/fcgiwrap/fcgiwrap-cgit.sock; - include fastcgi_params; - fastcgi_param SCRIPT_FILENAME /var/www/cgi-bin/cgit; - fastcgi_param CGIT_CONFIG /etc/cgitrc; - fastcgi_param PATH_INFO $uri; - fastcgi_param QUERY_STRING $args; - fastcgi_param HTTP_HOST $server_name; - fastcgi_read_timeout 60s; + # Every other path is a page of the Next.js site. + location / { + limit_req zone=git_pages burst=40 nodelay; + proxy_pass http://127.0.0.1:3010; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_read_timeout 60s; } } diff --git a/ops/git/repositories b/ops/git/repositories index ff7aaae..a1c5b87 100644 --- a/ops/git/repositories +++ b/ops/git/repositories @@ -1,5 +1,5 @@ # The repositories git-mirror.service mirrors from https://github.com/Progmasoft, one per line. -# Each must also have a repo.url entry in cgitrc. Installed as /etc/git-mirror/repositories. +# Each must also be in catalog.json, which the pages read. Installed as /etc/git-mirror/repositories. tazel tazelish catch3 diff --git a/ops/git/selinux/progmasoft_cgit.te b/ops/git/selinux/progmasoft_cgit.te deleted file mode 100644 index 6703728..0000000 --- a/ops/git/selinux/progmasoft_cgit.te +++ /dev/null @@ -1,18 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -# SPDX-License-Identifier: AGPL-3.0-or-later - -# fcgiwrap@cgit runs in httpd_t under NoNewPrivileges, which systemd sets for its sandboxing. -# This lets cgit and git-http-backend move from there into git_script_t, the narrower domain the -# policy gives them; nothing else is allowed. Built and loaded with: -# checkmodule -M -m -o progmasoft_cgit.mod progmasoft_cgit.te -# semodule_package -o progmasoft_cgit.pp -m progmasoft_cgit.mod -# semodule -i progmasoft_cgit.pp -module progmasoft_cgit 1.0; - -require { - type httpd_t; - type git_script_t; - class process2 nnp_transition; -} - -allow httpd_t git_script_t:process2 nnp_transition; diff --git a/ops/git/selinux/progmasoft_githttp.te b/ops/git/selinux/progmasoft_githttp.te new file mode 100644 index 0000000..bcda06c --- /dev/null +++ b/ops/git/selinux/progmasoft_githttp.te @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: AGPL-3.0-or-later + +# fcgiwrap@githttp runs in httpd_t under NoNewPrivileges, which systemd sets for its sandboxing. +# This lets git-http-backend move from there into git_script_t, the narrower domain the +# policy gives it; nothing else is allowed. Built and loaded with: +# checkmodule -M -m -o progmasoft_githttp.mod progmasoft_githttp.te +# semodule_package -o progmasoft_githttp.pp -m progmasoft_githttp.mod +# semodule -i progmasoft_githttp.pp +module progmasoft_githttp 1.0; + +require { + type httpd_t; + type git_script_t; + class process2 nnp_transition; +} + +allow httpd_t git_script_t:process2 nnp_transition; diff --git a/ops/git/static/icon.svg b/ops/git/static/icon.svg deleted file mode 100644 index c7c9ead..0000000 --- a/ops/git/static/icon.svg +++ /dev/null @@ -1,7 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 100 312 312"> - <title>Progmasoft</title> - <rect x="112" y="112" width="132" height="132" fill="#3b4658"/> - <rect x="268" y="112" width="132" height="132" fill="#1e7188"/> - <rect x="112" y="268" width="132" height="132" fill="#7655fa"/> - <rect x="268" y="268" width="132" height="132" fill="#dc7644"/> -</svg> diff --git a/ops/git/static/progmasoft-git.css b/ops/git/static/progmasoft-git.css deleted file mode 100644 index 8222d0b..0000000 --- a/ops/git/static/progmasoft-git.css +++ /dev/null @@ -1,730 +0,0 @@ -/* SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> */ -/* SPDX-License-Identifier: AGPL-3.0-or-later */ - -/* The look of progmasoft.com for cgit: the same tokens, brand, header and footer as - apps/web/app/globals.css, applied to the markup cgit writes. Light, like the default of - progmasoft.com; this site keeps no preferences. */ - -:root { - --blue-700: #004e8c; - --blue-600: #0066b8; - --blue-500: #0078d4; - --blue-100: #dff0ff; - --green-600: #16825d; - --ink-950: #121417; - --ink-800: #2a2f35; - --ink-650: #4c545d; - --ink-500: #68717c; - --line: #d9dee4; - --line-strong: #b9c1ca; - --surface: #ffffff; - --surface-muted: #f5f7f9; - --surface-blue: #f1f8ff; - --header-surface: rgb(255 255 255 / 94%); - --danger: #b42318; - --radius-sm: 4px; - --radius-md: 8px; - --shell: 1180px; - --mono: ui-monospace, "Cascadia Code", "SF Mono", Menlo, Consolas, monospace; - color-scheme: light; -} - -* { - box-sizing: border-box; -} - -body { - margin: 0; - background: var(--surface); - color: var(--ink-950); - font-family: - "Segoe UI Variable", - "Segoe UI", - system-ui, - -apple-system, - BlinkMacSystemFont, - sans-serif; - font-size: 15px; - line-height: 1.5; - text-rendering: optimizeLegibility; - /* The header and footer reach the edges of the window from inside div#cgit. */ - overflow-x: hidden; -} - -a { - color: var(--blue-600); - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - -:focus-visible { - outline: 3px solid #ffbf47; - outline-offset: 3px; -} - -.shell { - width: min(calc(100% - 40px), var(--shell)); - margin-inline: auto; -} - -/* ----- Header and footer, as on progmasoft.com ----- */ - -.site-header { - min-height: 68px; - border-bottom: 1px solid var(--line); - background: var(--header-surface); -} - -.header-inner { - min-height: 68px; - display: flex; - align-items: center; - justify-content: space-between; - gap: 24px; -} - -.brand { - display: inline-flex; - align-items: center; - gap: 11px; - color: var(--ink-950); -} - -.brand:hover { - text-decoration: none; -} - -.brand-mark { - width: 24px; - height: 24px; - display: grid; - flex: 0 0 auto; - grid-template-columns: repeat(2, 1fr); - grid-template-rows: repeat(2, 1fr); - gap: 2px; -} - -.brand-tile { - display: block; -} - -.brand-tile-slate { - background: #3b4658; -} - -.brand-tile-teal { - background: #1e7188; -} - -.brand-tile-violet { - background: #7655fa; -} - -.brand-tile-orange { - background: #dc7644; -} - -.brand-name { - color: #8e0000; - font-size: 20px; - font-weight: 650; - letter-spacing: -0.02em; - line-height: 1; -} - -.brand-product { - border-left: 2px solid var(--ink-800); - margin-left: 5px; - padding-left: 16px; - color: var(--ink-800); - font-size: 16px; - font-weight: 600; -} - -.primary-nav { - display: flex; - align-items: center; - gap: 28px; -} - -.primary-nav a { - color: var(--ink-800); - font-weight: 600; -} - -.primary-nav a:hover { - color: var(--blue-600); - text-decoration: none; -} - -.button { - display: inline-flex; - align-items: center; - border-radius: var(--radius-sm); - background: var(--blue-600); - color: #fff; - font-weight: 700; -} - -.primary-nav a.button, -.primary-nav a.button:hover { - color: #fff; -} - -.button:hover { - background: var(--blue-700); - text-decoration: none; -} - -.button-small { - min-height: 36px; - padding: 7px 14px; - font-size: 14px; -} - -.mirror-note { - margin-block: 18px 0; - border: 1px solid var(--line); - border-radius: var(--radius-md); - padding: 10px 14px; - background: var(--surface-blue); - color: var(--ink-650); - font-size: 14px; -} - -.site-footer { - margin-top: 56px; - border-top: 1px solid #343a40; - background: #20252a; - color: #d8dde2; -} - -.footer-bottom { - min-height: 64px; - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - font-size: 14px; -} - -/* ----- The page cgit writes ----- */ - -div#cgit { - width: min(calc(100% - 40px), var(--shell)); - margin-inline: auto; -} - -/* cgit writes the header before div#cgit and the footer inside it; the footer still reaches the - edges of the window. */ -div#cgit > .site-footer { - margin-inline: calc(50% - 50vw); - padding-inline: calc(50vw - 50%); -} - -table#header { - width: 100%; - margin-top: 28px; - border-collapse: collapse; -} - -table#header td.logo { - display: none; -} - -table#header td.main { - color: var(--ink-950); - font-size: 30px; - font-weight: 700; - letter-spacing: -0.02em; -} - -table#header td.main a { - color: var(--ink-950); -} - -table#header td.sub { - padding-top: 4px; - color: var(--ink-650); - font-size: 16px; -} - -table#header td.form { - text-align: right; - vertical-align: middle; -} - -table#header td.form form { - display: inline-flex; - gap: 6px; - align-items: center; -} - -table#header td.form select { - max-width: 260px; -} - -select, -input[type="search"], -input[type="text"], -input[type="submit"] { - min-height: 34px; - border: 1px solid var(--line); - border-radius: var(--radius-sm); - padding: 5px 9px; - background: var(--surface); - color: var(--ink-800); - font: inherit; - font-size: 14px; -} - -input[type="submit"] { - border-color: var(--blue-600); - background: var(--blue-600); - color: #fff; - font-weight: 700; - cursor: pointer; -} - -input[type="submit"]:hover { - background: var(--blue-700); -} - -table.tabs { - width: 100%; - margin-top: 22px; - border-collapse: collapse; - border-bottom: 1px solid var(--line); -} - -table.tabs td { - padding: 0; - vertical-align: bottom; -} - -table.tabs td a { - display: inline-block; - margin-right: 22px; - border-bottom: 3px solid transparent; - padding: 10px 0 9px; - color: var(--ink-650); - font-weight: 600; -} - -table.tabs td a.active, -table.tabs td a:hover { - border-bottom-color: var(--blue-600); - color: var(--ink-950); - text-decoration: none; -} - -table.tabs td.form { - padding-bottom: 8px; - text-align: right; -} - -table.tabs td.form form { - display: inline-flex; - gap: 6px; -} - -div.path { - margin-top: 14px; - color: var(--ink-650); - font-family: var(--mono); - font-size: 13px; -} - -div.content { - margin-top: 20px; - overflow-x: auto; -} - -div.cgit-panel { - float: right; - margin: 0 0 14px 18px; - border: 1px solid var(--line); - border-radius: var(--radius-md); - padding: 10px 12px; - background: var(--surface-muted); - font-size: 13px; -} - -div.cgit-panel b { - display: block; - margin-bottom: 6px; -} - -/* Lists: the repositories, refs, log and tree. */ -table.list { - width: 100%; - border: 1px solid var(--line); - border-radius: var(--radius-md); - border-collapse: separate; - border-spacing: 0; - overflow: hidden; -} - -table.list th { - border-bottom: 1px solid var(--line); - padding: 10px 12px; - background: var(--surface-muted); - color: var(--ink-650); - font-size: 13px; - font-weight: 700; - text-align: left; -} - -table.list td { - border-bottom: 1px solid var(--line); - padding: 9px 12px; - vertical-align: top; -} - -table.list tr:last-child td { - border-bottom: 0; -} - -table.list tr:hover td { - background: var(--surface-blue); -} - -table.list tr.nohover:hover td, -table.list tr.nohover-highlight:hover td { - background: transparent; -} - -/* The empty rows cgit puts between the parts of a summary. */ -table.list tr.nohover > td[colspan] { - height: 14px; - border-bottom: 0; - padding: 0; - font-size: 0; -} - -table.list tr.nohover > th { - border-top: 1px solid var(--line); -} - -table.list th a { - color: inherit; -} - -table.list td.reposection { - padding-top: 20px; - background: var(--surface); - color: var(--ink-950); - font-size: 13px; - font-weight: 700; - letter-spacing: 0.06em; - text-transform: uppercase; -} - -table.list td.toplevel-repo a, -table.list td.sublevel-repo a { - font-weight: 650; -} - -table.list td.commitgraph, -table.list td.ls-mode, -table.list td.ls-size, -table.list td.sha1, -td.ls-mode, -td.sha1 { - color: var(--ink-500); - font-family: var(--mono); - font-size: 13px; - white-space: nowrap; -} - -table.list td.ls-size { - text-align: right; -} - -a.ls-dir { - font-weight: 650; -} - -a.ls-blob, -a.ls-dir, -a.ls-mod { - font-family: var(--mono); - font-size: 14px; -} - -span.age-mins, -span.age-hours { - color: var(--green-600); - font-weight: 600; -} - -span.age-days, -span.age-weeks, -span.age-months, -span.age-years { - color: var(--ink-500); -} - -a.branch-deco, -a.tag-deco, -a.tag-annotated-deco, -a.remote-deco, -a.deco { - margin-left: 6px; - border: 1px solid var(--line-strong); - border-radius: 999px; - padding: 1px 8px; - background: var(--surface-muted); - color: var(--ink-800); - font-size: 12px; - font-weight: 600; -} - -a.branch-deco { - border-color: #a7d3b9; - background: #eaf7ef; - color: var(--green-600); -} - -a.tag-deco, -a.tag-annotated-deco { - border-color: #bcd8f2; - background: var(--surface-blue); - color: var(--blue-700); -} - -ul.pager { - display: flex; - gap: 8px; - justify-content: center; - margin: 18px 0 0; - padding: 0; - list-style: none; -} - -ul.pager a { - display: inline-block; - border: 1px solid var(--line); - border-radius: var(--radius-sm); - padding: 4px 10px; -} - -/* A commit. */ -table.commit-info { - width: auto; - border-collapse: collapse; - font-size: 14px; -} - -table.commit-info th { - width: 90px; - padding: 4px 12px 4px 0; - color: var(--ink-650); - font-weight: 600; - text-align: left; - vertical-align: top; -} - -table.commit-info td { - padding: 4px 0; - font-family: var(--mono); - font-size: 13px; -} - -div.commit-subject { - margin: 20px 0 8px; - font-size: 20px; - font-weight: 700; - letter-spacing: -0.01em; -} - -div.commit-msg { - border-left: 3px solid var(--line); - padding-left: 14px; - color: var(--ink-800); - font-family: var(--mono); - font-size: 13px; - white-space: pre-wrap; -} - -div.notes-header, -div.notes { - font-size: 13px; -} - -div.diffstat-header { - margin-top: 22px; - font-weight: 700; -} - -table.diffstat { - margin-top: 8px; - border: 1px solid var(--line); - border-radius: var(--radius-md); - border-collapse: separate; - border-spacing: 0; - padding: 6px 10px; - font-family: var(--mono); - font-size: 13px; -} - -table.diffstat td { - padding: 2px 8px; -} - -table.diffstat td.graph table { - border-collapse: collapse; -} - -/* Only the bars of the graph are coloured; a file cell has the same class names. */ -table.diffstat td.graph td.add { - background: var(--green-600); -} - -table.diffstat td.graph td.rem { - background: var(--danger); -} - -div.diffstat-summary { - margin-top: 6px; - color: var(--ink-650); - font-size: 13px; -} - -/* Diffs and files. */ -table.diff { - width: 100%; - margin-top: 18px; - border-collapse: collapse; -} - -table.diff td { - font-family: var(--mono); - font-size: 13px; - white-space: pre; -} - -table.diff td div.head { - margin-top: 18px; - border: 1px solid var(--line); - border-radius: var(--radius-sm) var(--radius-sm) 0 0; - padding: 8px 10px; - background: var(--surface-muted); - color: var(--ink-950); - font-weight: 700; - white-space: normal; -} - -table.diff td div.hunk { - padding: 2px 10px; - background: var(--surface-blue); - color: var(--blue-700); -} - -table.diff td div.add { - padding: 0 10px; - background: #e8f6ee; - color: #0d5c3f; -} - -table.diff td div.del { - padding: 0 10px; - background: #fdeceb; - color: #8c1d14; -} - -table.diff td div.ctx { - padding: 0 10px; - color: var(--ink-800); -} - -table.blob { - width: 100%; - border: 1px solid var(--line); - border-radius: var(--radius-md); - border-collapse: separate; - border-spacing: 0; - overflow: hidden; -} - -table.blob td { - padding: 10px 12px; - vertical-align: top; -} - -table.blob td.linenumbers { - border-right: 1px solid var(--line); - background: var(--surface-muted); - text-align: right; -} - -table.blob td.linenumbers a { - color: var(--ink-500); -} - -table.blob pre { - margin: 0; - font-family: var(--mono); - font-size: 13px; - line-height: 1.55; -} - -div.error { - border: 1px solid #f3c5c1; - border-radius: var(--radius-md); - padding: 12px 14px; - background: #fdeceb; - color: var(--danger); -} - -/* cgit's own footer is replaced by the one of progmasoft.com. */ -div.footer { - display: none; -} - -@media (max-width: 720px) { - .primary-nav { - gap: 14px; - } - - .primary-nav a:not(.button) { - display: none; - } - - .brand-product { - padding-left: 10px; - } - - table#header td.form, - table.tabs td.form { - display: none; - } - - table#header td.main { - font-size: 24px; - } - - div#cgit { - width: calc(100% - 24px); - } - - /* A list or a file wider than a phone scrolls inside its own box. */ - table.list, - table.blob, - table.diff, - div.content pre { - display: block; - max-width: 100%; - overflow-x: auto; - } - - .footer-bottom { - flex-direction: column; - align-items: flex-start; - justify-content: center; - padding-block: 14px; - } -} diff --git a/ops/git/systemd/fcgiwrap@cgit.service.d/hardening.conf b/ops/git/systemd/fcgiwrap@githttp.service.d/hardening.conf similarity index 75% rename from ops/git/systemd/fcgiwrap@cgit.service.d/hardening.conf rename to ops/git/systemd/fcgiwrap@githttp.service.d/hardening.conf index 65afc45..1928d0c 100644 --- a/ops/git/systemd/fcgiwrap@cgit.service.d/hardening.conf +++ b/ops/git/systemd/fcgiwrap@githttp.service.d/hardening.conf @@ -1,16 +1,15 @@ # SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> # SPDX-License-Identifier: AGPL-3.0-or-later -# cgit and git-http-backend read the mirrors and write only the cache of cgit; they reach no -# network and keep no rights of their own. +# git-http-backend reads the mirrors and writes nothing; it reaches no network and keeps no rights +# of its own. # # fcgiwrap runs in httpd_t (/usr/bin/fcgiwrap is httpd_exec_t), so Nginx may connect to it, and -# cgit and git-http-backend move into git_script_t; the module in ../selinux allows that move under +# git-http-backend moves into git_script_t; the module in ../selinux allows that move under # NoNewPrivileges. [Service] NoNewPrivileges=yes ProtectSystem=strict -ReadWritePaths=/var/cache/cgit ProtectHome=yes PrivateTmp=yes PrivateDevices=yes diff --git a/ops/git/systemd/fcgiwrap@cgit.service.d/processes.conf b/ops/git/systemd/fcgiwrap@githttp.service.d/processes.conf similarity index 50% rename from ops/git/systemd/fcgiwrap@cgit.service.d/processes.conf rename to ops/git/systemd/fcgiwrap@githttp.service.d/processes.conf index 79a1d1f..9b2e414 100644 --- a/ops/git/systemd/fcgiwrap@cgit.service.d/processes.conf +++ b/ops/git/systemd/fcgiwrap@githttp.service.d/processes.conf @@ -1,8 +1,8 @@ # SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> # SPDX-License-Identifier: AGPL-3.0-or-later -# Four workers, so a long clone does not hold up the pages. Without -f, what cgit and -# git-http-backend write to stderr goes to the journal, not to the visitor. +# Four workers, so a long clone does not hold up the others. Without -f, what git-http-backend +# writes to stderr goes to the journal, not to the visitor. [Service] ExecStart= ExecStart=/usr/sbin/fcgiwrap -c 4 diff --git a/ops/git/systemd/fcgiwrap@cgit.socket.d/nginx.conf b/ops/git/systemd/fcgiwrap@githttp.socket.d/nginx.conf similarity index 61% rename from ops/git/systemd/fcgiwrap@cgit.socket.d/nginx.conf rename to ops/git/systemd/fcgiwrap@githttp.socket.d/nginx.conf index e5897af..5e030c2 100644 --- a/ops/git/systemd/fcgiwrap@cgit.socket.d/nginx.conf +++ b/ops/git/systemd/fcgiwrap@githttp.socket.d/nginx.conf @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> # SPDX-License-Identifier: AGPL-3.0-or-later -# Only Nginx reaches cgit and git-http-backend: the socket belongs to cgit and the group nginx. +# Only Nginx reaches git-http-backend: the socket belongs to githttp and the group nginx. [Socket] SocketGroup=nginx SocketMode=0660