feat(go): implement current Node backend features

This commit is contained in:
Thomas Durieux committed 2026-11-14 14:12:47 +00:00
1 parent 566171342c
commit c201847b83
84 files changed
+8921 -384

No files matched your search

+8 -7
View File
@@ -22,13 +22,14 @@ const MaxInput = 100 * 1024 * 1024
const MaxOutput = 4 * MaxInput
type Options struct {
Terms []string `json:"terms" bson:"terms"`
Image *bool `json:"image,omitempty" bson:"image,omitempty"`
Link *bool `json:"link,omitempty" bson:"link,omitempty"`
RepoName string `json:"repoName,omitempty"`
BranchName string `json:"branchName,omitempty"`
RepoID string `json:"repoId,omitempty"`
SourceURLs []string `json:"sourceURLs"`
PreserveFiles []string `json:"preserveFiles,omitempty" bson:"preserveFiles,omitempty"`
Terms []string `json:"terms" bson:"terms"`
Image *bool `json:"image,omitempty" bson:"image,omitempty"`
Link *bool `json:"link,omitempty" bson:"link,omitempty"`
RepoName string `json:"repoName,omitempty"`
BranchName string `json:"branchName,omitempty"`
RepoID string `json:"repoId,omitempty"`
SourceURLs []string `json:"sourceURLs"`
}
type Context struct {
Mask string `json:"mask"`
+131
View File
@@ -0,0 +1,131 @@
package anonymize
import (
"errors"
"strings"
"unicode/utf16"
)
// NormalizePreserveFiles keeps the last duplicate because the last matching
// include/exclude rule decides whether term replacement is disabled.
func NormalizePreserveFiles(value any) ([]string, error) {
out := []string{}
if value == nil {
return out, nil
}
var values []any
switch v := value.(type) {
case []any:
values = v
case []string:
for _, s := range v {
values = append(values, s)
}
default:
return nil, errors.New("invalid_preserve_files_format")
}
for _, v := range values {
s, ok := v.(string)
if !ok {
return nil, errors.New("invalid_preserve_files_format")
}
s = strings.TrimSpace(s)
if s == "" {
continue
}
body := strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(s, "!"), "/"), "/")
if len(utf16.Encode([]rune(s))) > 512 || body == "" {
return nil, errors.New("invalid_preserve_files_format")
}
for _, part := range strings.Split(body, "/") {
if part == "" || part == ".." {
return nil, errors.New("invalid_preserve_files_format")
}
}
next := out[:0]
for _, old := range out {
if old != s {
next = append(next, old)
}
}
out = append(next, s)
}
if len(out) > 200 {
return nil, errors.New("invalid_preserve_files_format")
}
return out, nil
}
func preserveGlob(pattern, candidate string) bool {
budget := 4096
for _, expanded := range expandPreserveBraces(pattern, &budget) {
if preserveExpandedGlob(expanded, candidate) {
return true
}
}
return false
}
func preserveExpandedGlob(pattern, candidate string) bool {
// Globstar crosses directory boundaries. Other wildcards use path.Match's
// component-local matching, including bracket classes and backslash escapes.
parts, values := strings.Split(pattern, "/"), strings.Split(candidate, "/")
type key struct{ i, j int }
memo := map[key]bool{}
seen := map[key]bool{}
var match func(int, int) bool
match = func(i, j int) bool {
k := key{i, j}
if seen[k] {
return memo[k]
}
seen[k] = true
result := false
if i == len(parts) {
result = j == len(values)
} else if parts[i] == "**" {
result = match(i+1, j) || (j < len(values) && match(i, j+1))
if i == len(parts)-1 {
result = j < len(values) || i == 0
}
} else if j < len(values) {
ok := preserveComponent(parts[i], values[j])
result = ok && match(i+1, j+1)
}
memo[k] = result
return result
}
return match(0, 0)
}
func PreservedPath(file string, patterns []string) bool {
file = strings.TrimLeft(file, "/")
if file == "" {
return false
}
parts := strings.Split(file, "/")
result := false
for _, rule := range patterns {
negated := strings.HasPrefix(rule, "!")
body := strings.TrimPrefix(rule, "!")
anchored := strings.HasPrefix(body, "/")
body = strings.TrimPrefix(body, "/")
directory := strings.HasSuffix(body, "/")
body = strings.TrimSuffix(body, "/")
if result != negated {
continue
}
end := len(parts)
if directory {
end--
}
for i := 1; i <= end; i++ {
candidate := strings.Join(parts[:i], "/")
if !anchored && !strings.Contains(body, "/") {
candidate = parts[i-1]
}
if preserveGlob(body, candidate) {
result = !negated
break
}
}
}
return result
}
+259
View File
@@ -0,0 +1,259 @@
package anonymize
import (
"github.com/dlclark/regexp2"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// Bound expansion so a saved rule cannot multiply work exponentially.
func expandPreserveBraces(pattern string, budget *int) []string {
if *budget <= 0 {
return nil
}
start, depth := -1, 0
for i := 0; i < len(pattern); i++ {
if pattern[i] == '\\' {
i++
continue
}
if pattern[i] == '{' {
if start < 0 {
start = i
}
depth++
}
if pattern[i] != '}' || start < 0 {
continue
}
depth--
if depth != 0 {
continue
}
body := pattern[start+1 : i]
choices := []string{}
level, last := 0, 0
for j := 0; j < len(body); j++ {
if body[j] == '\\' {
j++
continue
}
switch body[j] {
case '{':
level++
case '}':
level--
case ',':
if level == 0 {
choices = append(choices, body[last:j])
last = j + 1
}
}
}
if len(choices) > 0 {
choices = append(choices, body[last:])
} else {
values := strings.Split(body, "..")
if len(values) == 2 || len(values) == 3 {
a, ae := strconv.Atoi(values[0])
b, be := strconv.Atoi(values[1])
alpha := false
if ae != nil || be != nil {
if len(values[0]) == 1 && len(values[1]) == 1 && ((values[0][0] >= 'a' && values[0][0] <= 'z' && values[1][0] >= 'a' && values[1][0] <= 'z') || (values[0][0] >= 'A' && values[0][0] <= 'Z' && values[1][0] >= 'A' && values[1][0] <= 'Z')) {
a, b, alpha = int(values[0][0]), int(values[1][0]), true
} else {
continue
}
}
step := 1
if len(values) == 3 {
var err error
step, err = strconv.Atoi(values[2])
if err != nil || step == 0 {
continue
}
if step < 0 {
step = -step
}
}
if a > b {
step = -step
}
width := 0
if !alpha {
for _, v := range values[:2] {
stripped := strings.TrimPrefix(v, "-")
if len(stripped) > 1 && stripped[0] == '0' && len(stripped) > width {
width = len(stripped)
}
}
}
for n := a; (step > 0 && n <= b) || (step < 0 && n >= b); n += step {
if len(choices) >= *budget {
return nil
}
value := strconv.Itoa(n)
if alpha {
value = string(rune(n))
} else if width > 0 {
sign := ""
if n < 0 {
sign = "-"
value = strings.TrimPrefix(value, "-")
}
if len(value) < width {
value = strings.Repeat("0", width-len(value)) + value
}
value = sign + value
}
choices = append(choices, value)
if (step > 0 && n > b-step) || (step < 0 && n < b-step) {
break
}
}
}
}
if len(choices) == 0 {
continue
}
out := []string{}
for _, choice := range choices {
out = append(out, expandPreserveBraces(pattern[:start]+choice+pattern[i+1:], budget)...)
if *budget <= 0 {
return out
}
}
return out
}
*budget--
return []string{pattern}
}
func preserveComponentRegex(pattern string) string {
out := ""
for i := 0; i < len(pattern); i++ {
c := pattern[i]
if c == '\\' && i+1 < len(pattern) {
i++
out += regexp.QuoteMeta(pattern[i : i+1])
continue
}
if strings.ContainsRune("@+?*!", rune(c)) && i+1 < len(pattern) && pattern[i+1] == '(' {
level, end := 1, -1
for j := i + 2; j < len(pattern); j++ {
if pattern[j] == '\\' {
j++
continue
}
if pattern[j] == '(' {
level++
}
if pattern[j] == ')' {
level--
if level == 0 {
end = j
break
}
}
}
if end >= 0 {
body := pattern[i+2 : end]
alternatives := []string{}
level, last := 0, 0
for j := 0; j < len(body); j++ {
if body[j] == '\\' {
j++
continue
}
if body[j] == '(' {
level++
}
if body[j] == ')' {
level--
}
if body[j] == '|' && level == 0 {
alternatives = append(alternatives, preserveComponentRegex(body[last:j]))
last = j + 1
}
}
alternatives = append(alternatives, preserveComponentRegex(body[last:]))
group := "(?:" + strings.Join(alternatives, "|") + ")"
suffix := preserveComponentRegex(pattern[end+1:])
if c == '!' {
return out + "(?!" + group + suffix + "$)[^/]*" + suffix
}
out += group
if c != '@' {
out += string(c)
}
i = end
continue
}
}
switch c {
case '*':
out += "[^/]*"
case '?':
out += "[^/]"
case '[':
end := -1
for j := i + 1; j < len(pattern); j++ {
if pattern[j] == '\\' {
j++
continue
}
if pattern[j] == ']' && j > i+1 {
end = j
break
}
}
if end < 0 {
out += `\[`
continue
}
class := pattern[i : end+1]
if strings.HasPrefix(class, "[!") {
class = "[^" + class[2:]
}
out += class
i = end
default:
out += regexp.QuoteMeta(string(c))
}
}
return out
}
var preserveComponents = struct {
sync.Mutex
expressions map[string]*regexp2.Regexp
}{expressions: map[string]*regexp2.Regexp{}}
func preserveComponent(pattern, value string) bool {
if !strings.ContainsAny(pattern, "*?[]()\\") {
return pattern == value
}
preserveComponents.Lock()
expression, exists := preserveComponents.expressions[pattern]
if !exists {
var err error
expression, err = regexp2.Compile("^(?:"+preserveComponentRegex(pattern)+")$", regexp2.ECMAScript)
if err != nil {
expression = nil
} else {
expression.MatchTimeout = 5 * time.Millisecond
}
if len(preserveComponents.expressions) >= 1024 {
clear(preserveComponents.expressions)
}
preserveComponents.expressions[pattern] = expression
}
preserveComponents.Unlock()
if expression == nil {
return pattern == value
}
matched, err := expression.MatchString(value)
return err == nil && matched
}
@@ -0,0 +1,38 @@
package anonymize
import (
"encoding/json"
"os"
"testing"
)
func TestNodePreserveFiles(t *testing.T) {
data, err := os.ReadFile("testdata/preserve-files.json")
if err != nil {
t.Fatal(err)
}
var cases []struct {
Patterns []string
Path string
Expected bool
}
if err = json.Unmarshal(data, &cases); err != nil {
t.Fatal(err)
}
for _, c := range cases {
if got := PreservedPath(c.Path, c.Patterns); got != c.Expected {
t.Errorf("%q %v: got %v want %v", c.Path, c.Patterns, got, c.Expected)
}
}
}
func TestPreserveNormalization(t *testing.T) {
for _, value := range []any{"refs.bib", []any{1}, []string{"//x"}, []string{"../x"}, []string{"!/"}} {
if _, err := NormalizePreserveFiles(value); err == nil {
t.Fatalf("accepted %v", value)
}
}
out, err := NormalizePreserveFiles([]string{"*.bib", "!secret.bib", "*.bib"})
if err != nil || len(out) != 2 || out[0] != "!secret.bib" {
t.Fatal(out, err)
}
}
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -1,7 +1,7 @@
-- Generated from src/core/blob-cache.ts by backend/contracts/blob-index.cjs.
CREATE TABLE IF NOT EXISTS aliases(key TEXT PRIMARY KEY,digest TEXT REFERENCES blobs(digest) ON DELETE CASCADE);
CREATE TABLE IF NOT EXISTS blobs(digest TEXT PRIMARY KEY,file TEXT,size INTEGER,stored INTEGER,encoding TEXT,accessed INTEGER,allocated INTEGER);
CREATE TABLE IF NOT EXISTS decisions(key TEXT PRIMARY KEY,digest TEXT,changed INTEGER,accessed INTEGER,expires INTEGER);
CREATE TABLE IF NOT EXISTS decisions(key TEXT PRIMARY KEY,digest TEXT,changed INTEGER,accessed INTEGER,expires INTEGER, isText INTEGER);
CREATE TABLE IF NOT EXISTS fills(key TEXT PRIMARY KEY,token TEXT,expires INTEGER,reserved INTEGER);
CREATE TABLE IF NOT EXISTS history(key TEXT PRIMARY KEY,seen INTEGER,evicted INTEGER);
CREATE TABLE IF NOT EXISTS maintenance(id INTEGER PRIMARY KEY,nextScan INTEGER);
@@ -24,13 +24,13 @@ CREATE TRIGGER IF NOT EXISTS summary_aliases_insert AFTER INSERT ON aliases BEGI
CREATE TRIGGER IF NOT EXISTS summary_blobs_delete AFTER DELETE ON blobs BEGIN UPDATE summary SET blobs=blobs-1,originalBytes=originalBytes-OLD.size,storedBytes=storedBytes-OLD.stored,allocatedBytes=allocatedBytes-OLD.allocated WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_blobs_insert AFTER INSERT ON blobs BEGIN UPDATE summary SET blobs=blobs+1,originalBytes=originalBytes+NEW.size,storedBytes=storedBytes+NEW.stored,allocatedBytes=allocatedBytes+NEW.allocated WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_blobs_update AFTER UPDATE OF size,stored,allocated ON blobs
BEGIN UPDATE summary SET originalBytes=originalBytes-OLD.size+NEW.size,storedBytes=storedBytes-OLD.stored+NEW.stored,allocatedBytes=allocatedBytes-OLD.allocated+NEW.allocated WHERE id=1; END;
BEGIN UPDATE summary SET originalBytes=originalBytes-OLD.size+NEW.size,storedBytes=storedBytes-OLD.stored+NEW.stored,allocatedBytes=allocatedBytes-OLD.allocated+NEW.allocated WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_decisions_delete AFTER DELETE ON decisions BEGIN UPDATE summary SET decisions=decisions-1 WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_decisions_insert AFTER INSERT ON decisions BEGIN UPDATE summary SET decisions=decisions+1 WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_fills_delete AFTER DELETE ON fills BEGIN UPDATE summary SET reservedBytes=reservedBytes-OLD.reserved WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_fills_insert AFTER INSERT ON fills BEGIN UPDATE summary SET reservedBytes=reservedBytes+NEW.reserved WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_fills_update AFTER UPDATE OF reserved ON fills
BEGIN UPDATE summary SET reservedBytes=reservedBytes-OLD.reserved+NEW.reserved WHERE id=1; END;
BEGIN UPDATE summary SET reservedBytes=reservedBytes-OLD.reserved+NEW.reserved WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_history_delete AFTER DELETE ON history BEGIN UPDATE summary SET history=history-1 WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_history_insert AFTER INSERT ON history BEGIN UPDATE summary SET history=history+1 WHERE id=1; END;
CREATE TRIGGER IF NOT EXISTS summary_readers_delete AFTER DELETE ON readers BEGIN UPDATE summary SET activeReaders=activeReaders-1 WHERE id=1; END;
+10 -3
View File
@@ -26,19 +26,26 @@ var names = map[string]bool{"license": true, "licence": true, "copying": true, "
var additional = map[string]bool{"license": true, "dockerfile": true, "sbt": true, "ipynb": true, "gp": true, "out": true, "sol": true, "in": true, "jsonl": true, "ndjson": true, "bat": true, "cmd": true, "ts": true}
var textual = map[string]bool{"application/json": true, "application/ld+json": true, "application/xml": true, "application/javascript": true, "application/ecmascript": true, "application/typescript": true, "application/toml": true, "application/sql": true, "application/x-sql": true, "application/x-sh": true, "application/x-csh": true, "application/x-yaml": true, "application/yaml": true, "application/x-httpd-php": true, "application/graphql": true, "application/x-tex": true, "application/x-latex": true, "application/x-perl": true, "application/x-ruby": true, "application/x-python": true}
func Text(name string, data []byte) bool {
func ClassifyName(name string) (bool, bool) {
base := strings.ToLower(path.Base(name))
parts := strings.Split(base, ".")
ext := parts[len(parts)-1]
if names[base] || additional[ext] {
return true
return true, true
}
mime := strings.Split(MIME(path.Ext(base)), ";")[0]
if mime != "" {
return strings.HasPrefix(mime, "text/") || textual[mime] || strings.HasSuffix(mime, "+json") || strings.HasSuffix(mime, "+xml") || strings.HasSuffix(mime, "+yaml")
return strings.HasPrefix(mime, "text/") || textual[mime] || strings.HasSuffix(mime, "+json") || strings.HasSuffix(mime, "+xml") || strings.HasSuffix(mime, "+yaml"), true
}
return false, false
}
func Text(name string, data []byte) bool {
if text, known := ClassifyName(name); known {
return text
}
return len(data) > 0 && !binary(data)
}
func binary(data []byte) bool {
if len(data) == 0 {
return false
+3
View File
@@ -47,7 +47,10 @@ type Branch struct {
Name, Commit string
Readme *string
}
type FileOrigin struct{ Provider, Repository, Commit, Path string }
type Entry struct {
Origin *FileOrigin
Submodule string
Path, Revision string
Size int64
Directory bool
@@ -0,0 +1,10 @@
package provider
import "context"
// SourcePreviews bounds author previews independently of full repository imports.
// Adapters must use the supplied identity and immutable revision.
type SourcePreviews interface {
PreviewTree(context.Context, Access, int) ([]Entry, bool, error)
PreviewFile(context.Context, Access, string, int64) ([]byte, int64, bool, error)
}
+107
View File
@@ -0,0 +1,107 @@
package server
import (
"crypto/subtle"
"regexp"
"strings"
"github.com/tdurieux/anonymous_github/backend/internal/security"
)
var mailboxPattern = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?\\.[a-zA-Z]{2,}$")
func normalizeNotificationEmail(value any) string {
email, ok := value.(string)
if !ok {
return ""
}
email = strings.TrimSpace(email)
if len(email) > 254 || !mailboxPattern.MatchString(email) || strings.Contains(email, "..") {
return ""
}
local := strings.SplitN(email, "@", 2)[0]
if len(local) > 64 || strings.HasPrefix(local, ".") || strings.HasSuffix(local, ".") {
return ""
}
return email
}
func accountNotificationEmail(user M) string {
if email := normalizeNotificationEmail(user["notificationEmail"]); email != "" {
return email
}
for _, entry := range arr(user["emails"]) {
if boolean(obj(entry)["default"]) {
if email := normalizeNotificationEmail(obj(entry)["email"]); email != "" {
return email
}
}
}
for _, entry := range arr(user["emails"]) {
if email := normalizeNotificationEmail(obj(entry)["email"]); email != "" {
return email
}
}
return ""
}
func (q *request) connectionCSRF() error {
if str(q.Session["githubConnectionCSRF"]) == "" {
token, err := security.RandomToken()
if err != nil {
return err
}
q.Session["githubConnectionCSRF"] = token
}
return q.saveSession(false)
}
func (s *Server) accountProfile(q *request) (any, error) {
result := userProfile(q.User)
enabled := s.Config.EmailAPIKey != "" && s.Config.EmailFrom != ""
show := enabled && accountNotificationEmail(q.User) == "" && !boolean(q.User["emailPromptNever"]) && !boolean(q.Session["emailPromptDismissed"])
result["showEmailPrompt"], result["notificationEmail"], result["emailNotificationsEnabled"] = show, accountNotificationEmail(q.User), enabled
if show {
if err := q.connectionCSRF(); err != nil {
return nil, err
}
result["emailPromptCSRF"] = q.Session["githubConnectionCSRF"]
}
q.W.Header().Set("Cache-Control", "no-store")
return result, nil
}
func (s *Server) accountEmail(q *request) (any, error) {
q.W.Header().Set("Cache-Control", "no-store")
if q.R.Method == "GET" {
if err := q.connectionCSRF(); err != nil {
return nil, err
}
return M{"csrf": q.Session["githubConnectionCSRF"], "notificationEmail": accountNotificationEmail(q.User)}, nil
}
csrf := str(q.Session["githubConnectionCSRF"])
if csrf == "" || subtle.ConstantTimeCompare([]byte(csrf), []byte(q.R.Header.Get("X-CSRF-Token"))) != 1 {
return nil, fail("invalid_auth_state", 403)
}
action := str(q.Body["action"])
if action == "" {
action = "save"
}
if action == "later" || action == "never" {
if action == "never" {
if _, err := s.Store.update(q.ctx(), "users", M{"_id": q.User["_id"]}, M{"$set": M{"emailPromptNever": true}}); err != nil {
return nil, err
}
}
q.Session["emailPromptDismissed"] = true
if err := q.saveSession(false); err != nil {
return nil, err
}
return M{"ok": true}, nil
}
if action != "save" {
return nil, fail("Invalid email preference.", 400)
}
email := normalizeNotificationEmail(q.Body["email"])
if email == "" {
return nil, fail("Enter a valid email address.", 400)
}
_, err := s.Store.update(q.ctx(), "users", M{"_id": q.User["_id"]}, M{"$set": M{"notificationEmail": email}})
return M{"notificationEmail": email}, err
}
+2 -2
View File
@@ -27,8 +27,8 @@ func omitEmptyObject(value M, key string) {
func adminUserJSON(user M, repositories []M, now time.Time) M {
// Explicit public metadata prevents legacy token fields and credential
// envelopes from becoming part of this administrator response.
out := selectFields(user, "_id", "__v", "username", "photo", "status", "isAdmin", "emails", "dateOfEntry", "externalIDs", "accessTokenDates", "projectNames", "default")
defaults(out, M{"isAdmin": false, "status": "active", "dateOfEntry": now, "emails": []any{}})
out := selectFields(user, "_id", "__v", "username", "photo", "status", "isAdmin", "emails", "dateOfEntry", "externalIDs", "accessTokenDates", "projectNames", "default", "notificationEmail", "emailPromptNever")
defaults(out, M{"emailPromptNever": false, "isAdmin": false, "status": "active", "dateOfEntry": now, "emails": []any{}})
for _, key := range []string{"externalIDs", "accessTokenDates"} {
omitEmptyObject(out, key)
}
+4
View File
@@ -332,6 +332,10 @@ func (s *Server) oauthCallback(q *request) (any, error) {
if err = s.saveGrant(q, user["_id"], flow.Provider, tokens); err != nil {
return nil, err
}
s.saveRegistrationEmail(q.ctx(), user, str(tokens["access_token"]))
if err = s.resetOwnerAlerts(q.ctx(), user["_id"], "", nil); err != nil {
return nil, err
}
if err = q.login(user); err != nil {
return nil, err
}
+301
View File
@@ -0,0 +1,301 @@
package server
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"regexp"
"sort"
"strings"
"time"
"github.com/google/uuid"
"github.com/tdurieux/anonymous_github/backend/internal/security"
"go.mongodb.org/mongo-driver/v2/bson"
)
var billingDraftPath = regexp.MustCompile(`^/anonymize(?:/[A-Za-z0-9_-]{1,200})?$`)
var billingDraftID = regexp.MustCompile(`^[a-f0-9-]{36}$`)
func (s *Server) billingDraft(q *request, id string) (M, error) {
if !billingDraftID.MatchString(id) {
return nil, fail("billing_draft_not_found", 404)
}
draft, err := s.Store.one(q.ctx(), "billingdrafts", M{"_id": id, "owner": q.Identity.ID, "expiresAt": M{"$gt": time.Now()}})
if err != nil {
return nil, err
}
if draft == nil {
return nil, fail("billing_draft_not_found", 404)
}
return draft, nil
}
func (s *Server) billingAPI(q *request) (any, error) {
q.W.Header().Set("Cache-Control", "no-store")
endpoint := strings.TrimPrefix(q.R.URL.Path, "/api/billing")
if q.R.Method == "GET" {
if strings.HasPrefix(endpoint, "/draft/") {
draft, err := s.billingDraft(q, q.Params["id"])
if err != nil {
return nil, err
}
return M{"id": draft["_id"], "path": draft["path"], "values": draft["values"]}, nil
}
if str(q.Session["billingCSRF"]) == "" {
token, err := security.RandomToken()
if err != nil {
return nil, err
}
q.Session["billingCSRF"] = token
}
if err := q.saveSession(false); err != nil {
return nil, err
}
account, err := s.Store.one(q.ctx(), "billingaccounts", M{"_id": q.Identity.ID})
if err != nil {
return nil, err
}
grants, err := s.Store.list(q.ctx(), "billinggrants", M{"owner": q.Identity.ID}, 0, nil)
if err != nil {
return nil, err
}
displayed, repoRows, purchases := []M{}, []M{}, []M{}
var allowance any
if s.Config.Billing.Enabled {
for _, plan := range s.Config.Billing.Plans {
if plan.PriceID == "" {
continue
}
price, err := s.stripe(q.ctx(), "GET", "/prices/"+segment(plan.PriceID), nil, "")
if err != nil {
return nil, err
}
row := M{"id": plan.ID, "name": plan.Name, "description": plan.Description, "repositories": plan.Repositories, "storage": plan.Storage, "amount": price["unit_amount"], "currency": price["currency"]}
if recurring := obj(price["recurring"]); len(recurring) > 0 {
row["interval"], row["intervalCount"] = recurring["interval"], recurring["interval_count"]
}
displayed = append(displayed, row)
}
repos, err := s.Store.list(q.ctx(), collection("repo"), M{"owner": q.User["_id"], "status": M{"$ne": "removed"}}, 500, bson.D{{Key: "anonymizeDate", Value: -1}})
if err != nil {
return nil, err
}
for _, repo := range repos {
row := selectFields(repo, "repoId", "status")
for _, field := range []string{"expirationMode", "expirationDate"} {
if value, exists := obj(repo["options"])[field]; exists {
row[field] = value
}
}
repoRows = append(repoRows, row)
}
allowance, err = s.billingAllowance(q.ctx(), q.Identity.ID, "", "")
if err != nil {
return nil, err
}
purchases = s.billingPurchases(q, grants)
}
publicGrants := []M{}
for _, grant := range grants {
row := selectFields(grant, "planId", "scope", "status", "until", "cancelAtPeriodEnd")
if boolean(grant["revoked"]) {
row["status"] = "revoked"
}
publicGrants = append(publicGrants, row)
}
return M{"enabled": s.Config.Billing.Enabled, "csrf": q.Session["billingCSRF"], "plans": displayed, "checkoutEnabled": s.Config.Billing.Checkout, "freeExpirationMonths": s.Config.Billing.FreeMonths, "grants": publicGrants, "purchases": purchases, "repositories": repoRows, "portal": str(account["customerId"]) != "", "allowance": allowance}, nil
}
csrf := str(q.Session["billingCSRF"])
if csrf == "" || subtle.ConstantTimeCompare([]byte(csrf), []byte(q.R.Header.Get("X-CSRF-Token"))) != 1 {
return nil, fail("invalid_auth_state", 403)
}
key := "go:billing-rate:" + q.Identity.ID + ":" + time.Now().UTC().Format("200601021504")
count, err := s.Store.Redis.Incr(q.ctx(), key).Result()
if err != nil {
return nil, err
}
if count == 1 {
s.Store.Redis.Expire(q.ctx(), key, 2*time.Minute)
}
if count > 30 {
return nil, fail("rate_limited", 429)
}
if err = s.Config.Billing.require(); err != nil {
return nil, err
}
switch endpoint {
case "/draft":
path, ok := q.Body["path"].(string)
values := obj(q.Body["values"])
raw, _ := json.Marshal(q.Body["values"])
_, validValues := q.Body["values"].(map[string]any)
if _, ok := q.Body["values"].(M); ok {
validValues = true
}
if !ok || !billingDraftPath.MatchString(path) || !validValues || len(raw) > 64*1024 {
return nil, fail("billing_invalid_draft", 400)
}
id := uuid.NewString()
_, err := s.Store.DB.Collection("billingdrafts").InsertOne(q.ctx(), M{"_id": id, "owner": q.Identity.ID, "path": path, "values": selectFields(values, "sourceUrl", "terms", "repoId", "source", "options", "conference", "githubConnection"), "expiresAt": time.Now().Add(7 * 24 * time.Hour)})
return M{"id": id}, err
case "/checkout":
plan, ok := q.Body["planId"].(string)
if !ok {
return nil, fail("invalid_request", 400)
}
target := ""
if q.Body["target"] != nil {
var valid bool
target, valid = q.Body["target"].(string)
if !valid {
return nil, fail("invalid_request", 400)
}
}
returnPath := ""
if q.Body["draftId"] != nil {
draft, err := s.billingDraft(q, str(q.Body["draftId"]))
if err != nil {
return nil, err
}
returnPath = str(draft["path"]) + "?billingDraft=" + str(draft["_id"])
}
address, err := s.createBillingCheckout(q.ctx(), q.Identity.ID, plan, target, returnPath)
return M{"url": address}, err
case "/portal":
account, err := s.Store.one(q.ctx(), "billingaccounts", M{"_id": q.Identity.ID})
if err != nil {
return nil, err
}
if str(account["customerId"]) == "" {
return nil, fail("billing_customer_not_found", 404)
}
portal, err := s.stripe(q.ctx(), "POST", "/billing_portal/sessions", M{"customer": account["customerId"], "return_url": strings.TrimSuffix(s.Config.Billing.Origin, "/") + "/profile?billing=portal"}, "")
return M{"url": portal["url"]}, err
case "/refresh":
account, err := s.Store.one(q.ctx(), "billingaccounts", M{"_id": q.Identity.ID})
if err != nil {
return nil, err
}
checkout := obj(account["checkout"])
pending := str(checkout["key"]) != "" && str(checkout["id"]) == ""
if id := str(checkout["id"]); id != "" {
if err = s.fulfillBillingCheckout(q.ctx(), id); err != nil {
return nil, err
}
session, err := s.stripe(q.ctx(), "GET", "/checkout/sessions/"+segment(id), nil, "")
if err != nil {
return nil, err
}
pending = session["status"] != "expired" && session["payment_status"] == "unpaid"
}
grants, err := s.Store.list(q.ctx(), "billinggrants", M{"owner": q.Identity.ID, "subscriptionId": M{"$exists": true}}, 0, nil)
if err != nil {
return nil, err
}
for _, grant := range grants {
if err = s.syncBillingSubscription(q.ctx(), str(grant["subscriptionId"])); err != nil {
return nil, err
}
}
return M{"ok": true, "pending": pending}, nil
}
return nil, fail("not_found", 404)
}
func (s *Server) billingPurchases(q *request, grants []M) []M {
state := func(g M) string {
if boolean(g["revoked"]) {
if g["revocationReason"] == "dispute" {
return "disputed"
}
return "refunded"
}
if g["status"] == "past_due" {
return "overdue"
}
if usableBillingGrant(g, time.Now()) {
return "active"
}
return "ended"
}
until := func(g M) any {
value := date(g["until"])
if value.IsZero() || !value.Before(billingNeverUntil) {
return nil
}
return value
}
groups := map[string][]M{}
keys := []string{}
for _, grant := range grants {
id := str(grant["_id"])
key := id
parts := strings.SplitN(id, ":", 2)
if len(parts) == 2 && billingPackPart.MatchString(id) {
count := 0
for _, other := range grants {
if strings.HasPrefix(str(other["_id"]), parts[0]+":") {
count++
}
}
if count == len(billingPack) {
key = parts[0]
}
}
if _, ok := groups[key]; !ok {
keys = append(keys, key)
}
groups[key] = append(groups[key], grant)
}
out := []M{}
for _, key := range keys {
rows := groups[key]
first := rows[0]
pack := len(rows) > 1
planID := str(first["planId"])
if pack {
planID = "repo_pack"
}
hash := sha256.Sum256([]byte(key))
scope := strings.SplitN(str(first["scope"]), ":", 2)
row := M{"id": hex.EncodeToString(hash[:])[:12], "planId": planID, "recurring": first["planId"] == "author_monthly" || first["planId"] == "author_annual", "repoId": nil, "conference": nil, "status": "ended", "until": until(first), "purchasedAt": first["purchasedAt"], "cancelAtPeriodEnd": boolean(first["cancelAtPeriodEnd"]), "amount": nil, "currency": nil, "interval": nil, "parts": []M{}}
if len(scope) == 2 {
if scope[0] == "repo" {
row["repoId"] = scope[1]
}
if scope[0] == "conference" {
row["conference"] = scope[1]
}
}
priorities := map[string]int{"ended": 0, "active": 1, "overdue": 2, "refunded": 3, "disputed": 4}
parts := []M{}
for _, grant := range rows {
status := state(grant)
if priorities[status] > priorities[str(row["status"])] {
row["status"] = status
}
if pack {
parts = append(parts, M{"planId": grant["planId"], "until": until(grant), "status": status})
}
}
if pack {
row["until"] = nil
row["parts"] = parts
}
if price := str(first["priceId"]); price != "" {
value, err := s.stripe(q.ctx(), "GET", "/prices/"+segment(price), nil, "")
if err == nil {
row["amount"], row["currency"], row["interval"] = value["unit_amount"], value["currency"], obj(value["recurring"])["interval"]
}
}
out = append(out, row)
}
sort.SliceStable(out, func(i, j int) bool {
active := func(row M) bool { return row["status"] == "active" || row["status"] == "overdue" }
if active(out[i]) != active(out[j]) {
return active(out[i])
}
return date(out[i]["purchasedAt"]).After(date(out[j]["purchasedAt"]))
})
return out
}
+243
View File
@@ -0,0 +1,243 @@
package server
import (
"context"
"net/url"
"regexp"
"strings"
"time"
"github.com/google/uuid"
)
var billingRepoID = regexp.MustCompile(`^[0-9a-zA-Z_-]{3,200}$`)
var billingDraftReturn = regexp.MustCompile(`^/anonymize(?:/[A-Za-z0-9_-]{1,200})?\?billingDraft=[a-f0-9-]{36}$`)
func (s *Server) createBillingCheckout(ctx context.Context, owner, planID, target, returnPath string) (string, error) {
if err := s.Config.Billing.require(); err != nil {
return "", err
}
if !s.Config.Billing.Checkout {
return "", fail("billing_checkout_disabled", 503)
}
plan := s.Config.Billing.plan(planID)
if plan == nil || plan.PriceID == "" {
return "", fail("billing_plan_unavailable", 400)
}
if conferencePlan(planID) {
oid, err := oid(owner)
if err != nil {
return "", err
}
conference, err := s.Store.one(ctx, "conferences", M{"conferenceID": target, "owners": oid})
if err != nil {
return "", err
}
if conference == nil || obj(conference["plan"])["planID"] != planID || conference["status"] != "pending_payment" {
return "", fail("billing_invalid_conference", 400)
}
if !date(conference["endDate"]).After(time.Now()) || date(conference["endDate"]).Sub(date(conference["startDate"])) > 180*24*time.Hour {
return "", fail("billing_invalid_review_window", 400)
}
} else if !plan.Recurring {
if !billingRepoID.MatchString(target) {
return "", fail("repo_not_found", 404)
}
repo, err := s.Store.one(ctx, collection("repo"), M{"repoId": target})
if err != nil {
return "", err
}
if repo != nil {
if str(repo["owner"]) != owner || repo["status"] == "removed" {
return "", fail("repo_not_found", 404)
}
target = str(repo["repoId"])
}
} else {
target = ""
}
destination := "/profile"
if conferencePlan(planID) {
destination = "/conference/" + url.PathEscape(target)
}
if returnPath != "" {
if !billingDraftReturn.MatchString(returnPath) {
return "", fail("billing_invalid_draft", 400)
}
destination = returnPath
}
outcome := func(value string) string {
separator := "?"
if strings.Contains(destination, "?") {
separator = "&"
}
return strings.TrimSuffix(s.Config.Billing.Origin, "/") + destination + separator + "billing=" + value
}
result := ""
err := s.billingLock(ctx, "checkout:"+owner, func(work context.Context) error {
if err := s.billingUpsert(work, "billingaccounts", M{"_id": owner}, M{"$setOnInsert": M{"reconcileAfter": time.Unix(0, 0)}}); err != nil {
return err
}
account, err := s.Store.one(work, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
save := func(values M) error {
_, e := s.Store.update(work, "billingaccounts", M{"_id": owner}, M{"$set": values})
return e
}
if str(account["customerId"]) == "" {
attempted := date(account["customerAttemptAt"])
if !attempted.IsZero() && time.Since(attempted) >= 23*time.Hour {
return fail("billing_recovery_required", 409)
}
if attempted.IsZero() {
if err = save(M{"customerAttemptAt": time.Now()}); err != nil {
return err
}
}
customer, e := s.stripe(work, "POST", "/customers", M{"metadata": M{"application": "anonymous-github", "owner": owner}}, "customer:"+owner)
if e != nil {
return e
}
if str(customer["id"]) == "" {
return fail("billing_provider_invalid_response", 502)
}
account["customerId"] = customer["id"]
if err = save(M{"customerId": customer["id"]}); err != nil {
return err
}
}
checkout := obj(account["checkout"])
if str(checkout["key"]) != "" && str(checkout["id"]) == "" && (date(checkout["createdAt"]).IsZero() || time.Since(date(checkout["createdAt"])) >= 23*time.Hour) {
err = s.stripeEach(work, "/checkout/sessions", M{"customer": account["customerId"]}, func(row M) error {
meta := obj(row["metadata"])
if meta["attempt"] == checkout["key"] && meta["owner"] == owner {
checkout["id"] = row["id"]
return errBillingStop
}
return nil
})
if err != nil && err != errBillingStop {
return err
}
if str(checkout["id"]) != "" {
if err = save(M{"checkout": checkout}); err != nil {
return err
}
} else {
expiry := number(obj(checkout["params"])["expires_at"])
if expiry > 0 && !date(checkout["createdAt"]).IsZero() && time.Since(date(checkout["createdAt"])) > 24*time.Hour && expiry < time.Now().Unix() {
checkout = M{}
if _, err = s.Store.update(work, "billingaccounts", M{"_id": owner}, M{"$unset": M{"checkout": 1}}); err != nil {
return err
}
} else {
return fail("billing_recovery_required", 409)
}
}
}
params := obj(checkout["params"])
if str(params["success_url"]) != "" && str(checkout["id"]) == "" && params["success_url"] != outcome("success") {
return fail("billing_checkout_in_progress", 409)
}
if id := str(checkout["id"]); id != "" {
existing, e := s.stripe(work, "GET", "/checkout/sessions/"+segment(id), nil, "")
if e != nil {
return e
}
if existing["status"] == "open" {
if checkout["planId"] != planID || checkout["target"] != target || (str(params["success_url"]) != "" && params["success_url"] != outcome("success")) {
return fail("billing_checkout_in_progress", 409)
}
result = str(existing["url"])
return nil
}
if existing["status"] == "complete" {
if e = s.fulfillBillingCheckout(work, id); e != nil {
return e
}
}
}
price, err := s.stripe(work, "GET", "/prices/"+segment(plan.PriceID), nil, "")
if err != nil {
return err
}
interval := "year"
if planID == "author_monthly" {
interval = "month"
}
recurring := obj(price["recurring"])
if !boolean(price["active"]) || price["currency"] != "eur" || number(price["unit_amount"]) <= 0 || (plan.Recurring && (recurring["interval"] != interval || number(recurring["interval_count"]) != 1)) || (!plan.Recurring && len(recurring) > 0) {
return fail("billing_price_misconfigured", 503)
}
if plan.Recurring {
err = s.stripeEach(work, "/subscriptions", M{"customer": account["customerId"], "status": "all"}, func(sub M) error {
if sub["status"] != "canceled" && sub["status"] != "incomplete_expired" {
return fail("billing_subscription_exists", 409)
}
return nil
})
if err != nil {
return err
}
} else if conferencePlan(planID) || (planID != "repo_extend" && planID != "repo_pack") {
filter := M{"scope": "repo:" + target, "owner": owner, "planId": planID, "revoked": false, "until": M{"$gt": time.Now()}}
if conferencePlan(planID) {
filter = M{"scope": "conference:" + target, "revoked": false, "until": M{"$gt": time.Now()}}
}
grant, e := s.Store.one(work, "billinggrants", filter)
if e != nil {
return e
}
if grant != nil {
return fail("billing_already_paid", 409)
}
}
if str(checkout["key"]) == "" || str(checkout["id"]) != "" {
checkout = M{"key": uuid.NewString(), "planId": planID, "target": target, "createdAt": time.Now(), "expiresAt": time.Now().Add(1860 * time.Second)}
if err = save(M{"checkout": checkout}); err != nil {
return err
}
}
if checkout["planId"] != planID || checkout["target"] != target {
return fail("billing_checkout_in_progress", 409)
}
params = obj(checkout["params"])
if len(params) == 0 {
metadata := M{"application": "anonymous-github", "owner": owner, "planId": planID, "target": target, "attempt": checkout["key"]}
params = M{"customer": account["customerId"], "expires_at": time.Now().Unix() + 1860, "mode": "payment", "line_items": []M{{"price": plan.PriceID, "quantity": 1}}, "allowed_payment_method_types": []string{"card"}, "metadata": metadata, "billing_address_collection": "required", "tax_id_collection": M{"enabled": true}, "customer_update": M{"address": "auto", "name": "auto"}, "automatic_tax": M{"enabled": s.Config.Billing.AutomaticTax}, "success_url": outcome("success"), "cancel_url": outcome("cancelled")}
if plan.Recurring {
params["mode"] = "subscription"
params["subscription_data"] = M{"metadata": metadata}
} else {
params["payment_intent_data"] = M{"metadata": metadata}
params["invoice_creation"] = M{"enabled": true}
}
checkout["params"] = params
if err = save(M{"checkout": checkout}); err != nil {
return err
}
}
lines := arr(params["line_items"])
if len(lines) > 0 {
if err = s.billingUpsert(work, "billingprices", M{"_id": obj(lines[0])["price"]}, M{"$setOnInsert": M{"planId": planID}}); err != nil {
return err
}
}
session, err := s.stripe(work, "POST", "/checkout/sessions", params, str(checkout["key"]))
if err != nil {
return err
}
if str(session["id"]) == "" || str(session["url"]) == "" {
return fail("billing_provider_invalid_response", 502)
}
checkout["id"] = session["id"]
if err = save(M{"checkout": checkout}); err != nil {
return err
}
result = str(session["url"])
return nil
})
return result, err
}
+237
View File
@@ -0,0 +1,237 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func stripeRef(value any) string {
if s, ok := value.(string); ok {
return s
}
return str(obj(value)["id"])
}
func stripeValues(values M) url.Values {
out := url.Values{}
var add func(string, any)
add = func(key string, value any) {
switch v := value.(type) {
case M:
for k, x := range v {
add(key+"["+k+"]", x)
}
case map[string]any:
for k, x := range v {
add(key+"["+k+"]", x)
}
case bson.D:
for _, field := range v {
add(key+"["+field.Key+"]", field.Value)
}
case bson.A:
for i, x := range v {
add(key+"["+strconv.Itoa(i)+"]", x)
}
case []any:
for i, x := range v {
add(key+"["+strconv.Itoa(i)+"]", x)
}
case []M:
for i, x := range v {
add(key+"["+strconv.Itoa(i)+"]", x)
}
case []string:
for i, x := range v {
add(key+"["+strconv.Itoa(i)+"]", x)
}
case nil:
out.Set(key, "")
default:
out.Set(key, fmt.Sprint(v))
}
}
for key, value := range values {
add(key, value)
}
return out
}
func (s *Server) stripe(ctx context.Context, method, path string, params M, idempotency string) (M, error) {
if err := s.Config.Billing.require(); err != nil {
return nil, err
}
if !strings.HasPrefix(path, "/") || strings.ContainsAny(path, "?#\\") {
return nil, fail("billing_invalid_request", 500)
}
encoded := stripeValues(params).Encode()
address := "https://api.stripe.com/v1" + path
var body io.Reader
if method == "GET" {
if encoded != "" {
address += "?" + encoded
}
} else {
body = strings.NewReader(encoded)
}
work, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(work, method, address, body)
if err != nil {
return nil, err
}
request.Header.Set("Authorization", "Bearer "+s.Config.Billing.Secret)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.Header.Set("Stripe-Version", "2026-10-28.endive")
if idempotency != "" {
request.Header.Set("Idempotency-Key", idempotency)
}
client := *s.HTTP
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
response, err := client.Do(request)
if err != nil {
return nil, fail("billing_provider_unavailable", 502)
}
defer response.Body.Close()
raw, err := io.ReadAll(io.LimitReader(response.Body, 4*1024*1024+1))
if err != nil || len(raw) > 4*1024*1024 {
return nil, fail("billing_provider_unavailable", 502)
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return nil, fail("billing_provider_failed", 502)
}
var result M
if json.Unmarshal(raw, &result) != nil {
return nil, fail("billing_provider_invalid_response", 502)
}
return result, nil
}
func (s *Server) stripeEach(ctx context.Context, path string, params M, visit func(M) error) error {
if params == nil {
params = M{}
}
copied := M{}
for k, v := range params {
copied[k] = v
}
params = copied
params["limit"] = 100
seen := map[string]bool{}
for page := 0; page < 10000; page++ {
response, err := s.stripe(ctx, "GET", path, params, "")
if err != nil {
return err
}
rows := arr(response["data"])
for _, row := range rows {
if err := visit(obj(row)); err != nil {
return err
}
}
if !boolean(response["has_more"]) {
return nil
}
if len(rows) == 0 {
return fail("billing_provider_invalid_response", 502)
}
after := str(obj(rows[len(rows)-1])["id"])
if after == "" || seen[after] {
return fail("billing_provider_invalid_response", 502)
}
seen[after] = true
params["starting_after"] = after
}
return fail("billing_provider_page_limit", 502)
}
func (s *Server) billingUpsert(ctx context.Context, collection string, filter, update M) error {
_, err := s.Store.DB.Collection(collection).UpdateOne(ctx, filter, update, options.UpdateOne().SetUpsert(true))
return err
}
func (s *Server) billingLock(ctx context.Context, id string, work func(context.Context) error) error {
token := uuid.NewString()
now := time.Now()
if err := s.billingUpsert(ctx, "billinglocks", M{"_id": id, "until": M{"$lt": now}}, M{"$set": M{"token": token, "until": now.Add(3 * time.Minute)}}); err != nil {
if mongo.IsDuplicateKeyError(err) {
return fail("billing_busy", 409)
}
return err
}
lockCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
defer close(done)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-lockCtx.Done():
return
case <-ticker.C:
result, err := s.Store.DB.Collection("billinglocks").UpdateOne(lockCtx, M{"_id": id, "token": token}, M{"$set": M{"until": time.Now().Add(3 * time.Minute)}})
if err != nil || result.MatchedCount != 1 {
cancel()
return
}
}
}
}()
defer func() {
cancel()
<-done
cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer stop()
s.Store.DB.Collection("billinglocks").DeleteOne(cleanup, M{"_id": id, "token": token})
}()
return work(lockCtx)
}
func (s *Server) billingPlanForPrice(ctx context.Context, id string, recurring bool) (*BillingPlan, error) {
if id == "" {
return nil, nil
}
for _, plan := range s.Config.Billing.Plans {
if plan.Recurring == recurring && plan.PriceID == id {
return &plan, nil
}
}
planID := s.Config.Billing.LegacyPrices[id]
if planID == "" {
row, err := s.Store.one(ctx, "billingprices", M{"_id": id})
if err != nil {
return nil, err
}
planID = str(row["planId"])
}
plan := s.Config.Billing.plan(planID)
if plan == nil || plan.Recurring != recurring {
return nil, nil
}
return plan, nil
}
func (s *Server) rememberBillingPrices(ctx context.Context) error {
for _, p := range s.Config.Billing.Plans {
if p.PriceID != "" {
if err := s.billingUpsert(ctx, "billingprices", M{"_id": p.PriceID}, M{"$setOnInsert": M{"planId": p.ID}}); err != nil {
return err
}
}
}
for price, plan := range s.Config.Billing.LegacyPrices {
if err := s.billingUpsert(ctx, "billingprices", M{"_id": price}, M{"$setOnInsert": M{"planId": plan}}); err != nil {
return err
}
}
return nil
}
var errBillingStop = errors.New("billing_stop_iteration")
+107
View File
@@ -0,0 +1,107 @@
package server
import (
_ "embed"
"encoding/json"
"errors"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type BillingConfig struct {
Enabled, Checkout, AutomaticTax bool
Origin, Secret, WebhookSecret string
FreeMonths, FreeRepositories int64
FreeStorage int64
Plans []BillingPlan
LegacyPrices map[string]string
}
type BillingPlan struct {
ID, Name, PriceID, Description string
Recurring, Capacity bool
Repositories, Storage int64
}
//go:embed billing_plans.json
var billingPlanDefinitions []byte
var billingNeverUntil = time.Date(9999, 12, 31, 0, 0, 0, 0, time.UTC)
var billingPack = []string{"repo_slot", "author_pass", "repo_extend"}
func conferencePlan(id string) bool {
return id == "conference" || id == "conference_workshop" || id == "conference_large"
}
func (c BillingConfig) plan(id string) *BillingPlan {
for _, p := range c.Plans {
if p.ID == id {
return &p
}
}
return nil
}
func loadBillingConfig() (BillingConfig, error) {
c := BillingConfig{Enabled: envBool("BILLING_ENABLED", false), Checkout: envBool("BILLING_CHECKOUT_ENABLED", true), AutomaticTax: envBool("BILLING_AUTOMATIC_TAX", false), Origin: env("BILLING_ORIGIN", "http://localhost:5000"), Secret: os.Getenv("STRIPE_SECRET_KEY"), WebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"), FreeMonths: int64(envInt("FREE_EXPIRATION_MONTHS", 5)), FreeRepositories: int64(envInt("FREE_AUTHOR_REPOSITORIES", 5)), FreeStorage: int64(envInt("FREE_AUTHOR_STORAGE", 2<<30)), LegacyPrices: map[string]string{}}
defaults := map[string]int{"PAID_AUTHOR_REPOSITORIES": 20, "PAID_AUTHOR_STORAGE": 10 << 30, "PAID_PASS_STORAGE": 2 << 30, "PAID_CONFERENCE_REPOSITORIES": 100, "PAID_CONFERENCE_STORAGE": 50 << 30, "PAID_CONFERENCE_SMALL_REPOSITORIES": 25, "PAID_CONFERENCE_SMALL_STORAGE": 10 << 30, "PAID_CONFERENCE_LARGE_REPOSITORIES": 400, "PAID_CONFERENCE_LARGE_STORAGE": 200 << 30}
if c.Enabled {
for _, key := range append([]string{"FREE_EXPIRATION_MONTHS", "FREE_AUTHOR_REPOSITORIES", "FREE_AUTHOR_STORAGE"}, billingCapacityKeys(defaults)...) {
if raw, ok := os.LookupEnv(key); ok {
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n <= 0 || n > 9007199254740991 {
return c, errors.New("invalid_" + key)
}
}
}
}
var rows []M
if err := json.Unmarshal(billingPlanDefinitions, &rows); err != nil {
return c, err
}
for _, row := range rows {
capacity := func(key string) int64 {
if name, ok := row[key].(string); ok {
return int64(envInt(name, defaults[name]))
}
return number(row[key])
}
c.Plans = append(c.Plans, BillingPlan{ID: str(row["id"]), Name: str(row["name"]), PriceID: os.Getenv(str(row["priceId"])), Description: str(row["description"]), Recurring: boolean(row["recurring"]), Capacity: boolean(row["capacity"]), Repositories: capacity("repositories"), Storage: capacity("storage")})
}
for _, entry := range strings.Split(os.Getenv("STRIPE_LEGACY_PRICES"), ",") {
if strings.TrimSpace(entry) == "" {
continue
}
p := strings.Split(entry, ":")
if len(p) != 2 || c.plan(strings.TrimSpace(p[1])) == nil || !strings.HasPrefix(strings.TrimSpace(p[0]), "price_") {
return c, errors.New("invalid_STRIPE_LEGACY_PRICES")
}
c.LegacyPrices[strings.TrimSpace(p[0])] = strings.TrimSpace(p[1])
}
if c.Enabled {
if err := c.require(); err != nil {
return c, err
}
}
return c, nil
}
func (c BillingConfig) require() error {
if !c.Enabled || c.Secret == "" || c.WebhookSecret == "" {
return fail("billing_unavailable", 503)
}
u, err := url.Parse(c.Origin)
if err != nil || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
return fail("billing_origin_invalid", 503)
}
return nil
}
func usableBillingGrant(g M, now time.Time) bool {
return !boolean(g["revoked"]) && date(g["until"]).After(now) && (g["status"] == "active" || g["status"] == "past_due" || g["status"] == "paid")
}
func billingCapacityKeys(values map[string]int) []string {
out := []string{}
for key := range values {
out = append(out, key)
}
return out
}
@@ -0,0 +1,51 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
)
func (s *Server) reserveBillingExpansion(ctx context.Context, repoID, key string, bytes int64) error {
if !s.Config.Billing.Enabled || bytes <= 0 || repoID == "" {
return nil
}
repo, err := s.Store.one(ctx, collection("repo"), M{"repoId": repoID})
if err != nil {
return err
}
if !boolean(repo["billingManaged"]) {
return nil
}
digest := sha256.Sum256([]byte(key))
key = hex.EncodeToString(digest[:])
return s.reserveBillingRepository(ctx, str(repo["owner"]), str(repo["repoId"]), 0, str(repo["conference"]), key, bytes)
}
type billingContentReader struct {
io.ReadCloser
s *Server
ctx context.Context
repoID, key string
expected, read, charged int64
failed error
}
func (r *billingContentReader) Read(p []byte) (int, error) {
if r.failed != nil {
return 0, r.failed
}
n, err := r.ReadCloser.Read(p)
r.read += int64(n)
if extra := r.read - r.expected; extra > 0 && (extra > r.charged || err == io.EOF) {
reserve := extra
if e := r.s.reserveBillingExpansion(r.ctx, r.repoID, r.key, reserve); e != nil {
r.failed = e
return 0, e
}
r.charged = reserve
}
return n, err
}
+194
View File
@@ -0,0 +1,194 @@
package server
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func stripeSignature(body []byte, header, secret string, now time.Time) bool {
timestamp := ""
signatures := []string{}
for _, part := range strings.Split(header, ",") {
kv := strings.SplitN(part, "=", 2)
if len(kv) != 2 {
continue
}
if kv[0] == "t" {
timestamp = kv[1]
}
if kv[0] == "v1" {
signatures = append(signatures, kv[1])
}
}
seconds, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil || secret == "" || seconds < now.Add(-5*time.Minute).Unix() || seconds > now.Add(5*time.Minute).Unix() {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp + "."))
mac.Write(body)
expected := mac.Sum(nil)
for _, signature := range signatures {
decoded, err := hex.DecodeString(signature)
if err == nil && hmac.Equal(decoded, expected) {
return true
}
}
return false
}
func (s *Server) billingWebhook(q *request) (any, error) {
if !s.Config.Billing.Enabled {
return nil, fail("not_found", 404)
}
if q.R.Method != "POST" {
return nil, fail("not_found", 404)
}
raw, err := io.ReadAll(http.MaxBytesReader(q.W, q.R.Body, 256*1024))
if err != nil || !stripeSignature(raw, q.R.Header.Get("Stripe-Signature"), s.Config.Billing.WebhookSecret, time.Now()) {
return nil, fail("invalid_billing_signature", 400)
}
var event M
if json.Unmarshal(raw, &event) != nil || str(event["id"]) == "" {
return nil, fail("invalid_billing_signature", 400)
}
live := strings.HasPrefix(s.Config.Billing.Secret, "sk_live_") || strings.HasPrefix(s.Config.Billing.Secret, "rk_live_")
if str(event["account"]) != "" {
return nil, fail("billing_environment_mismatch", 400)
}
if flag, ok := event["livemode"].(bool); ok && flag != live {
return nil, fail("billing_environment_mismatch", 400)
}
value := obj(obj(event["data"])["object"])
sanitized := selectFields(value, "id", "amount", "amount_refunded", "refunded", "disputed")
sanitized["payment_intent"], sanitized["charge"] = stripeRef(value["payment_intent"]), stripeRef(value["charge"])
sanitized["parent"] = M{"subscription_details": M{"subscription": stripeRef(obj(obj(value["parent"])["subscription_details"])["subscription"])}}
namespace := "test"
if boolean(event["livemode"]) {
namespace = "live"
}
err = s.billingUpsert(q.ctx(), "billingevents", M{"_id": namespace + ":platform:" + str(event["id"])}, M{"$setOnInsert": M{"eventId": event["id"], "type": event["type"], "object": sanitized, "state": "pending", "attempts": 0, "receivedAt": time.Now(), "nextAttemptAt": time.Now()}})
if err != nil {
return nil, fail("billing_webhook_failed", 500)
}
return M{"received": true}, nil
}
func (s *Server) processBillingEvent(ctx context.Context, event M) error {
kind := str(event["type"])
value := obj(event["object"])
if kind == "checkout.session.completed" || kind == "checkout.session.async_payment_succeeded" {
return s.fulfillBillingCheckout(ctx, str(value["id"]))
}
if strings.HasPrefix(kind, "customer.subscription.") {
return s.syncBillingSubscription(ctx, str(value["id"]))
}
if kind == "invoice.paid" || kind == "invoice.payment_failed" {
id := stripeRef(obj(obj(value["parent"])["subscription_details"])["subscription"])
if id != "" {
return s.syncBillingSubscription(ctx, id)
}
return nil
}
if kind != "charge.refunded" && kind != "charge.dispute.created" {
return nil
}
charge := value
if kind == "charge.dispute.created" {
var err error
charge, err = s.stripe(ctx, "GET", "/charges/"+segment(stripeRef(value["charge"])), nil, "")
if err != nil {
return err
}
}
if kind == "charge.refunded" && charge["refunded"] == false {
return nil
}
intent := stripeRef(charge["payment_intent"])
if intent == "" {
return nil
}
reason := "full_refund"
if kind == "charge.dispute.created" || boolean(charge["disputed"]) {
reason = "dispute"
}
if err := s.billingUpsert(ctx, "billingrevocations", M{"_id": intent}, M{"$setOnInsert": M{"reason": reason, "reviewed": false, "createdAt": time.Now()}}); err != nil {
return err
}
if reason == "dispute" {
if _, err := s.Store.update(ctx, "billingrevocations", M{"_id": intent, "reason": "full_refund"}, M{"$set": M{"reason": reason, "reviewed": false}}); err != nil {
return err
}
}
reversal, err := s.Store.one(ctx, "billingrevocations", M{"_id": intent})
if err != nil {
return err
}
if boolean(reversal["reviewed"]) {
return nil
}
revoked := M{"revoked": true, "revocationReason": reason, "revokedAt": time.Now()}
if _, err = s.Store.DB.Collection("billinggrants").UpdateMany(ctx, M{"paymentIntentId": intent}, M{"$set": revoked, "$inc": M{"revision": 1}}); err != nil {
return err
}
return s.stripeEach(ctx, "/invoice_payments", M{"payment": M{"type": "payment_intent", "payment_intent": intent}}, func(payment M) error {
invoice, err := s.stripe(ctx, "GET", "/invoices/"+segment(stripeRef(payment["invoice"])), nil, "")
if err != nil {
return err
}
subscription := stripeRef(obj(obj(invoice["parent"])["subscription_details"])["subscription"])
if subscription == "" {
return nil
}
if _, err = s.Store.update(ctx, "billingrevocations", M{"_id": intent}, M{"$set": M{"subscriptionId": subscription}}); err != nil {
return err
}
return s.billingUpsert(ctx, "billinggrants", M{"_id": subscription}, M{"$set": revoked, "$inc": M{"revision": 1}})
})
}
func (s *Server) processBillingInbox(ctx context.Context) error {
namespace := "^test:platform:"
if strings.HasPrefix(s.Config.Billing.Secret, "sk_live_") || strings.HasPrefix(s.Config.Billing.Secret, "rk_live_") {
namespace = "^live:platform:"
}
for i := 0; i < 25; i++ {
now, token := time.Now(), uuid.NewString()
var event M
err := s.Store.DB.Collection("billingevents").FindOneAndUpdate(ctx, M{"_id": M{"$regex": namespace}, "$or": []M{{"state": "pending", "nextAttemptAt": M{"$lte": now}}, {"state": "processing", "leaseUntil": M{"$lte": now}}}}, M{"$set": M{"state": "processing", "token": token, "leaseUntil": now.Add(5 * time.Minute)}, "$inc": M{"attempts": 1}}, options.FindOneAndUpdate().SetSort(bson.D{{Key: "receivedAt", Value: 1}}).SetReturnDocument(options.After)).Decode(&event)
if errors.Is(err, mongo.ErrNoDocuments) {
return nil
}
if err != nil {
return err
}
work, cancel := context.WithTimeout(ctx, 4*time.Minute)
failure := s.processBillingEvent(work, event)
cancel()
update := M{"$set": M{"state": "complete", "completedAt": time.Now()}, "$unset": M{"token": 1, "leaseUntil": 1, "lastError": 1}}
if failure != nil {
state := "pending"
attempts := number(event["attempts"])
if attempts >= 12 {
state = "failed"
}
delay := min(time.Hour, time.Second*time.Duration(1<<min(attempts, 20)))
update = M{"$set": M{"state": state, "lastError": "billing_processing_failed", "nextAttemptAt": time.Now().Add(delay)}, "$unset": M{"token": 1, "leaseUntil": 1}}
}
if _, err = s.Store.update(ctx, "billingevents", M{"_id": event["_id"], "token": token}, update); err != nil {
return err
}
}
return nil
}
@@ -0,0 +1,101 @@
package server
import (
"context"
"time"
)
func billingMonthLimit(now time.Time, months int) time.Time {
next := now.In(time.Local).AddDate(0, months, 0)
return time.Date(next.Year(), next.Month(), next.Day(), 23, 59, 59, 999000000, next.Location())
}
func (s *Server) billingMaximumExpiration(ctx context.Context, owner, repoID, conference string, now time.Time) (time.Time, error) {
if !s.Config.Billing.Enabled {
return billingMonthLimit(now, 12), nil
}
maximum := billingMonthLimit(now, int(s.Config.Billing.FreeMonths))
if conference != "" {
row, err := s.Store.one(ctx, "conferences", M{"conferenceID": conference})
if err != nil {
return time.Time{}, err
}
if end := date(row["endDate"]); end.After(maximum) {
maximum = end
}
}
grants, err := s.Store.list(ctx, "billinggrants", M{"$or": []M{{"scope": "user:" + owner, "planId": M{"$in": []string{"author_monthly", "author_annual"}}}, {"scope": "repo:" + repoID, "owner": owner, "planId": "repo_extend"}}}, 0, nil)
if err != nil {
return time.Time{}, err
}
for _, grant := range grants {
if !usableBillingGrant(grant, now) {
continue
}
limit := billingMonthLimit(now, 12)
if grant["planId"] == "repo_extend" {
until := date(grant["until"]).In(time.Local)
limit = time.Date(until.Year(), until.Month(), until.Day(), 23, 59, 59, 999000000, until.Location())
}
if limit.After(maximum) {
maximum = limit
}
}
return maximum, nil
}
func (s *Server) billingNeverDeadline(ctx context.Context, owner, repoID string, existing time.Time) (time.Time, error) {
if !s.Config.Billing.Enabled {
return time.Time{}, nil
}
now := time.Now()
grants, err := s.Store.list(ctx, "billinggrants", M{"$or": []M{{"scope": "user:" + owner, "planId": M{"$in": []string{"author_monthly", "author_annual"}}}, {"scope": "repo:" + repoID, "owner": owner, "planId": "repo_never"}}}, 0, nil)
if err != nil {
return time.Time{}, err
}
deadline := existing
for _, grant := range grants {
if !usableBillingGrant(grant, now) {
continue
}
until := date(grant["until"])
if grant["planId"] == "repo_never" {
until = now
}
until = until.Add(90 * 24 * time.Hour)
if until.After(deadline) {
deadline = until
}
}
if !deadline.After(now) {
return time.Time{}, fail("subscription_required_for_never_expiration", 402)
}
return deadline, nil
}
func (s *Server) billingResourceSettings(ctx context.Context, owner, repoID, conference string, opt, previous M) (M, error) {
set := M{}
if !s.Config.Billing.Enabled {
return set, nil
}
if opt["expirationMode"] == "never" {
existing := time.Time{}
if obj(previous["options"])["expirationMode"] == "never" {
existing = date(previous["billingNeverExpiresUntil"])
}
deadline, err := s.billingNeverDeadline(ctx, owner, repoID, existing)
if err != nil {
return nil, err
}
set["billingNeverExpiresUntil"] = deadline
} else {
maximum, err := s.billingMaximumExpiration(ctx, owner, repoID, conference, time.Now())
if err != nil {
return nil, err
}
value := date(opt["expirationDate"])
unchanged := value.Equal(date(obj(previous["options"])["expirationDate"]))
if (opt["expirationMode"] != "remove" && opt["expirationMode"] != "redirect") || value.IsZero() || (value.After(maximum) && !unchanged) {
return nil, fail("invalid_billing_expiration", 400)
}
}
set["billingManaged"] = true
return set, nil
}
+253
View File
@@ -0,0 +1,253 @@
package server
import (
"context"
"time"
"go.mongodb.org/mongo-driver/v2/mongo"
)
func (s *Server) syncBillingSubscription(ctx context.Context, id string) error {
for retry := 0; retry < 4; retry++ {
previous, err := s.Store.one(ctx, "billinggrants", M{"_id": id})
if err != nil {
return err
}
sub, err := s.stripe(ctx, "GET", "/subscriptions/"+segment(id), M{"expand": []string{"latest_invoice"}}, "")
if err != nil {
return err
}
metadata := obj(sub["metadata"])
owner := str(metadata["owner"])
if owner == "" || metadata["application"] != "anonymous-github" {
return nil
}
account, err := s.Store.one(ctx, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
if account == nil || account["customerId"] != stripeRef(sub["customer"]) {
return fail("billing_customer_mismatch", 400)
}
items := arr(obj(sub["items"])["data"])
item := M{}
if len(items) > 0 {
item = obj(items[0])
}
price := stripeRef(item["price"])
plan, err := s.billingPlanForPrice(ctx, price, true)
if err != nil {
return err
}
invoice := obj(sub["latest_invoice"])
paid := plan != nil && len(items) == 1 && sub["status"] == "active" && invoice["status"] == "paid"
paidThrough := date(previous["until"])
if paidThrough.IsZero() {
paidThrough = time.Unix(0, 0)
}
if paid && number(item["current_period_end"]) > 0 {
paidThrough = time.Unix(number(item["current_period_end"]), 0)
}
if !paid && plan != nil && len(items) == 1 {
err = s.stripeEach(ctx, "/invoices", M{"subscription": id, "status": "paid"}, func(invoice M) error {
return s.stripeEach(ctx, "/invoices/"+segment(str(invoice["id"]))+"/lines", nil, func(line M) error {
details := obj(obj(line["parent"])["subscription_item_details"])
end := time.Unix(number(obj(line["period"])["end"]), 0)
if !boolean(details["proration"]) && number(line["amount"]) >= 0 && details["subscription_item"] == item["id"] && end.After(paidThrough) {
paidThrough = end
}
return nil
})
})
if err != nil {
return err
}
}
planID := "unknown"
if plan != nil {
planID = plan.ID
}
values := M{"owner": owner, "scope": "user:" + owner, "planId": planID, "customerId": account["customerId"], "priceId": price, "subscriptionId": id, "status": sub["status"], "cancelAtPeriodEnd": boolean(sub["cancel_at_period_end"]) || number(sub["cancel_at"]) > 0, "until": paidThrough}
if number(sub["start_date"]) > 0 {
values["purchasedAt"] = time.Unix(number(sub["start_date"]), 0)
}
if str(previous["salePriceId"]) == "" && invoice["status"] == "paid" && invoice["billing_reason"] == "subscription_create" {
err = s.stripeEach(ctx, "/invoices/"+segment(str(invoice["id"]))+"/lines", nil, func(line M) error {
details := obj(obj(line["parent"])["subscription_item_details"])
price := stripeRef(obj(obj(line["pricing"])["price_details"])["price"])
if !boolean(details["proration"]) && details["subscription_item"] == item["id"] && price != "" {
plan, e := s.billingPlanForPrice(ctx, price, true)
if e != nil {
return e
}
if plan != nil {
values["salePriceId"], values["salePlanId"] = price, plan.ID
}
return errBillingStop
}
return nil
})
if err != nil && err != errBillingStop {
return err
}
}
if previous == nil {
values["_id"], values["revision"], values["revoked"] = id, 0, false
_, err = s.Store.DB.Collection("billinggrants").InsertOne(ctx, values)
if err == nil {
return nil
}
if !mongo.IsDuplicateKeyError(err) {
return err
}
} else {
filter := M{"_id": id, "revision": previous["revision"]}
result, e := s.Store.DB.Collection("billinggrants").UpdateOne(ctx, filter, M{"$set": values, "$inc": M{"revision": 1}})
if e != nil {
return e
}
if result.MatchedCount == 1 {
return nil
}
}
}
return fail("billing_busy", 409)
}
func (s *Server) fulfillBillingCheckout(ctx context.Context, id string) error {
session, err := s.stripe(ctx, "GET", "/checkout/sessions/"+segment(id), M{"expand": []string{"line_items", "payment_intent.latest_charge"}}, "")
if err != nil {
return err
}
metadata := obj(session["metadata"])
if metadata["application"] != "anonymous-github" {
return nil
}
owner, planID, target := str(metadata["owner"]), str(metadata["planId"]), str(metadata["target"])
account, err := s.Store.one(ctx, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
if account == nil || account["customerId"] != stripeRef(session["customer"]) {
return fail("billing_customer_mismatch", 400)
}
if session["status"] != "complete" {
return nil
}
if subscription := stripeRef(session["subscription"]); subscription != "" {
return s.syncBillingSubscription(ctx, subscription)
}
plan := s.Config.Billing.plan(planID)
items := arr(obj(session["line_items"])["data"])
if plan == nil || plan.Recurring || len(items) != 1 || number(obj(items[0])["quantity"]) != 1 {
return fail("billing_invalid_purchase", 400)
}
priceID := stripeRef(obj(items[0])["price"])
accepted, err := s.billingPlanForPrice(ctx, priceID, false)
if err != nil {
return err
}
scope := "repo:" + target
if conferencePlan(planID) {
scope = "conference:" + target
}
if accepted == nil || accepted.ID != planID {
previous, e := s.Store.one(ctx, "billinggrants", M{"_id": id})
if e != nil {
return e
}
if previous == nil || previous["owner"] != owner || previous["customerId"] != account["customerId"] || previous["planId"] != planID || previous["scope"] != scope || (str(previous["priceId"]) != "" && previous["priceId"] != priceID) {
return fail("billing_invalid_purchase", 400)
}
}
if priceID == "" {
return fail("billing_invalid_purchase", 400)
}
if err = s.billingUpsert(ctx, "billingprices", M{"_id": priceID}, M{"$setOnInsert": M{"planId": planID}}); err != nil {
return err
}
if session["payment_status"] != "paid" {
return nil
}
intent := obj(session["payment_intent"])
charge := obj(intent["latest_charge"])
revoked := boolean(charge["refunded"]) || boolean(charge["disputed"])
purchased := time.Unix(number(session["created"]), 0)
conferenceEnd := time.Time{}
if conferencePlan(planID) {
conference, e := s.Store.one(ctx, "conferences", M{"conferenceID": target})
if e != nil {
return e
}
if conference == nil {
return nil
}
conferenceEnd = date(conference["endDate"])
}
reversal, err := s.Store.one(ctx, "billingrevocations", M{"_id": stripeRef(session["payment_intent"])})
if err != nil {
return err
}
parts := []string{planID}
if planID == "repo_pack" {
parts = billingPack
}
// Serializing extensions prevents concurrent purchases from losing a year.
return s.billingLock(ctx, "fulfill:"+scope, func(work context.Context) error {
for _, part := range parts {
grantID := id
if planID == "repo_pack" {
grantID += ":" + part
}
until := purchased.Add(180 * 24 * time.Hour)
if part == "repo_never" || part == "repo_slot" {
until = billingNeverUntil
}
if part == "repo_extend" {
earlier, e := s.Store.list(work, "billinggrants", M{"_id": M{"$ne": grantID}, "scope": scope, "owner": owner, "planId": "repo_extend"}, 0, nil)
if e != nil {
return e
}
base := purchased
for _, g := range earlier {
if usableBillingGrant(g, purchased) && date(g["until"]).After(base) {
base = date(g["until"])
}
}
until = base.Add(365 * 24 * time.Hour)
}
if !conferenceEnd.IsZero() {
until = conferenceEnd
}
values := M{"owner": owner, "scope": scope, "planId": part, "customerId": account["customerId"], "paymentIntentId": stripeRef(session["payment_intent"]), "priceId": priceID, "status": "paid", "until": until, "purchasedAt": purchased, "revision": 0}
update := M{"$setOnInsert": values}
// Never clear a stored reversal on a duplicate delivery.
if boolean(reversal["reviewed"]) {
update["$set"] = M{"revoked": false}
} else if reversal != nil {
update["$set"] = M{"revoked": true, "revocationReason": reversal["reason"]}
} else if revoked {
update["$set"] = M{"revoked": true}
} else {
values["revoked"] = false
}
if err := s.billingUpsert(work, "billinggrants", M{"_id": grantID}, update); err != nil {
return err
}
grant, e := s.Store.one(work, "billinggrants", M{"_id": grantID})
if e != nil {
return e
}
if part == "repo_slot" && !boolean(grant["revoked"]) {
if _, e = s.Store.update(work, "billingquotas", M{"_id": "user:" + owner}, M{"$pull": M{"allocations": M{"repoId": target}}}); e != nil {
return e
}
}
if conferencePlan(planID) && !boolean(grant["revoked"]) {
if _, e = s.Store.update(work, "conferences", M{"conferenceID": target, "status": "pending_payment", "plan.planID": planID}, M{"$set": M{"status": "ready"}}); e != nil {
return e
}
}
}
return nil
})
}
@@ -0,0 +1,199 @@
package server
import (
"encoding/json"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/v2/bson"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func runBillingIntegration(t *testing.T, base *Server) {
ctx := t.Context()
db := base.Store.DB.Client().Database("billing_test_" + bson.NewObjectID().Hex())
defer db.Drop(ctx)
config := base.Config
config.Billing = BillingConfig{Enabled: true, Checkout: true, Origin: "https://anonymous.test", Secret: "sk_test_synthetic", WebhookSecret: "whsec_synthetic", FreeMonths: 5, FreeRepositories: 2, FreeStorage: 100, Plans: []BillingPlan{{ID: "repo_slot", PriceID: "price_slot", Capacity: true, Repositories: 1, Storage: 200}, {ID: "repo_extend", PriceID: "price_extend"}, {ID: "author_pass", PriceID: "price_pass", Capacity: true, Repositories: 1, Storage: 200}, {ID: "repo_pack", PriceID: "price_pack"}}}
s := &Server{Config: config, Store: &Store{DB: db, Redis: base.Store.Redis}}
owner := bson.NewObjectID()
user := M{"_id": owner, "username": "billing-fixture", "status": "active"}
_, err := db.Collection("users").InsertOne(ctx, user)
if err != nil {
t.Fatal(err)
}
_, err = db.Collection("billingaccounts").InsertOne(ctx, M{"_id": owner.Hex(), "customerId": "cus_fixture"})
if err != nil {
t.Fatal(err)
}
refund := false
s.HTTP = &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Host != "api.stripe.com" {
t.Fatalf("unexpected host %s", r.URL.Host)
}
var result M
switch r.URL.Path {
case "/v1/checkout/sessions/cs_fixture":
result = M{"id": "cs_fixture", "customer": "cus_fixture", "status": "complete", "payment_status": "paid", "created": time.Now().Unix(), "metadata": M{"application": "anonymous-github", "owner": owner.Hex(), "planId": "repo_pack", "target": "billing-repo"}, "line_items": M{"data": []M{{"quantity": 1, "price": M{"id": "price_pack"}}}}, "payment_intent": M{"id": "pi_fixture", "latest_charge": M{"refunded": refund, "disputed": false}}}
case "/v1/prices/price_pack":
result = M{"id": "price_pack", "unit_amount": 900, "currency": "eur"}
case "/v1/invoice_payments":
result = M{"data": []any{}, "has_more": false}
default:
t.Fatalf("unexpected Stripe path %s", r.URL.Path)
}
raw, _ := json.Marshal(result)
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
})}
if err = s.fulfillBillingCheckout(ctx, "cs_fixture"); err != nil {
t.Fatal(err)
}
if err = s.fulfillBillingCheckout(ctx, "cs_fixture"); err != nil {
t.Fatal(err)
}
grants, err := s.Store.list(ctx, "billinggrants", M{}, 0, nil)
if err != nil || len(grants) != 3 {
t.Fatal("pack not fulfilled exactly once", len(grants), err)
}
for _, g := range grants {
if !usableBillingGrant(g, time.Now()) {
t.Fatal("unusable paid grant", g)
}
}
q := &request{R: httptest.NewRequest("GET", "/api/admin/billing/summary?period=30d", nil), W: httptest.NewRecorder(), Server: s}
report, err := s.billingSummaryReport(q)
if err != nil {
t.Fatal(err)
}
if number(obj(obj(report)["sales"])["count"]) != 1 || decimal(obj(obj(obj(report)["sales"])["revenue"])["eur"]) != 900 {
t.Fatal("pack sales duplicated", report)
}
q.R = httptest.NewRequest("GET", "/api/admin/billing/grants?search=billing-fixture&state=active", nil)
listed, err := s.billingGrantReport(q)
if err != nil || number(obj(listed)["total"]) != 3 {
t.Fatal("grant search failed", listed, err)
}
if err = s.reserveBillingRepository(ctx, owner.Hex(), "free-one", 60, "", "", 0); err != nil {
t.Fatal(err)
}
if err = s.reserveBillingRepository(ctx, owner.Hex(), "free-one", 60, "", "", 0); err != nil {
t.Fatal("reservation not idempotent", err)
}
if err = s.reserveBillingRepository(ctx, owner.Hex(), "free-two", 50, "", "", 0); err == nil {
t.Fatal("storage quota bypassed")
}
if err = s.reserveBillingRepository(ctx, owner.Hex(), "billing-repo", 150, "", "", 0); err != nil {
t.Fatal("paid capacity unavailable", err)
}
if err = s.processBillingEvent(ctx, M{"type": "charge.refunded", "object": M{"id": "ch_fixture", "payment_intent": "pi_fixture", "amount": 900, "amount_refunded": 900, "refunded": true}}); err != nil {
t.Fatal(err)
}
if err = s.fulfillBillingCheckout(ctx, "cs_fixture"); err != nil {
t.Fatal(err)
}
grants, err = s.Store.list(ctx, "billinggrants", M{}, 0, nil)
if err != nil {
t.Fatal(err)
}
for _, g := range grants {
if !boolean(g["revoked"]) {
t.Fatal("checkout replay restored refunded access", g)
}
}
}
func runOwnerAlertsIntegration(t *testing.T, base *Server) {
ctx := t.Context()
db := base.Store.DB.Client().Database("alerts_test_" + bson.NewObjectID().Hex())
defer db.Drop(ctx)
s := &Server{Store: &Store{DB: db, Redis: base.Store.Redis}, Config: Config{EmailAPIKey: "synthetic", EmailFrom: "alerts@example.test", Hostname: "anonymous.test"}}
sends := 0
s.HTTP = &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Host != "api.resend.com" {
t.Fatal(r.URL.Host)
}
sends++
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{}`))}, nil
})}
resources := []M{}
for i := 0; i < 2; i++ {
owner := bson.NewObjectID()
_, err := db.Collection("users").InsertOne(ctx, M{"_id": owner, "status": "active", "notificationEmail": "shared@example.test"})
if err != nil {
t.Fatal(err)
}
row := M{"_id": bson.NewObjectID(), "repoId": owner.Hex(), "owner": owner, "status": "ready"}
_, err = db.Collection(collection("repo")).InsertOne(ctx, row)
if err != nil {
t.Fatal(err)
}
resources = append(resources, row)
}
if err := s.notifyOwnerAccessProblem(ctx, "repo", resources[0], fail("repo_not_found", 502)); err != nil {
t.Fatal(err)
}
if sends != 0 {
t.Fatal("outage sent an access alert")
}
for _, r := range resources {
if err := s.notifyOwnerAccessProblem(ctx, "repo", r, fail("repo_not_found", 404)); err != nil {
t.Fatal(err)
}
}
if sends != 1 {
t.Fatal("recipient was notified more than once", sends)
}
if err := s.resetOwnerAlerts(ctx, resources[0]["owner"], "repo", resources[0]["_id"]); err != nil {
t.Fatal(err)
}
if err := s.notifyOwnerAccessProblem(ctx, "repo", resources[0], fail("repo_not_found", 404)); err != nil {
t.Fatal(err)
}
if sends != 1 {
t.Fatal("reset erased delivery history")
}
_, err := db.Collection("users").UpdateOne(ctx, M{"_id": resources[1]["owner"]}, M{"$set": M{"notificationEmail": "new@example.test"}})
if err != nil {
t.Fatal(err)
}
finish, err := s.beginAlertDeactivation(ctx, resources[1]["owner"])
if err != nil {
t.Fatal(err)
}
if err = s.notifyOwnerAccessProblem(ctx, "repo", resources[1], fail("repo_not_found", 404)); err != nil {
t.Fatal(err)
}
finish()
if sends != 1 {
t.Fatal("deactivation allowed dispatch")
}
if err = s.notifyOwnerAccessProblem(ctx, "repo", resources[1], fail("repo_not_found", 404)); err != nil {
t.Fatal(err)
}
if sends != 2 {
t.Fatal("new recipient not notified")
}
for _, state := range []string{"prepared", "committed"} {
attempt := uuid.NewString()
email := state + "@example.test"
owner := resources[1]["owner"]
_, err := db.Collection("users").UpdateOne(ctx, M{"_id": owner}, M{"$set": M{"notificationEmail": email, "accessAlertDispatches." + attempt: M{"state": state}}})
if err != nil {
t.Fatal(err)
}
_, err = db.Collection(recipientAlerts).InsertOne(ctx, M{"_id": alertRecipientKey(email), "owner": owner, "resourceKind": "repository", "resourceId": resources[1]["_id"], "attemptId": attempt, "state": "sending", "dispatchPrepared": true, "claimedAt": time.Now().Add(-2 * time.Minute)})
if err != nil {
t.Fatal(err)
}
if err := s.notifyOwnerAccessProblem(ctx, "repo", resources[1], fail("repo_not_found", 404)); err != nil {
t.Fatal(err)
}
if sends != 3 {
t.Fatalf("%s recovery: sends=%d", state, sends)
}
}
}
@@ -0,0 +1,203 @@
package server
import (
"context"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
)
func (s *Server) reconcileBillingAccount(ctx context.Context, owner string) error {
return s.billingLock(ctx, "reconcile:"+owner, func(work context.Context) error {
account, err := s.Store.one(work, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
if str(account["customerId"]) == "" {
return fail("billing_customer_missing", 400)
}
if err = s.stripeEach(work, "/subscriptions", M{"customer": account["customerId"], "status": "all"}, func(sub M) error { return s.syncBillingSubscription(work, str(sub["id"])) }); err != nil {
return err
}
if err = s.stripeEach(work, "/checkout/sessions", M{"customer": account["customerId"]}, func(session M) error {
meta := obj(session["metadata"])
if meta["application"] != "anonymous-github" || meta["owner"] != owner {
return nil
}
checkout := obj(account["checkout"])
if str(checkout["key"]) != "" && str(checkout["id"]) == "" && meta["attempt"] == checkout["key"] {
if _, err := s.Store.update(work, "billingaccounts", M{"_id": owner, "checkout.key": checkout["key"]}, M{"$set": M{"checkout.id": session["id"]}}); err != nil {
return err
}
}
if session["status"] == "complete" {
return s.fulfillBillingCheckout(work, str(session["id"]))
}
return nil
}); err != nil {
return err
}
if err = s.stripeEach(work, "/charges", M{"customer": account["customerId"]}, func(charge M) error {
if boolean(charge["refunded"]) || boolean(charge["disputed"]) {
charge["refunded"] = true
return s.processBillingEvent(work, M{"type": "charge.refunded", "object": charge})
}
return nil
}); err != nil {
return err
}
_, err = s.Store.update(work, "billingaccounts", M{"_id": owner}, M{"$set": M{"reconciledAt": time.Now(), "reconcileAfter": time.Now().Add(24 * time.Hour)}, "$unset": M{"reconcileError": 1}})
return err
})
}
func (s *Server) reconcileBillingAccounts(ctx context.Context) error {
rows, err := s.Store.list(ctx, "billingaccounts", M{"customerId": M{"$exists": true}, "$or": []M{{"reconcileAfter": M{"$lte": time.Now()}}, {"reconcileAfter": M{"$exists": false}}}}, 10, bson.D{{Key: "reconcileAfter", Value: 1}})
if err != nil {
return err
}
for _, row := range rows {
if err := s.reconcileBillingAccount(ctx, str(row["_id"])); err != nil {
s.Store.update(ctx, "billingaccounts", M{"_id": row["_id"]}, M{"$set": M{"reconcileAfter": time.Now().Add(15 * time.Minute), "reconcileError": "billing_processing_failed"}})
}
}
_, err = s.Store.DB.Collection("billingevents").DeleteMany(ctx, M{"state": "complete", "completedAt": M{"$lt": time.Now().Add(-90 * 24 * time.Hour)}})
return err
}
func (s *Server) runBillingMaintenance(ctx context.Context) {
if !s.Config.Billing.Enabled {
return
}
if err := s.rememberBillingPrices(ctx); err != nil {
s.recordError(ctx, err)
}
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
next := time.Time{}
for {
if err := s.processBillingInbox(ctx); err != nil && ctx.Err() == nil {
s.recordError(ctx, err)
}
if time.Now().After(next) {
if err := s.reconcileBillingAccounts(ctx); err != nil && ctx.Err() == nil {
s.recordError(ctx, err)
}
next = time.Now().Add(5 * time.Minute)
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (s *Server) cancelAccountBilling(ctx context.Context, owner string) error {
account, err := s.Store.one(ctx, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
if str(account["customerId"]) == "" {
return nil
}
return s.billingLock(ctx, "checkout:"+owner, func(work context.Context) error {
account, err := s.Store.one(work, "billingaccounts", M{"_id": owner})
if err != nil {
return err
}
if str(account["customerId"]) == "" {
return nil
}
checkout := obj(account["checkout"])
if str(checkout["key"]) != "" && str(checkout["id"]) == "" {
return fail("billing_checkout_in_progress", 409)
}
if id := str(checkout["id"]); id != "" {
session, err := s.stripe(work, "GET", "/checkout/sessions/"+segment(id), nil, "")
if err != nil {
return err
}
if session["status"] == "open" {
if _, err = s.stripe(work, "POST", "/checkout/sessions/"+segment(id)+"/expire", nil, ""); err != nil {
return err
}
}
}
if err = s.stripeEach(work, "/subscriptions", M{"customer": account["customerId"], "status": "all"}, func(sub M) error {
if sub["status"] == "canceled" || sub["status"] == "incomplete_expired" {
return nil
}
_, err := s.stripe(work, "DELETE", "/subscriptions/"+segment(str(sub["id"])), nil, "")
return err
}); err != nil {
return err
}
_, err = s.Store.DB.Collection("billinggrants").UpdateMany(work, M{"owner": owner, "subscriptionId": M{"$exists": true}}, M{"$set": M{"status": "canceled"}, "$inc": M{"revision": 1}})
return err
})
}
func (s *Server) reconcileBillingExpiration(ctx context.Context) error {
if !s.Config.Billing.Enabled {
return nil
}
cursor, err := s.Store.DB.Collection(collection("repo")).Find(ctx, M{"options.expirationMode": "never", "billingNeverExpiresUntil": M{"$exists": true}, "status": M{"$nin": []string{"removed", "expired", "expiring", "removing"}}})
if err != nil {
return err
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var repo M
if err := cursor.Decode(&repo); err != nil {
return err
}
now := time.Now()
owner := str(repo["owner"])
previous := date(repo["billingNeverExpiresUntil"])
deadline := previous
refresh := func() error {
grants, err := s.Store.list(ctx, "billinggrants", M{"$or": []M{{"scope": "user:" + owner, "planId": M{"$in": []string{"author_monthly", "author_annual"}}}, {"scope": "repo:" + str(repo["repoId"]), "owner": owner, "planId": "repo_never"}}}, 0, nil)
if err != nil {
return err
}
for _, g := range grants {
if boolean(g["revoked"]) {
continue
}
until := date(g["until"])
if g["planId"] == "repo_never" {
if !usableBillingGrant(g, now) || !previous.Before(now.Add(83*24*time.Hour)) {
continue
}
until = now
}
if until.IsZero() {
continue
}
until = until.Add(90 * 24 * time.Hour)
if until.After(deadline) {
deadline = until
}
}
return nil
}
if err := refresh(); err != nil {
return err
}
if !deadline.After(now) {
if err := s.reconcileBillingAccount(ctx, owner); err != nil {
continue
}
if err := refresh(); err != nil {
return err
}
}
set := M{"billingNeverExpiresUntil": deadline}
update := M{"$set": set}
if !deadline.After(now) {
set = M{"options.expirationMode": "remove", "options.expirationDate": deadline}
update = M{"$set": set, "$unset": M{"billingNeverExpiresUntil": 1}}
}
if _, err = s.Store.update(ctx, collection("repo"), M{"_id": repo["_id"], "options.expirationMode": "never", "billingNeverExpiresUntil": previous}, update); err != nil {
return err
}
}
return cursor.Err()
}
+102
View File
@@ -0,0 +1,102 @@
[
{
"id": "author_monthly",
"name": "Author monthly",
"priceId": "STRIPE_AUTHOR_MONTHLY_PRICE",
"recurring": true,
"capacity": true,
"repositories": "PAID_AUTHOR_REPOSITORIES",
"storage": "PAID_AUTHOR_STORAGE",
"description": "Never-expiring repositories while subscribed, then a 90-day grace period. Renews monthly. Cancel renewal at any time."
},
{
"id": "author_annual",
"name": "Author annual",
"priceId": "STRIPE_AUTHOR_ANNUAL_PRICE",
"recurring": true,
"capacity": true,
"repositories": "PAID_AUTHOR_REPOSITORIES",
"storage": "PAID_AUTHOR_STORAGE",
"description": "Never-expiring repositories while subscribed, then a 90-day grace period. Renews annually. Cancel renewal at any time."
},
{
"id": "author_pass",
"name": "Live updates",
"priceId": "STRIPE_AUTHOR_PASS_PRICE",
"recurring": false,
"capacity": true,
"repositories": 1,
"storage": "PAID_PASS_STORAGE",
"description": "Automatic updates for one repository for 180 days, with its own storage allowance. No automatic renewal."
},
{
"id": "repo_extend",
"name": "Extended expiration",
"priceId": "STRIPE_REPO_EXTEND_PRICE",
"recurring": false,
"capacity": false,
"repositories": 0,
"storage": 0,
"description": "Keep one repository online for up to one more year. Buy again to add another year. No automatic renewal."
},
{
"id": "repo_never",
"name": "Never expire",
"priceId": "STRIPE_REPO_NEVER_PRICE",
"recurring": false,
"capacity": false,
"repositories": 0,
"storage": 0,
"description": "One repository never expires. One-time payment, no subscription."
},
{
"id": "repo_slot",
"name": "Extra repository",
"priceId": "STRIPE_REPO_SLOT_PRICE",
"recurring": false,
"capacity": true,
"repositories": 1,
"storage": "PAID_PASS_STORAGE",
"description": "Host one more repository beyond the free allowance, with its own storage. It does not count toward your free repositories. One-time payment, valid while the repository exists."
},
{
"id": "repo_pack",
"name": "Paper pack",
"priceId": "STRIPE_REPO_PACK_PRICE",
"recurring": false,
"capacity": false,
"repositories": 0,
"storage": 0,
"description": "Everything one paper needs during review: an extra repository, automatic updates for 180 days, and one more year before it expires. One-time payment."
},
{
"id": "conference_workshop",
"name": "Workshop",
"priceId": "STRIPE_CONFERENCE_SMALL_PRICE",
"recurring": false,
"capacity": true,
"repositories": "PAID_CONFERENCE_SMALL_REPOSITORIES",
"storage": "PAID_CONFERENCE_SMALL_STORAGE",
"description": "For a workshop or small venue. A review window of up to 180 days. No automatic renewal."
},
{
"id": "conference",
"name": "Conference",
"priceId": "STRIPE_CONFERENCE_PRICE",
"recurring": false,
"capacity": true,
"repositories": "PAID_CONFERENCE_REPOSITORIES",
"storage": "PAID_CONFERENCE_STORAGE",
"description": "For a typical conference track. A review window of up to 180 days. No automatic renewal."
},
{
"id": "conference_large",
"name": "Large conference",
"priceId": "STRIPE_CONFERENCE_LARGE_PRICE",
"recurring": false,
"capacity": true,
"repositories": "PAID_CONFERENCE_LARGE_REPOSITORIES",
"storage": "PAID_CONFERENCE_LARGE_STORAGE",
"description": "For a large venue with several tracks. A review window of up to 180 days. No automatic renewal."
}
]
+218
View File
@@ -0,0 +1,218 @@
package server
import (
"context"
"math"
"strings"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/v2/mongo"
)
func (s *Server) billingAllowance(ctx context.Context, owner, repoID, conference string) (M, error) {
scopes := []string{"user:" + owner}
if repoID != "" {
scopes = append(scopes, "repo:"+repoID)
}
if conference != "" {
scopes = append(scopes, "conference:"+conference)
}
now := time.Now()
grants, err := s.Store.list(ctx, "billinggrants", M{"scope": M{"$in": scopes}, "until": M{"$gt": now}, "revoked": false}, 0, nil)
if err != nil {
return nil, err
}
for i := len(scopes) - 1; i >= 0; i-- {
scope := scopes[i]
var chosen *BillingPlan
for _, grant := range grants {
if grant["scope"] != scope || !usableBillingGrant(grant, now) || (strings.HasPrefix(scope, "repo:") && grant["owner"] != owner) {
continue
}
plan := s.Config.Billing.plan(str(grant["planId"]))
if plan != nil && plan.Capacity && (chosen == nil || chosen.ID == "repo_slot") {
chosen = plan
}
}
if chosen != nil {
return M{"scope": scope, "repositories": chosen.Repositories, "storage": chosen.Storage, "plan": chosen.ID}, nil
}
}
return M{"scope": "user:" + owner, "repositories": s.Config.Billing.FreeRepositories, "storage": s.Config.Billing.FreeStorage, "plan": "free"}, nil
}
func (s *Server) reserveBillingRepository(ctx context.Context, owner, repoID string, bytes int64, conference, expansionKey string, expansionBytes int64) error {
if !s.Config.Billing.Enabled {
return nil
}
if bytes < 0 || bytes > 9007199254740991 || expansionBytes < 0 || expansionBytes > 9007199254740991 {
return fail("billing_invalid_repository_size", 400)
}
limits, err := s.billingAllowance(ctx, owner, repoID, conference)
if err != nil {
return err
}
scope := str(limits["scope"])
for retry := 0; retry < 10; retry++ {
ledger, err := s.Store.one(ctx, "billingquotas", M{"_id": scope})
if err != nil {
return err
}
if ledger == nil {
filter := M{"status": M{"$nin": []string{"removed", "expired"}}}
switch {
case strings.HasPrefix(scope, "user:"):
ownerID, e := oid(owner)
if e != nil {
return e
}
filter["owner"] = ownerID
case strings.HasPrefix(scope, "conference:"):
filter["conference"] = conference
default:
filter["repoId"] = repoID
}
repos, e := s.Store.list(ctx, collection("repo"), filter, 0, nil)
if e != nil {
return e
}
allocations := []M{}
for _, repo := range repos {
funding, e := s.billingAllowance(ctx, str(repo["owner"]), str(repo["repoId"]), str(repo["conference"]))
if e != nil {
return e
}
if funding["scope"] == scope {
allocations = append(allocations, M{"repoId": repo["repoId"], "reservationId": uuid.NewString(), "bytes": number(obj(repo["size"])["storage"]), "createdAt": time.Now()})
}
}
_, e = s.Store.DB.Collection("billingquotas").InsertOne(ctx, M{"_id": scope, "allocations": allocations})
if e != nil && !mongo.IsDuplicateKeyError(e) {
return e
}
continue
}
original := arr(ledger["allocations"])
ids := make([]string, 0, len(original))
for _, value := range original {
ids = append(ids, str(obj(value)["repoId"]))
}
removed, e := s.Store.list(ctx, collection("repo"), M{"repoId": M{"$in": ids}, "status": "removed"}, 0, nil)
if e != nil {
return e
}
terminal := make(map[string]bool, len(removed))
for _, row := range removed {
terminal[str(row["repoId"])] = true
}
next := []M{}
old := M{}
used := int64(0)
for _, value := range original {
allocation := obj(value)
if allocation["repoId"] == repoID {
old = allocation
continue
}
if terminal[str(allocation["repoId"])] {
continue
}
size := number(allocation["bytes"])
if size < 0 || used > math.MaxInt64-size {
return fail("quota_exceeded", 402)
}
used += size
next = append(next, allocation)
}
expansions := []M{}
oldExtra, newExtra := int64(0), int64(0)
found := false
for _, value := range arr(old["expansions"]) {
entry := obj(value)
size := number(entry["bytes"])
if size < 0 || oldExtra > 9007199254740991-size {
return fail("billing_invalid_repository_size", 400)
}
oldExtra += size
if expansionKey != "" && entry["key"] == expansionKey {
size = max(size, expansionBytes)
found = true
}
expansions = append(expansions, M{"key": entry["key"], "bytes": size})
if newExtra > 9007199254740991-size {
return fail("billing_invalid_repository_size", 400)
}
newExtra += size
}
if expansionKey != "" && !found {
expansions = append(expansions, M{"key": expansionKey, "bytes": expansionBytes})
if newExtra > 9007199254740991-expansionBytes {
return fail("billing_invalid_repository_size", 400)
}
newExtra += expansionBytes
}
base := number(old["baseBytes"])
if _, exists := old["baseBytes"]; !exists {
base = number(old["bytes"]) - oldExtra
}
base = max(base, bytes)
reserved := base + newExtra
if reserved < 0 || reserved > 9007199254740991 || int64(len(next)) >= number(limits["repositories"]) || used > number(limits["storage"])-reserved {
return fail("quota_exceeded", 402)
}
next = append(next, M{"repoId": repoID, "reservationId": uuid.NewString(), "bytes": reserved, "baseBytes": base, "expansions": expansions, "createdAt": time.Now()})
result, e := s.Store.DB.Collection("billingquotas").UpdateOne(ctx, M{"_id": scope, "allocations": ledger["allocations"]}, M{"$set": M{"allocations": next}})
if e != nil {
return e
}
if result.MatchedCount == 1 {
return nil
}
}
return fail("billing_busy", 409)
}
func (s *Server) billingConferenceAdmission(ctx context.Context, owner, repoID, conference string) error {
if !s.Config.Billing.Enabled || conference == "" {
return nil
}
row, err := s.Store.one(ctx, "conferences", M{"conferenceID": conference})
if err != nil {
return err
}
now := time.Now()
if row == nil || row["status"] != "ready" || date(row["startDate"]).After(now) || !date(row["endDate"]).After(now) {
return fail("conf_not_activated", 400)
}
if conferencePlan(str(obj(row["plan"])["planID"])) {
allowance, err := s.billingAllowance(ctx, owner, repoID, conference)
if err != nil {
return err
}
if allowance["scope"] != "conference:"+conference {
return fail("conference_payment_required", 402)
}
}
return nil
}
func (s *Server) billingAutomaticUpdates(ctx context.Context, owner, repoID, conference string) (bool, error) {
if !s.Config.Billing.Enabled {
return true, nil
}
allowance, err := s.billingAllowance(ctx, owner, repoID, conference)
if err != nil {
return false, err
}
if allowance["plan"] != "free" && allowance["plan"] != "repo_slot" {
return true, nil
}
grants, err := s.Store.list(ctx, "billinggrants", M{"scope": "user:" + owner, "planId": M{"$in": []string{"author_monthly", "author_annual"}}}, 0, nil)
if err != nil {
return false, err
}
for _, g := range grants {
if usableBillingGrant(g, time.Now()) {
return true, nil
}
}
return false, nil
}
+199
View File
@@ -0,0 +1,199 @@
package server
import (
"crypto/sha256"
"encoding/hex"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"math"
"regexp"
"sort"
"strings"
"time"
)
var billingPackPart = regexp.MustCompile(`^cs_[^:]+:(repo_slot|author_pass|repo_extend)$`)
var billingFilterWord = regexp.MustCompile(`^[a-z_]{1,40}$`)
func billingFamily(plan string) string {
if plan == "author_monthly" || plan == "author_annual" || plan == "subscription_unknown" {
return "subscription"
}
if conferencePlan(plan) {
return "conference"
}
return "repository"
}
func billingStates(now time.Time) M {
return M{"active": M{"revoked": M{"$ne": true}, "until": M{"$gt": now}, "status": M{"$in": []string{"active", "paid", "past_due"}}}, "revoked": M{"revoked": true}, "expired": M{"revoked": M{"$ne": true}, "$or": []M{{"until": M{"$not": M{"$gt": now}}}, {"status": M{"$nin": []string{"active", "paid", "past_due"}}}}}}
}
func (s *Server) billingGrantReport(q *request) (any, error) {
q.W.Header().Set("Cache-Control", "no-store")
query := q.R.URL.Query()
now := time.Now()
states := billingStates(now)
filter := M{}
plan, status := query.Get("plan"), query.Get("status")
if billingFilterWord.MatchString(plan) {
if plan == "repo_pack" {
filter["_id"] = M{"$regex": billingPackPart.String()}
} else {
filter["planId"] = plan
}
}
if billingFilterWord.MatchString(status) {
filter["status"] = status
}
pipeline := []M{{"$match": filter}}
if search := strings.TrimSpace(query.Get("search")); search != "" {
pipeline = append(pipeline, M{"$set": M{"userId": M{"$convert": M{"input": "$owner", "to": "objectId", "onError": nil, "onNull": nil}}}}, M{"$lookup": M{"from": "users", "localField": "userId", "foreignField": "_id", "pipeline": []M{{"$match": M{"username": M{"$regex": regexp.QuoteMeta(search), "$options": "i"}}}, {"$project": M{"_id": 1}}}, "as": "user"}}, M{"$match": M{"user.0": M{"$exists": true}}})
}
page := max(int64(1), int64(math.Min(90071992547409, adminParseInt(query.Get("page"), 1))))
limit := int64(math.Min(100, adminParseInt(query.Get("limit"), 25)))
if limit == 0 {
limit = 25
}
limit = max(int64(1), min(limit, int64(100)))
page = min(page, int64(90071992547409))
field := query.Get("sort")
if field != "until" {
field = "purchasedAt"
}
direction := -1
if query.Get("direction") == "asc" {
direction = 1
}
selected := []M{}
if state, ok := states[query.Get("state")]; ok {
selected = append(selected, M{"$match": state})
}
count := append(append([]M{}, selected...), M{"$count": "count"})
listed := append(append([]M{}, selected...), M{"$sort": bson.D{{Key: field, Value: direction}, {Key: "_id", Value: -1}}}, M{"$skip": (page - 1) * limit}, M{"$limit": limit}, M{"$project": M{"owner": 1, "scope": 1, "planId": 1, "status": 1, "until": 1, "cancelAtPeriodEnd": 1, "purchasedAt": 1, "revoked": 1, "revocationReason": 1, "revokedAt": 1, "subscriptionId": 1}})
facets := M{"total": count, "grants": listed}
for key, state := range states {
facets[key] = []M{{"$match": state}, {"$count": "count"}}
}
pipeline = append(pipeline, M{"$facet": facets})
cursor, err := s.Store.DB.Collection("billinggrants").Aggregate(q.ctx(), pipeline)
if err != nil {
return nil, err
}
defer cursor.Close(q.ctx())
result := M{}
if cursor.Next(q.ctx()) {
if err = cursor.Decode(&result); err != nil {
return nil, err
}
}
if err = cursor.Err(); err != nil {
return nil, err
}
counts := func(key string) int64 {
rows := arr(result[key])
if len(rows) == 0 {
return 0
}
return number(obj(rows[0])["count"])
}
ownerIDs := []bson.ObjectID{}
for _, value := range arr(result["grants"]) {
if id, e := oid(str(obj(value)["owner"])); e == nil {
ownerIDs = append(ownerIDs, id)
}
}
users, err := s.Store.list(q.ctx(), "users", M{"_id": M{"$in": ownerIDs}}, 0, nil)
if err != nil {
return nil, err
}
names := map[string]string{}
for _, user := range users {
names[str(user["_id"])] = str(user["username"])
}
rows := []M{}
for _, value := range arr(result["grants"]) {
grant := obj(value)
id := str(grant["_id"])
digest := sha256.Sum256([]byte(id))
state := "expired"
if boolean(grant["revoked"]) {
state = "revoked"
} else if usableBillingGrant(grant, now) {
state = "active"
}
never := !date(grant["until"]).Before(billingNeverUntil)
until := grant["until"]
if never {
until = nil
}
scope := M{"kind": "account", "id": nil}
parts := strings.SplitN(str(grant["scope"]), ":", 2)
if len(parts) == 2 && (parts[0] == "repo" || parts[0] == "conference") {
scope = M{"kind": parts[0], "id": parts[1]}
}
var user any
if name := names[str(grant["owner"])]; name != "" {
user = name
}
plan := str(grant["planId"])
if plan == "" {
plan = "unknown"
}
rows = append(rows, M{"id": hex.EncodeToString(digest[:])[:12], "user": user, "planId": plan, "pack": billingPackPart.MatchString(id), "family": billingFamily(plan), "subscription": str(grant["subscriptionId"]) != "", "status": grant["status"], "state": state, "purchasedAt": grant["purchasedAt"], "until": until, "never": never, "cancelAtPeriodEnd": boolean(grant["cancelAtPeriodEnd"]), "revoked": boolean(grant["revoked"]), "revocationReason": grant["revocationReason"], "revokedAt": grant["revokedAt"], "scope": scope})
}
statuses := []string{}
distinct := s.Store.DB.Collection("billinggrants").Distinct(q.ctx(), "status", M{})
var values []any
if err = distinct.Decode(&values); err != nil {
return nil, err
}
for _, v := range values {
if str(v) != "" {
statuses = append(statuses, str(v))
}
}
sort.Strings(statuses)
return M{"page": page, "limit": limit, "total": counts("total"), "results": rows, "stateCounts": M{"active": counts("active"), "expired": counts("expired"), "revoked": counts("revoked")}, "statuses": statuses}, nil
}
func (s *Server) billingWebhookHealth(q *request) (M, error) {
out := M{}
for _, spec := range []struct {
key, collection string
filter M
}{{"pending", "billingevents", M{"state": M{"$in": []string{"pending", "processing"}}}}, {"failed", "billingevents", M{"state": "failed"}}, {"unresolved", "billingaccounts", M{"checkout.key": M{"$exists": true}, "checkout.id": M{"$exists": false}}}, {"reconciliationFailed", "billingaccounts", M{"reconcileError": M{"$exists": true}}}, {"unreviewedRevocations", "billingrevocations", M{"reviewed": false}}} {
n, err := s.Store.DB.Collection(spec.collection).CountDocuments(q.ctx(), spec.filter)
if err != nil {
return nil, err
}
out[spec.key] = n
}
for _, spec := range []struct {
key, collection, sort string
direction int
filter M
fields []string
}{{"oldest", "billingevents", "receivedAt", 1, M{"state": M{"$in": []string{"pending", "processing"}}}, []string{"receivedAt"}}, {"lastError", "billingevents", "nextAttemptAt", -1, M{"state": M{"$in": []string{"pending", "processing", "failed"}}, "lastError": M{"$exists": true}}, []string{"type", "state", "lastError", "attempts", "receivedAt"}}, {"latestRevocation", "billingrevocations", "createdAt", -1, M{"reviewed": false}, []string{"reason", "createdAt"}}} {
cursor, err := s.Store.DB.Collection(spec.collection).Find(q.ctx(), spec.filter, options.Find().SetSort(bson.D{{Key: spec.sort, Value: spec.direction}}).SetLimit(1))
if err != nil {
return nil, err
}
var rows []M
err = cursor.All(q.ctx(), &rows)
if err != nil {
return nil, err
}
out[spec.key] = nil
if len(rows) > 0 {
out[spec.key] = selectFields(rows[0], spec.fields...)
}
}
out["oldestPendingSeconds"] = int64(0)
if row := obj(out["oldest"]); len(row) > 0 {
out["oldestPendingSeconds"] = int64(time.Since(date(row["receivedAt"])).Seconds())
}
delete(out, "oldest")
if row := obj(out["lastError"]); len(row) > 0 {
row["error"] = row["lastError"]
delete(row, "lastError")
}
return out, nil
}
+248
View File
@@ -0,0 +1,248 @@
package server
import (
"math"
"time"
)
func billingBucket(d time.Time, unit string) time.Time {
d = d.UTC()
day := d.Day()
if unit == "month" {
day = 1
}
out := time.Date(d.Year(), d.Month(), day, 0, 0, 0, 0, time.UTC)
if unit == "week" {
out = out.AddDate(0, 0, -(int(out.Weekday())+6)%7)
}
return out
}
func billingNextBucket(d time.Time, unit string) time.Time {
if unit == "month" {
return d.AddDate(0, 1, 0)
}
if unit == "week" {
return d.AddDate(0, 0, 7)
}
return d.AddDate(0, 0, 1)
}
type billingTotals struct {
count, missing int64
money map[string]float64
}
func (t *billingTotals) add(price M, monthly bool, plan string) {
t.count++
if price == nil || price["unit_amount"] == nil {
t.missing++
return
}
if t.money == nil {
t.money = map[string]float64{}
}
amount := decimal(price["unit_amount"])
if monthly {
recurring := obj(price["recurring"])
interval := str(recurring["interval"])
if interval == "" {
interval = "month"
if plan == "author_annual" {
interval = "year"
}
}
factor := map[string]float64{"day": 365.0 / 12, "week": 52.0 / 12, "month": 1, "year": 1.0 / 12}[interval]
if factor == 0 {
factor = 1
}
amount = amount * factor / math.Max(1, decimal(recurring["interval_count"]))
}
t.money[str(price["currency"])] += amount
}
func (t billingTotals) amounts() M {
out := M{}
for c, n := range t.money {
out[c] = math.Floor(n + 0.5)
}
return out
}
func (t billingTotals) json(available bool) M {
return M{"count": t.count, "revenue": t.amounts(), "complete": available && t.missing == 0}
}
type billingPlanTotals struct {
all, period billingTotals
active int64
}
func (s *Server) billingSummaryReport(q *request) (any, error) {
q.W.Header().Set("Cache-Control", "no-store")
period := q.R.URL.Query().Get("period")
days, ok := map[string]int{"7d": 7, "30d": 30, "90d": 90, "12m": 365, "all": 0}[period]
if !ok {
period, days = "30d", 30
}
now := time.Now()
var since time.Time
var sinceJSON any
if days > 0 {
since = now.Add(-time.Duration(days) * 24 * time.Hour)
sinceJSON = since
}
unit := "day"
if period == "12m" {
unit = "week"
}
if period == "all" {
unit = "month"
}
pack := M{"$regexMatch": M{"input": M{"$toString": "$_id"}, "regex": billingPackPart.String()}}
subscription := M{"$ne": []any{M{"$ifNull": []any{"$subscriptionId", nil}}, nil}}
cond := func(test, a, b any) M { return M{"$cond": []any{test, a, b}} }
fallback := func(value, defaultValue any) M { return M{"$ifNull": []any{value, defaultValue}} }
project := M{"sale": cond(pack, M{"$arrayElemAt": []any{M{"$split": []any{"$_id", ":"}}, 0}}, "$_id"), "plan": cond(pack, "repo_pack", cond(subscription, fallback("$salePlanId", "subscription_unknown"), fallback("$planId", "unknown"))), "priceId": cond(subscription, fallback("$salePriceId", nil), "$priceId"), "currentPriceId": "$priceId", "currentPlan": cond(pack, "repo_pack", fallback("$planId", "unknown")), "purchasedAt": cond(M{"$and": []any{subscription, M{"$not": []any{M{"$gt": []any{"$until", time.Unix(0, 0)}}}}}}, nil, "$purchasedAt"), "cancel": M{"$eq": []any{"$cancelAtPeriodEnd", true}}, "usable": M{"$and": []any{M{"$ne": []any{"$revoked", true}}, M{"$gt": []any{"$until", now}}, M{"$in": []any{"$status", []string{"active", "paid", "past_due"}}}}}}
group := M{"_id": "$sale", "plan": M{"$first": "$plan"}, "priceId": M{"$first": "$priceId"}, "currentPlan": M{"$first": "$currentPlan"}, "currentPriceId": M{"$first": "$currentPriceId"}, "purchasedAt": M{"$min": "$purchasedAt"}, "active": M{"$max": "$usable"}, "cancel": M{"$max": "$cancel"}}
cursor, err := s.Store.DB.Collection("billinggrants").Aggregate(q.ctx(), []M{{"$project": project}, {"$group": group}})
if err != nil {
return nil, err
}
defer cursor.Close(q.ctx())
available := s.Config.Billing.Enabled && s.Config.Billing.Secret != ""
prices := map[string]M{}
price := func(id string) M {
if !available || id == "" {
return nil
}
if p, ok := prices[id]; ok {
return p
}
p, err := s.stripe(q.ctx(), "GET", "/prices/"+segment(id), nil, "")
if err != nil {
p = nil
}
prices[id] = p
return p
}
all, selected, subs := billingTotals{}, billingTotals{}, billingTotals{}
monthly, annual, cancelling := int64(0), int64(0), int64(0)
plans := map[string]*billingPlanTotals{}
order := []string{}
names := map[string]string{}
for _, p := range s.Config.Billing.Plans {
order = append(order, p.ID)
names[p.ID] = p.Name
plans[p.ID] = &billingPlanTotals{}
}
ensure := func(id string) *billingPlanTotals {
if p := plans[id]; p != nil {
return p
}
p := &billingPlanTotals{}
plans[id] = p
order = append(order, id)
return p
}
series := map[time.Time]M{}
first := since
for cursor.Next(q.ctx()) {
var row M
if err = cursor.Decode(&row); err != nil {
return nil, err
}
plan, current := str(row["plan"]), str(row["currentPlan"])
p := ensure(plan)
at := date(row["purchasedAt"])
if !at.IsZero() {
rate := price(str(row["priceId"]))
all.add(rate, false, plan)
p.all.add(rate, false, plan)
if since.IsZero() || !at.Before(since) {
selected.add(rate, false, plan)
p.period.add(rate, false, plan)
bucket := billingBucket(at, unit)
if first.IsZero() || bucket.Before(first) {
first = bucket
}
v := series[bucket]
if v == nil {
v = M{"date": bucket, "subscription": int64(0), "repository": int64(0), "conference": int64(0)}
series[bucket] = v
}
family := billingFamily(plan)
v[family] = number(v[family]) + 1
}
}
if boolean(row["active"]) {
ensure(current).active++
if current == "author_monthly" || current == "author_annual" {
subs.add(price(str(row["currentPriceId"])), true, current)
if current == "author_monthly" {
monthly++
} else {
annual++
}
if boolean(row["cancel"]) {
cancelling++
}
}
}
}
if err = cursor.Err(); err != nil {
return nil, err
}
timeline := []M{}
if !first.IsZero() {
for d := billingBucket(first, unit); !d.After(now); d = billingNextBucket(d, unit) {
row := series[d]
if row == nil {
row = M{"date": d, "subscription": 0, "repository": 0, "conference": 0}
}
timeline = append(timeline, row)
}
}
planRows := []M{}
for _, id := range order {
p := plans[id]
name := names[id]
if name == "" {
name = id
}
planRows = append(planRows, M{"planId": id, "name": name, "family": billingFamily(id), "active": p.active, "sales": p.period.count, "revenue": p.period.amounts(), "revenueComplete": available && p.period.missing == 0, "allTimeSales": p.all.count, "allTimeRevenue": p.all.amounts(), "allTimeRevenueComplete": available && p.all.missing == 0})
}
reversalPipeline := []M{}
if !since.IsZero() {
reversalPipeline = append(reversalPipeline, M{"$match": M{"createdAt": M{"$gte": since}}})
}
for _, spec := range []struct{ as, local, foreign string }{{"checkout", "_id", "paymentIntentId"}, {"subscription", "subscriptionId", "_id"}} {
reversalPipeline = append(reversalPipeline, M{"$lookup": M{"from": "billinggrants", "localField": spec.local, "foreignField": spec.foreign, "pipeline": []M{{"$match": M{"owner": M{"$type": "string"}}}, {"$limit": 1}}, "as": spec.as}})
}
reversalPipeline = append(reversalPipeline, M{"$match": M{"$or": []M{{"checkout.0": M{"$exists": true}}, {"subscription.0": M{"$exists": true}}}}}, M{"$group": M{"_id": "$reason", "count": M{"$sum": 1}}})
reversals := M{"refunds": int64(0), "disputes": int64(0)}
rc, err := s.Store.DB.Collection("billingrevocations").Aggregate(q.ctx(), reversalPipeline)
if err != nil {
return nil, err
}
var rs []M
if err = rc.All(q.ctx(), &rs); err != nil {
return nil, err
}
for _, r := range rs {
if r["_id"] == "full_refund" {
reversals["refunds"] = r["count"]
}
if r["_id"] == "dispute" {
reversals["disputes"] = r["count"]
}
}
health, err := s.billingWebhookHealth(q)
if err != nil {
return nil, err
}
var reason any
missingSales, missingAll, missingSubs := selected.missing, all.missing, subs.missing
if !available {
reason = "stripe_not_configured"
missingSales, missingAll, missingSubs = 0, 0, 0
}
return M{"period": period, "since": sinceJSON, "now": now, "bucket": unit, "sales": selected.json(available), "allTime": all.json(available), "subscriptions": M{"active": subs.count, "monthly": monthly, "annual": annual, "cancelling": cancelling, "mrr": subs.amounts(), "complete": available && subs.missing == 0}, "reversals": reversals, "plans": planRows, "series": timeline, "revenue": M{"available": available, "reason": reason, "missingSales": missingSales, "missingAllTimeSales": missingAll, "missingSubscriptions": missingSubs, "basis": "list_price"}, "webhooks": health}, nil
}
@@ -17,7 +17,7 @@ func runConferenceOptionsIntegration(t *testing.T, s *Server, token, otherToken
t.Run("conference option casts persist and appear in public output", func(t *testing.T) {
ctx := context.Background()
id := "conference-options"
seed := M{"_id": bson.NewObjectID(), "conferenceID": id, "name": "Original", "status": "ready", "owners": []any{owner}, "repositories": []any{}, "billing": M{"name": "Private payer"}}
seed := M{"_id": bson.NewObjectID(), "conferenceID": id, "name": "Original", "plan": M{"planID": "free_conference"}, "status": "ready", "owners": []any{owner}, "repositories": []any{}, "billing": M{"name": "Private payer"}}
if _, err := s.Store.DB.Collection("conferences").InsertOne(ctx, seed); err != nil {
t.Fatal(err)
}
+95 -7
View File
@@ -1,6 +1,7 @@
package server
import (
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"math"
"strings"
@@ -8,11 +9,74 @@ import (
)
var plans = []M{
{"id": "free_conference", "name": "Free", "pricePerRepo": 0, "storagePerRepo": -1, "description": "<li><strong>Quota is deducted from user account</strong></li>\n <li>No-download</li>\n <li>Conference dashboard</li>"},
{"id": "premium_conference", "name": "Premium", "pricePerRepo": 0.5, "storagePerRepo": 500 * 8 * 1024, "description": "<li>500Mo / repository</li>\n <li>Repository download</li>\n <li>Conference dashboard</li>"},
{"id": "unlimited_conference", "name": "Unlimited", "pricePerRepo": 3, "storagePerRepo": 0, "description": "<li><strong>Unlimited</strong> repository size</li>\n <li>Repository download</li>\n <li>Conference dashboard</li>"},
{"id": "free_conference", "name": "Free", "pricePerRepo": 0, "storagePerRepo": -1, "repositories": 0},
{"id": "conference_workshop", "name": "Workshop", "pricePerRepo": 0, "storagePerRepo": int64(10) << 30, "repositories": 25},
{"id": "conference", "name": "Conference", "pricePerRepo": 0, "storagePerRepo": int64(50) << 30, "repositories": 100},
{"id": "conference_large", "name": "Large conference", "pricePerRepo": 0, "storagePerRepo": int64(200) << 30, "repositories": 400},
}
func (s *Server) offeredConferencePlans() []M {
out := []M{}
if !s.Config.Billing.Enabled {
return []M{{"id": "free_conference", "name": "Free", "pricePerRepo": 0, "storagePerRepo": -1, "repositories": 0, "description": "<li>Uses each author's allowance</li><li>Conference dashboard</li>"}}
}
for _, p := range s.Config.Billing.Plans {
if conferencePlan(p.ID) && p.PriceID != "" {
out = append(out, M{"id": p.ID, "name": p.Name, "pricePerRepo": 0, "storagePerRepo": p.Storage, "repositories": p.Repositories, "description": fmt.Sprintf("<li>Up to %d repositories</li><li>Up to 180 days</li><li>Prepaid at checkout</li>", p.Repositories)})
}
}
return out
}
func (s *Server) validateConferenceChange(body, existing M, now time.Time) (M, error) {
id := str(obj(body["plan"])["planID"])
if existing != nil {
if id != str(obj(existing["plan"])["planID"]) {
return nil, fail("billing_plan_change_not_supported", 400)
}
start, end, err := conferenceFormDates(body)
if err != nil {
return nil, err
}
if conferencePlan(id) && (!start.Equal(date(existing["startDate"])) || !end.Equal(date(existing["endDate"]))) {
return nil, fail("billing_review_window_locked", 400)
}
}
// Reuse the required-field checks; retired plans remain editable.
copy := M{}
for k, v := range body {
copy[k] = v
}
copy["plan"] = M{"planID": "free_conference"}
if _, err := validateConferenceForm(copy, now); err != nil {
return nil, err
}
start, startOK, err := javascriptDateValue(body["startDate"])
if err != nil {
return nil, err
}
end, endOK, err := javascriptDateValue(body["endDate"])
if err != nil {
return nil, err
}
if !startOK || !endOK {
return nil, fail("conf_start_date_invalid", 400)
}
if conferencePlan(id) && end.Sub(start) > 180*24*time.Hour {
return nil, fail("billing_invalid_review_window", 400)
}
for _, p := range s.offeredConferencePlans() {
if p["id"] == id {
return p, nil
}
}
if existing != nil {
return M{}, nil
}
if conferencePlan(id) {
return nil, fail("billing_invalid_review_window", 400)
}
return nil, fail("invalid_plan", 400)
}
func conferenceOwner(q *request, c M) bool {
if q.Identity.Admin {
return true
@@ -108,14 +172,30 @@ func (s *Server) conferences(q *request) (any, error) {
}
}
if q.R.Method == "GET" {
hosting := false
if s.Config.Billing.Enabled && conferencePlan(str(obj(c["plan"])["planID"])) && c["status"] == "ready" && !date(c["startDate"]).After(time.Now()) && date(c["endDate"]).After(time.Now()) {
grants, e := s.Store.list(q.ctx(), "billinggrants", M{"scope": "conference:" + str(c["conferenceID"]), "revoked": false, "until": M{"$gt": time.Now()}}, 0, nil)
if e != nil {
return nil, e
}
for _, g := range grants {
if usableBillingGrant(g, time.Now()) {
hosting = true
break
}
}
}
if !conferenceOwner(q, c) {
return selectFields(c, "conferenceID", "name", "url", "startDate", "endDate", "options"), nil
out := selectFields(c, "conferenceID", "name", "url", "startDate", "endDate", "options")
out["hosting"] = hosting
return out, nil
}
c, err = s.reconcileConference(q.ctx(), c)
if err != nil {
return nil, err
}
out := conferenceJSON(c)
out["hosting"] = hosting
rows, err := s.Store.list(q.ctx(), "anonymizedrepositories", M{"_id": M{"$in": conferenceRepositoryIDs(c)}}, 0, nil)
if err != nil {
return nil, err
@@ -141,7 +221,7 @@ func (s *Server) conferences(q *request) (any, error) {
return q.text("ok"), nil
}
body := q.Body
plan, err := validateConferenceForm(body, time.Now())
plan, err := s.validateConferenceChange(body, c, time.Now())
if err != nil {
return nil, err
}
@@ -156,7 +236,6 @@ func (s *Server) conferences(q *request) (any, error) {
set := selectFields(body, "name", "url")
set["startDate"] = start
set["endDate"] = end
set["status"] = "ready"
options, err := conferenceOptions(body)
if err != nil {
return nil, err
@@ -171,8 +250,11 @@ func (s *Server) conferences(q *request) (any, error) {
set["owners"] = []any{q.User["_id"]}
set["repositories"] = []any{}
set["status"] = "ready"
if conferencePlan(planID) {
set["status"] = "pending_payment"
}
set["dateOfEntry"] = time.Now()
set["plan"] = M{"planID": planID, "pricePerRepository": plan["pricePerRepo"], "quota": M{"size": plan["storagePerRepo"], "file": 0, "repository": 0}}
set["plan"] = M{"planID": planID, "pricePerRepository": plan["pricePerRepo"], "quota": M{"size": plan["storagePerRepo"], "file": 0, "repository": plan["repositories"]}}
if body["billing"] != nil {
set["billing"] = selectFields(obj(body["billing"]), "name", "email", "address", "address2", "city", "zip", "country", "vat")
}
@@ -245,6 +327,12 @@ func validateConferenceForm(body M, now time.Time) (M, error) {
if plan == nil {
return nil, fail("invalid_plan", 400)
}
if !startOK || !endOK {
return nil, fail("conf_start_date_invalid", 400)
}
if conferencePlan(str(plan["id"])) && end.Sub(start) > 180*24*time.Hour {
return nil, fail("billing_invalid_review_window", 400)
}
if decimal(plan["pricePerRepo"]) > 0 {
if !inputTruthy(body["billing"]) {
return nil, fail("billing_missing", 400)
@@ -14,7 +14,7 @@ import (
)
func runConferenceFormIntegration(t *testing.T, s *Server, token, otherToken string, owner any) {
t.Run("conference forms preserve history and restore status", func(t *testing.T) {
t.Run("conference edits preserve history and status", func(t *testing.T) {
ctx := context.Background()
call := func(method, id, auth string, body M) *httptest.ResponseRecorder {
raw, _ := json.Marshal(body)
@@ -56,13 +56,14 @@ func runConferenceFormIntegration(t *testing.T, s *Server, token, otherToken str
t.Fatal(err)
}
checkError(call("POST", id, otherToken, M{}), 401, "not_authorized")
checkError(call("POST", id, token, M{}), 400, "conf_name_missing")
checkError(call("POST", id, token, M{}), 400, "billing_plan_change_not_supported")
body := valid()
body["plan"] = M{"planID": "unknown"}
checkError(call("POST", id, token, body), 400, "invalid_plan")
checkError(call("POST", id, token, body), 400, "billing_plan_change_not_supported")
body = valid()
body["plan"] = M{"planID": "premium_conference"}
checkError(call("POST", id, token, body), 400, "billing_missing")
body["name"] = ""
checkError(call("POST", id, token, body), 400, "conf_name_missing")
after, err := s.Store.one(ctx, "conferences", M{"conferenceID": id})
if err != nil {
t.Fatal(err)
@@ -71,6 +72,7 @@ func runConferenceFormIntegration(t *testing.T, s *Server, token, otherToken str
t.Fatal("rejected edit mutated conference")
}
body = valid()
body["plan"] = M{"planID": "premium_conference"}
body["billing"] = M{"name": "Ignored payer"}
w := call("POST", id, token, body)
if w.Code != 200 || w.Body.String() != "ok" {
@@ -80,7 +82,7 @@ func runConferenceFormIntegration(t *testing.T, s *Server, token, otherToken str
if err != nil {
t.Fatal(err)
}
if after["status"] != "ready" || after["name"] != "Updated" {
if after["status"] != status || after["name"] != "Updated" {
t.Fatal(after)
}
for _, field := range []string{"_id", "conferenceID", "owners", "repositories", "plan", "billing"} {
+15 -1
View File
@@ -15,6 +15,9 @@ import (
)
type Config struct {
ReviewKeys *string
Billing BillingConfig
EmailAPIKey, EmailFrom string
GitHubPermissionTTL time.Duration
SharedCacheDecisions bool
SharedResultBytes int64
@@ -53,7 +56,18 @@ func envInt(key string, fallback int) int {
return v
}
func LoadConfig() (Config, error) {
c := Config{CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)}
c := Config{EmailAPIKey: os.Getenv("RESEND_API_KEY"), EmailFrom: os.Getenv("EMAIL_FROM"), CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)}
if raw, ok := os.LookupEnv("REVIEW_SERVICE_KEYS"); ok {
c.ReviewKeys = &raw
}
if _, err := parseReviewRegistry(c.ReviewKeys); err != nil {
return c, err
}
var billingErr error
c.Billing, billingErr = loadBillingConfig()
if billingErr != nil {
return c, billingErr
}
if raw, ok := os.LookupEnv("GITHUB_PERMISSION_CACHE_SECONDS"); ok {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 0 || seconds > 3600 {
+13 -2
View File
@@ -50,7 +50,7 @@ func (s *Server) connections(q *request) (any, error) {
return nil, e
}
installations := []M{}
out := M{"csrf": q.Session["githubConnectionCSRF"], "appEnabled": s.Config.AppEnabled && s.Config.AppNewConnections, "oauthEnabled": s.Config.OAuthEnabled, "oauthConnected": oauthToken != "", "appConnected": app, "gistConnection": "oauth"}
out := M{"notificationEmail": accountNotificationEmail(q.User), "emailNotificationsEnabled": s.Config.EmailAPIKey != "" && s.Config.EmailFrom != "", "csrf": q.Session["githubConnectionCSRF"], "appEnabled": s.Config.AppEnabled && s.Config.AppNewConnections, "oauthEnabled": s.Config.OAuthEnabled, "oauthConnected": oauthToken != "", "appConnected": app, "gistConnection": "oauth"}
if seenApp && s.Config.AppEnabled {
out["gistConnection"] = "github-app"
}
@@ -354,10 +354,21 @@ func (s *Server) revokeGrant(ctx context.Context, owner any, provider string) er
return e
}
func (s *Server) deleteAccount(q *request) (any, error) {
if err := s.cancelAccountBilling(q.ctx(), q.Identity.ID); err != nil {
return nil, err
}
finish, err := s.beginAlertDeactivation(q.ctx(), q.User["_id"])
if err != nil {
return nil, err
}
defer finish()
if err := s.removeAccountResources(q); err != nil {
return nil, err
}
owner := q.User["_id"]
if _, err = s.Store.DB.Collection("billingdrafts").DeleteMany(q.ctx(), M{"owner": q.Identity.ID}); err != nil {
return nil, err
}
// Removed records remain as tombstones and may still carry legacy credentials.
for _, kind := range []string{"repo", "pr", "gist"} {
if _, err := s.Store.DB.Collection(collection(kind)).UpdateMany(q.ctx(), M{"owner": owner}, M{"$unset": M{"source.accessToken": "", "accessToken": ""}}); err != nil {
@@ -376,7 +387,7 @@ func (s *Server) deleteAccount(q *request) (any, error) {
if _, err := s.Store.DB.Collection("dashboardnames").DeleteMany(q.ctx(), M{"owner": owner}); err != nil {
return nil, err
}
_, err := s.Store.update(q.ctx(), "users", M{"_id": owner}, M{"$inc": M{"repositoryDiscoveryRevision": 1}, "$set": M{"status": "removed", "username": "deleted-" + str(owner), "emails": []any{}, "apiTokens": []any{}, "repositories": []any{}}, "$unset": M{"accessTokens": "", "accessTokenDates": "", "externalIDs": "", "photo": "", "default": "", "projectNames": ""}})
_, err = s.Store.update(q.ctx(), "users", M{"_id": owner}, M{"$inc": M{"repositoryDiscoveryRevision": 1}, "$set": M{"status": "removed", "username": "deleted-" + str(owner), "emails": []any{}, "apiTokens": []any{}, "repositories": []any{}}, "$unset": M{"accessTokens": "", "accessTokenDates": "", "externalIDs": "", "photo": "", "default": "", "projectNames": "", "notificationEmail": "", "emailPromptNever": "", "accessAlertAfter": ""}})
if err != nil {
return nil, err
}
+17
View File
@@ -18,6 +18,23 @@ func (s *Server) extendResource(ctx context.Context, kind string, r M) (M, error
base = now
}
next := base.In(time.Local).AddDate(0, 6, 0)
if kind == "repo" && s.Config.Billing.Enabled {
maximum, err := s.billingMaximumExpiration(ctx, str(r["owner"]), str(r["repoId"]), str(r["conference"]), now)
if err != nil {
return nil, err
}
if next.After(maximum) {
next = maximum
}
if !next.After(base) {
return nil, fail("expiration_limit_reached", 402)
}
if str(r["status"]) == "expired" {
if err := s.billingConferenceAdmission(ctx, str(r["owner"]), str(r["repoId"]), str(r["conference"])); err != nil {
return nil, err
}
}
}
set := M{"options.expirationDate": next}
if kind == "repo" {
set["settingsSavedAt"] = now
+25 -5
View File
@@ -43,6 +43,9 @@ func scriptableFile(name string) bool {
}
func textFile(name string, sample []byte) bool { return filetype.Text(name, sample) }
func (s *Server) blob(ctx context.Context, r, row M) (io.ReadCloser, error) {
if err := s.assertFileOrigin(ctx, row); err != nil {
return nil, err
}
if number(row["size"]) > anonymize.MaxInput {
return nil, fail("file_too_big", 413)
}
@@ -57,12 +60,15 @@ func (s *Server) blob(ctx context.Context, r, row M) (io.ReadCloser, error) {
return nil, e
}
}
return s.cachedBlob(ctx, r, p, a, provider.Entry{Path: path.Join(str(row["path"]), str(row["name"])), Revision: str(row["sha"]), Size: number(row["size"])})
return s.cachedBlob(ctx, r, p, a, fileProviderEntry(row))
}
func (s *Server) transformed(ctx context.Context, r, row M) (io.Reader, func(), bool, error) {
return s.transformedResponse(ctx, r, row, nil)
}
func (s *Server) transformedResponse(ctx context.Context, r, row M, response *sharedResponse) (io.Reader, func(), bool, error) {
if err := s.assertFileOrigin(ctx, row); err != nil {
return nil, nil, false, err
}
var body io.ReadCloser
var err error
if s.sourceCache != nil && number(row["size"]) <= anonymize.MaxInput {
@@ -71,7 +77,7 @@ func (s *Server) transformedResponse(ctx context.Context, r, row M, response *sh
return nil, nil, false, accessErr
}
if a.Ref.Provider != "archive" {
entry := provider.Entry{Path: path.Join(str(row["path"]), str(row["name"])), Revision: str(row["sha"]), Size: number(row["size"])}
entry := fileProviderEntry(row)
if _, err = security.RelativePath(entry.Path); err == nil {
body, err = s.sharedSourceRead(ctx, r, p, a, entry, true)
}
@@ -109,7 +115,7 @@ func (s *Server) transformBody(ctx context.Context, r, row M, body io.ReadCloser
name := str(row["name"])
isText := textFile(name, sample)
if source, ok := body.(*blobcache.Reader); ok && s.resultCache != nil {
opt, err := s.anonymizerOptions(r, "repo")
opt, err := s.fileAnonymizerOptions(r, row)
if err != nil {
body.Close()
return nil, nil, isText, err
@@ -150,7 +156,7 @@ func (s *Server) transformBody(ctx context.Context, r, row M, body io.ReadCloser
}
return file, cleanup, false, nil
}
opt, err := s.anonymizerOptions(r, "repo")
opt, err := s.fileAnonymizerOptions(r, row)
if err != nil {
body.Close()
return nil, nil, false, err
@@ -202,6 +208,12 @@ func (s *Server) file(q *request) (any, error) {
if selected == nil {
return nil, fail("file_not_found", 404)
}
if selected["size"] == nil || str(selected["submodule"]) != "" {
return nil, fail("folder_not_supported", 404)
}
if err = s.assertFileOrigin(q.ctx(), selected); err != nil {
return nil, err
}
name := str(selected["name"])
if !fileAllowed(name, obj(r["options"])) {
return nil, fail("file_not_supported", 403)
@@ -341,7 +353,7 @@ func (s *Server) zip(q *request) (any, error) {
// Consume bounded metadata batches instead of retaining the entire tree.
// No limit: a successful ZIP must contain every eligible file.
rows, err := s.Store.DB.Collection("files").Find(q.ctx(), M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r), "size": M{"$ne": nil}},
options.Find().SetBatchSize(128).SetProjection(M{"_id": 0, "path": 1, "name": 1, "size": 1, "sha": 1}))
options.Find().SetBatchSize(128).SetProjection(M{"_id": 0, "path": 1, "name": 1, "size": 1, "sha": 1, "upstream": 1, "submodule": 1}))
if err != nil {
return nil, err
}
@@ -520,3 +532,11 @@ func (s *Server) sourceRepository(mode string) handler {
func (s *Server) authorizeContent(ctx context.Context, r M) (string, error) {
return "", s.authorizeSource(ctx, r)
}
func (s *Server) fileAnonymizerOptions(r, row M) (anonymize.Options, error) {
opt, err := s.anonymizerOptions(r, "repo")
if err == nil && anonymize.PreservedPath(path.Join(str(row["path"]), str(row["name"])), opt.PreserveFiles) {
opt.Terms = []string{}
}
return opt, err
}
+36 -2
View File
@@ -46,6 +46,8 @@ type route struct {
handler handler
}
type Server struct {
ownerAlertSlots chan struct{}
review *reviewRegistry
webFiles webFileCache
permissions permissionCache
publicStats publicStatsState
@@ -110,11 +112,15 @@ func (q *request) redirect(s string) any {
type written struct{}
func New(c Config, store *Store, extensions ...provider.Provider) (*Server, error) {
review, err := parseReviewRegistry(c.ReviewKeys)
if err != nil {
return nil, err
}
root, err := os.OpenRoot(c.PublicDir)
if err != nil {
return nil, errors.New("public_directory_unavailable")
}
s := &Server{Config: c, Store: store, public: root, started: time.Now(), HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error {
s := &Server{ownerAlertSlots: make(chan struct{}, 16), review: review, Config: c, Store: store, public: root, started: time.Now(), HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return errors.New("too_many_redirects")
}
@@ -126,6 +132,13 @@ func New(c Config, store *Store, extensions ...provider.Provider) (*Server, erro
}
return nil
}}}
initCtx, initCancel := context.WithTimeout(context.Background(), 2*time.Minute)
initErr := s.initializeOwnerAlerts(initCtx)
initCancel()
if initErr != nil {
root.Close()
return nil, initErr
}
binary, err := os.Executable()
if err != nil {
root.Close()
@@ -254,6 +267,23 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeError(w, fail("server_error", 500))
}
}()
if r.URL.Path == "/service" || strings.HasPrefix(r.URL.Path, "/service/") {
s.reviewCapabilities(w, r)
return
}
if reviewConsentPath(r.URL.Path) {
s.reviewConsentPage(w, r)
return
}
if strings.TrimSuffix(r.URL.Path, "/") == "/api/billing/webhook" {
result, err := s.billingWebhook(&request{W: w, R: r, Server: s})
if err != nil {
writeError(w, err)
} else {
writeJSON(w, result)
}
return
}
if r.URL.Path == "/github/app/webhook" {
s.webhook(w, r)
return
@@ -305,7 +335,11 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if r.Body != nil && r.ContentLength != 0 && (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" || r.Method == "DELETE") {
if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 100*1024))
limit := int64(100 * 1024)
if r.URL.Path == "/api/anonymize-preview" {
limit = 3 * 1024 * 1024
}
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
if err := d.Decode(&q.Body); err != nil {
writeError(w, fail("invalid_request", 400))
return
+6 -1
View File
@@ -18,12 +18,17 @@ func (s *Store) ensureIndexes(ctx context.Context) error {
}
}
indexes := map[string][]mongo.IndexModel{
"billinggrants": {{Keys: bson.D{{Key: "owner", Value: 1}}}, {Keys: bson.D{{Key: "scope", Value: 1}, {Key: "until", Value: 1}}}, {Keys: bson.D{{Key: "paymentIntentId", Value: 1}}}},
"billingaccounts": {{Keys: bson.D{{Key: "reconcileAfter", Value: 1}}}},
"billingevents": {{Keys: bson.D{{Key: "state", Value: 1}, {Key: "nextAttemptAt", Value: 1}}}},
"billingdrafts": {{Keys: bson.D{{Key: "expiresAt", Value: 1}}, Options: options.Index().SetExpireAfterSeconds(0)}},
"gocachemetrics": {{Keys: bson.D{{Key: "period", Value: 1}, {Key: "bucket", Value: 1}}}, {Keys: bson.D{{Key: "expires", Value: 1}}, Options: options.Index().SetExpireAfterSeconds(0)}},
"anonymizedrepositories": {{Keys: bson.D{{Key: "conferenceMembership.id", Value: 1}}, Options: options.Index().SetSparse(true)}},
"users": {{Keys: bson.D{{Key: "username", Value: 1}}, Options: options.Index().SetUnique(true)}, {Keys: bson.D{{Key: "externalIDs.github", Value: 1}}}, {Keys: bson.D{{Key: "apiTokens.tokenHash", Value: 1}}}},
"repositories": {{Keys: bson.D{{Key: "externalId", Value: 1}}, Options: options.Index().SetUnique(true)}},
"githubinstallations": {{Keys: bson.D{{Key: "appId", Value: 1}, {Key: "installationId", Value: 1}}, Options: options.Index().SetUnique(true)}},
"files": {{Keys: bson.D{{Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}, {Key: "path", Value: 1}, {Key: "name", Value: 1}}}, {Keys: bson.D{{Key: "metadataPending", Value: 1}, {Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}}, Options: options.Index().SetPartialFilterExpression(M{"metadataPending": true})}},
"files": {{Keys: bson.D{{Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}, {Key: "submodule", Value: 1}}, Options: options.Index().SetName("file_submodule_status").SetPartialFilterExpression(M{"submodule": M{"$exists": true}})}, {Keys: bson.D{{Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}, {Key: "path", Value: 1}, {Key: "name", Value: 1}}}, {Keys: bson.D{{Key: "metadataPending", Value: 1}, {Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}}, Options: options.Index().SetPartialFilterExpression(M{"metadataPending": true})}},
"gojobs": {{Keys: bson.D{{Key: "state", Value: 1}, {Key: "priority", Value: 1}, {Key: "availableAt", Value: 1}, {Key: "queueOrder", Value: 1}, {Key: "createdAt", Value: 1}, {Key: "_id", Value: 1}}}, {Keys: bson.D{{Key: "kind", Value: 1}, {Key: "resourceId", Value: 1}, {Key: "action", Value: 1}, {Key: "state", Value: 1}}}, {Keys: bson.D{{Key: "state", Value: 1}, {Key: "availableAt", Value: 1}}}, {Keys: bson.D{{Key: "state", Value: 1}, {Key: "leaseUntil", Value: 1}}}, {Keys: bson.D{{Key: "action", Value: 1}, {Key: "state", Value: 1}, {Key: "createdAt", Value: -1}}}},
"dashboardnames": {{Keys: bson.D{{Key: "owner", Value: 1}, {Key: "type", Value: 1}, {Key: "artifactId", Value: 1}}, Options: options.Index().SetUnique(true)}},
"dailystats": {{Keys: bson.D{{Key: "date", Value: 1}}, Options: options.Index().SetUnique(true)}},
@@ -0,0 +1,37 @@
package server
import (
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"os"
"strings"
"testing"
)
func TestExistingNodeSubmoduleIndex(t *testing.T) {
uri := os.Getenv("GO_TEST_MONGODB_URI")
if uri == "" {
t.Skip("requires disposable MongoDB")
}
if !strings.HasPrefix(uri, "mongodb://127.0.0.1:") {
t.Fatal("requires local disposable MongoDB")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
t.Fatal(err)
}
defer client.Disconnect(t.Context())
db := client.Database("index_compatibility_test_" + bson.NewObjectID().Hex())
defer db.Drop(t.Context())
_, err = db.Collection("files").Indexes().CreateOne(t.Context(), mongo.IndexModel{Keys: bson.D{{Key: "repoId", Value: 1}, {Key: "treeGeneration", Value: 1}, {Key: "submodule", Value: 1}}, Options: options.Index().SetName("file_submodule_status").SetPartialFilterExpression(M{"submodule": M{"$exists": true}})})
if err != nil {
t.Fatal(err)
}
store := &Store{DB: db}
for i := 0; i < 2; i++ {
if err := store.ensureIndexes(t.Context()); err != nil {
t.Fatal(err)
}
}
}
@@ -129,6 +129,8 @@ func TestBackendIntegration(t *testing.T) {
server.ServeHTTP(w, req)
return w
}
t.Run("owner notification lifecycle", func(t *testing.T) { runOwnerAlertsIntegration(t, server) })
t.Run("billing lifecycle", func(t *testing.T) { runBillingIntegration(t, server) })
t.Run("second provider lifecycle", func(t *testing.T) { runProviderIntegration(t, server, fakeProvider, call, token, otherToken) })
t.Run("public statistics cache", func(t *testing.T) { runPublicStatsIntegration(t, server) })
t.Run("overview rolling activity counts", func(t *testing.T) { runOverviewIntegration(t, server) })
+21 -1
View File
@@ -49,6 +49,9 @@ func (s *Server) RunJobs(ctx context.Context) {
s.removalRecoveryPending.Store(true)
s.recoverImportedRemovalJobs(ctx)
var workers sync.WaitGroup
if s.Config.Billing.Enabled {
workers.Go(func() { s.runBillingMaintenance(ctx) })
}
for _, queue := range workerQueues {
for i := 0; i < queue.concurrency; i++ {
workers.Go(func() { s.jobLoop(ctx, queue.name) })
@@ -134,6 +137,9 @@ func (s *Server) runJob(ctx context.Context, job M) (jobErr error) {
}
if action == "prepare" {
defer func() {
if jobErr != nil {
_ = s.notifyOwnerAccessProblem(ctx, kind, r, providerFailure(jobErr))
}
if jobErr == nil {
return
}
@@ -236,7 +242,7 @@ func (s *Server) prepareTree(ctx context.Context, r M) error {
if f.Size < 0 {
return fail("invalid_file_size", 422)
}
entries = append(entries, M{"path": f.Path, "sha": f.Revision, "size": f.Size, "type": kind})
entries = append(entries, M{"path": f.Path, "sha": f.Revision, "size": f.Size, "type": kind, "upstream": originDocument(f.Origin), "submodule": f.Submodule})
}
generation, err := security.RandomToken()
if err != nil {
@@ -263,12 +269,23 @@ func (s *Server) prepareTree(ctx context.Context, r M) error {
}
dir, name := path.Split(p)
row := M{"repoId": r["repoId"], "treeGeneration": generation, "treeStaged": true, "name": name, "path": strings.TrimSuffix(dir, "/"), "sha": item["sha"]}
if item["upstream"] != nil && len(obj(item["upstream"])) > 0 {
row["upstream"] = item["upstream"]
}
if str(item["submodule"]) != "" {
row["submodule"] = item["submodule"]
}
if kind == "blob" {
row["size"] = number(item["size"])
total += number(item["size"])
}
rows = append(rows, row)
}
if boolean(r["billingManaged"]) {
if err := s.reserveBillingRepository(ctx, str(r["owner"]), str(r["repoId"]), total, str(r["conference"]), "", 0); err != nil {
return err
}
}
if len(rows) > 0 {
if _, err = s.Store.DB.Collection("files").InsertMany(ctx, rows); err != nil {
return err
@@ -320,6 +337,9 @@ func (s *Server) prepareEmbedded(ctx context.Context, kind string, r M) error {
return nil
}
func (s *Server) maintenance(ctx context.Context) {
if err := s.reconcileBillingExpiration(ctx); err != nil {
s.recordError(ctx, err)
}
s.recoverImportedRemovalJobs(ctx)
if s.pool != nil {
s.pool.PruneResults()
@@ -0,0 +1,215 @@
package server
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/tdurieux/anonymous_github/backend/internal/provider"
"go.mongodb.org/mongo-driver/v2/bson"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestBillingSignature(t *testing.T) {
now := time.Unix(1800000000, 0)
body := []byte(`{"id":"evt_fixture"}`)
sign := func(at time.Time) string {
stamp := fmt.Sprint(at.Unix())
mac := hmac.New(sha256.New, []byte("synthetic-secret"))
mac.Write([]byte(stamp + "."))
mac.Write(body)
return "t=" + stamp + ",v1=" + hex.EncodeToString(mac.Sum(nil))
}
if !stripeSignature(body, sign(now), "synthetic-secret", now) {
t.Fatal("valid signature rejected")
}
for _, tc := range []struct {
body []byte
header, secret string
}{{append(append([]byte{}, body...), ' '), sign(now), "synthetic-secret"}, {body, sign(now.Add(-301 * time.Second)), "synthetic-secret"}, {body, sign(now.Add(301 * time.Second)), "synthetic-secret"}, {body, sign(now), ""}, {body, sign(now), "wrong"}} {
if stripeSignature(tc.body, tc.header, tc.secret, now) {
t.Fatal("invalid signature accepted")
}
}
if !stripeSignature(body, sign(now)+",v1=bad", "synthetic-secret", now) {
t.Fatal("rotation signature rejected")
}
}
func TestStripePersistedParameters(t *testing.T) {
params := M{"line_items": []M{{"price": "price_fixture", "quantity": 1}}, "metadata": M{"owner": "synthetic"}, "payment_method_types": []string{"card"}, "automatic_tax": M{"enabled": true}}
before := stripeValues(params).Encode()
encoded, err := bson.Marshal(params)
if err != nil {
t.Fatal(err)
}
var restored M
if err = bson.Unmarshal(encoded, &restored); err != nil {
t.Fatal(err)
}
if after := stripeValues(restored).Encode(); before != after {
t.Fatalf("persisted retry changes parameters: %s != %s", before, after)
}
}
func TestConferencePaymentLifecycle(t *testing.T) {
now := time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
start, end := now.Add(time.Hour), now.Add(24*time.Hour)
s := &Server{Config: Config{Billing: BillingConfig{Enabled: true, Plans: []BillingPlan{{ID: "conference", PriceID: "price_fixture", Storage: 100, Repositories: 10}}}}}
body := M{"name": "Test", "conferenceID": "fixture", "startDate": start, "endDate": end, "plan": M{"planID": "conference"}}
if _, err := s.validateConferenceChange(body, nil, now); err != nil {
t.Fatal(err)
}
previous := M{"plan": M{"planID": "conference"}, "startDate": start, "endDate": end, "status": "pending_payment"}
body["endDate"] = end.Add(time.Hour)
if _, err := s.validateConferenceChange(body, previous, now); err == nil {
t.Fatal("paid review window changed")
}
body["endDate"] = end
body["plan"] = M{"planID": "free_conference"}
if _, err := s.validateConferenceChange(body, nil, now); err == nil {
t.Fatal("free conference created with billing enabled")
}
if _, err := s.validateConferenceChange(body, previous, now); err == nil {
t.Fatal("existing plan changed")
}
}
func TestReviewCapabilitiesSecurity(t *testing.T) {
client, token := strings.Repeat("a", 32), strings.Repeat("b", 64)
digest := sha256.Sum256([]byte(token))
raw, _ := json.Marshal(M{"version": 1, "keys": []M{{"clientId": client, "keyId": "rotation-1", "tokenSHA256": hex.EncodeToString(digest[:]), "notBefore": "2020-01-01T00:00:00Z", "notAfter": "2099-01-01T00:00:00Z"}}})
value := string(raw)
registry, err := parseReviewRegistry(&value)
if err != nil {
t.Fatal(err)
}
s := &Server{review: registry}
request := func(path string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", path, nil)
r.Header.Set("X-4open-artifact-client-id", client)
r.Header.Set("X-4open-artifact-service-key-id", "rotation-1")
r.Header.Set("Authorization", "Bearer "+token)
w := httptest.NewRecorder()
s.reviewCapabilities(w, r)
return w
}
if w := request("/service/v1/capabilities"); w.Code != 200 || !strings.Contains(w.Body.String(), `"available":[]`) {
t.Fatal(w.Code, w.Body.String())
}
if w := request("/service/v1/capabilities?token=ignored"); w.Code != 404 {
t.Fatal("query accepted", w.Code)
}
for _, header := range []string{"Cookie", "Origin", "Sec-Fetch-Site"} {
r := httptest.NewRequest("GET", "/service/v1/capabilities", nil)
r.Header.Set(header, "")
w := httptest.NewRecorder()
s.reviewCapabilities(w, r)
if w.Code != 403 {
t.Fatal(header, w.Code)
}
}
for i := 1; i < 60; i++ {
if w := request("/service/v1/capabilities"); w.Code != 200 {
t.Fatal("early limit", i, w.Code)
}
}
if w := request("/service/v1/capabilities"); w.Code != 429 {
t.Fatal("rate limit missing", w.Code)
}
}
func TestBillingMonthlyRevenueAndBuckets(t *testing.T) {
total := billingTotals{}
total.add(M{"unit_amount": 1200, "currency": "eur", "recurring": M{"interval": "year", "interval_count": 1}}, true, "author_annual")
total.add(nil, true, "author_monthly")
if total.count != 2 || total.missing != 1 || total.amounts()["eur"] != float64(100) {
t.Fatal(total)
}
sunday := time.Date(2026, 11, 15, 16, 0, 0, 0, time.UTC)
if got := billingBucket(sunday, "week"); got.Day() != 9 || got.Hour() != 0 {
t.Fatal(got)
}
}
type previewFixture struct {
*fixtureProvider
previews int
}
func (p *previewFixture) PreviewTree(ctx context.Context, a provider.Access, limit int) ([]provider.Entry, bool, error) {
p.previews++
return []provider.Entry{{Path: "refs.bib"}, {Path: "photo.png"}, {Path: ".gitmodules"}, {Path: "../secret"}}, false, nil
}
func (p *previewFixture) PreviewFile(ctx context.Context, a provider.Access, path string, limit int64) ([]byte, int64, bool, error) {
p.previews++
return []byte("hello Alice"), 11, false, nil
}
func TestProviderSourcePreview(t *testing.T) {
p := &previewFixture{fixtureProvider: &fixtureProvider{name: "team/subgroup/project", commit: "opaque:revision"}}
registry, err := provider.New(p)
if err != nil {
t.Fatal(err)
}
s := &Server{providers: registry}
owner := bson.NewObjectID()
q := &request{R: httptest.NewRequest("GET", "/api/providers/fixture/repository/tree?repository=team/subgroup/project&commit=opaque:revision", nil), W: httptest.NewRecorder(), User: M{"_id": owner}, Params: map[string]string{"provider": p.ID()}, Server: s}
result, err := s.sourcePreview(q)
if err != nil {
t.Fatal(err)
}
data := obj(result)
if len(arr(data["files"])) != 1 || len(arr(data["binaryFiles"])) != 1 {
t.Fatal(result)
}
p.revoked = true
if _, err = s.sourcePreview(q); err == nil || p.previews != 1 {
t.Fatal("revocation bypassed", err, p.previews)
}
p.revoked = false
q.R = httptest.NewRequest("GET", "/api/providers/fixture/repository/file?repository=team/subgroup/project&commit=opaque:revision&path=../private", nil)
if _, err = s.sourcePreview(q); err == nil || p.previews != 1 {
t.Fatal("unsafe path reached provider", err)
}
}
func TestSubmoduleExpansionDoesNotShareCredentials(t *testing.T) {
sha := strings.Repeat("a", 40)
requests := 0
s := &Server{HTTP: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
requests++
var result M
switch r.URL.Path {
case "/repos/parent/project/contents/vendor":
if r.Header.Get("Authorization") != "Bearer parent-secret" {
t.Fatal("parent metadata lost authorization")
}
result = M{"sha": sha, "submodule_git_url": "../dependency.git"}
case "/repos/parent/dependency/git/trees/" + sha:
if r.Header.Get("Authorization") != "" {
t.Fatal("parent credential leaked to child")
}
result = M{"tree": []M{{"type": "blob", "path": "readme.md", "sha": sha, "size": 10}, {"type": "blob", "path": ".gitmodules", "sha": sha, "size": 10}, {"type": "commit", "path": "nested", "sha": sha}}}
default:
t.Fatal("unexpected path", r.URL.Path)
}
raw, _ := json.Marshal(result)
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
})}}
g := &githubProvider{server: s}
entries, err := g.expandSubmodules(t.Context(), provider.Access{Ref: provider.Ref{Name: "parent/project", Commit: sha}}, "parent-secret", []provider.Entry{{Path: ".gitmodules"}, {Path: "vendor", Revision: sha, Directory: true, Submodule: "unsupported"}})
if err != nil || len(entries) != 3 || requests != 2 {
t.Fatal(entries, requests, err)
}
if entries[0].Submodule != "included" || entries[1].Origin == nil || entries[1].Origin.Repository != "parent/dependency" || entries[2].Submodule != "nested" {
t.Fatal(entries)
}
for _, raw := range []string{"https://evil.test/org/repo", "https://github.com:8443/org/repo", "https://user@github.com/org/repo", "https://github.com/org/repo?secret=x", "file:///etc/passwd", "https://github.com/org/../repo"} {
if submoduleRepository(raw, "parent/project") != "" {
t.Fatal("unsafe submodule URL accepted", raw)
}
}
}
@@ -36,6 +36,8 @@ func runOAuthCallbackIntegration(t *testing.T, s *Server, token string) {
case "github.com/login/oauth/access_token":
exchanges++
value = M{"access_token": "synthetic-callback-access", "refresh_token": "synthetic-callback-refresh", "expires_in": 3600, "refresh_token_expires_in": 7200}
case "api.github.com/user/emails":
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("[]"))}, nil
case "api.github.com/user":
profiles++
value = M{"id": profileID, "login": "oauth-callback-fixture", "avatar_url": "https://avatar.test/image"}
@@ -28,6 +28,9 @@ func runOAuthInstallIntegration(t *testing.T, base *Server) {
}
calls := 0
s.HTTP = &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/user/emails" {
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("[]"))}, nil
}
calls++
data := M{}
switch r.URL.Path {
+346
View File
@@ -0,0 +1,346 @@
package server
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/v2/mongo"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const recipientAlerts = "owner_access_alert_recipients"
func alertRecipientKey(email string) string {
sum := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email))))
return hex.EncodeToString(sum[:])
}
func ownerAccessFailure(err error) bool {
var api *APIError
if !errors.As(err, &api) || api.Status == 429 || api.Status >= 500 {
return false
}
switch api.Code {
case "token_expired", "github_oauth_required", "github_app_reconnect_required", "github_app_access_required", "repo_not_found", "repository_not_found", "file_not_accessible", "file_not_found", "pull_request_not_found", "gist_not_found", "repo_not_accessible", "repo_access_limited", "repo_saml_enforcement":
return true
}
return false
}
func alertResourceKind(kind string) string {
switch kind {
case "repo":
return "repository"
case "pr":
return "pull-request"
}
return kind
}
// Preserve recipient guards across the Node/Go cutover, including delivery
// evidence whose original account or repository has since been deleted.
func (s *Server) initializeOwnerAlerts(ctx context.Context) error {
if s.Config.EmailAPIKey == "" || s.Config.EmailFrom == "" {
return nil
}
if err := s.recoverUnsentOwnerAlerts(ctx, ""); err != nil {
return err
}
events, err := s.Store.DB.Collection("owner_access_alert_events").Find(ctx, M{"state": M{"$in": []string{"accepted", "failed"}}, "completedAt": M{"$exists": true}})
if err != nil {
return err
}
defer events.Close(ctx)
for events.Next(ctx) {
var event M
if err = events.Decode(&event); err != nil {
return err
}
key := str(event["recipientKey"])
if len(key) != 64 {
continue
}
if err = s.billingUpsert(ctx, recipientAlerts, M{"_id": key}, M{"$setOnInsert": M{"state": "recipient_notified", "attemptId": event["attemptId"], "claimedAt": event["completedAt"], "completedAt": event["completedAt"]}}); err != nil {
return err
}
}
if err = events.Err(); err != nil {
return err
}
for _, kind := range []string{"repo", "pr", "gist"} {
cursor, err := s.Store.DB.Collection(collection(kind)).Find(ctx, M{"accessAlertClaimedAt": M{"$exists": true}})
if err != nil {
return err
}
for cursor.Next(ctx) {
var row M
if err = cursor.Decode(&row); err != nil {
cursor.Close(ctx)
return err
}
owner, err := s.Store.one(ctx, "users", M{"_id": row["owner"]})
if err != nil {
cursor.Close(ctx)
return err
}
email := accountNotificationEmail(owner)
if email == "" || !identity(owner).Active() {
continue
}
claim := M{"owner": row["owner"], "resourceKind": alertResourceKind(kind), "resourceId": row["_id"], "generation": row["accessAlertGeneration"], "recovered": false}
err = s.billingUpsert(ctx, recipientAlerts, M{"_id": alertRecipientKey(email)}, M{"$setOnInsert": M{"state": "legacy", "owner": row["owner"], "resourceKind": alertResourceKind(kind), "resourceId": row["_id"], "generation": row["accessAlertGeneration"], "attemptId": uuid.NewString(), "claimedAt": row["accessAlertClaimedAt"]}, "$addToSet": M{"legacyClaims": claim}})
if err != nil {
cursor.Close(ctx)
return err
}
}
err = cursor.Err()
cursor.Close(ctx)
if err != nil {
return err
}
}
return nil
}
func (s *Server) resetOwnerAlerts(ctx context.Context, owner any, kind string, id any) error {
// Every dispatch commits against this revision on the owner document.
if _, err := s.Store.update(ctx, "users", M{"_id": owner}, M{"$inc": M{"accessAlertResetRevision": 1}}); err != nil {
return err
}
kinds := []string{kind}
if kind == "" {
kinds = []string{"repo", "pr", "gist"}
}
for _, k := range kinds {
filter := M{"owner": owner}
if id != nil {
filter["_id"] = id
}
if _, err := s.Store.DB.Collection(collection(k)).UpdateMany(ctx, filter, M{"$set": M{"accessAlertGeneration": uuid.NewString()}, "$unset": M{"accessAlertClaimedAt": 1, "accessAlertAttemptId": 1}}); err != nil {
return err
}
}
return nil
}
func (s *Server) scheduleOwnerAlert(owner, repoID string, err error) {
if s.Config.EmailAPIKey == "" || s.Config.EmailFrom == "" || !ownerAccessFailure(err) || repoID == "" || s.ownerAlertSlots == nil {
return
}
select {
case s.ownerAlertSlots <- struct{}{}:
default:
return
}
go func() {
defer func() { <-s.ownerAlertSlots }()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
ownerID, e := oid(owner)
if e != nil {
return
}
repo, e := s.Store.one(ctx, collection("repo"), M{"repoId": repoID, "owner": ownerID})
if e == nil && repo != nil {
_ = s.notifyOwnerAccessProblem(ctx, "repo", repo, err)
}
}()
}
func (s *Server) notifyOwnerAccessProblem(ctx context.Context, kind string, resource M, cause error) error {
if s.Config.EmailAPIKey == "" || s.Config.EmailFrom == "" || !ownerAccessFailure(cause) {
return nil
}
owner, err := s.Store.one(ctx, "users", M{"_id": resource["owner"], "status": M{"$nin": []string{"removed", "banned"}}})
if err != nil || owner == nil {
return err
}
if len(arr(owner["accessAlertDeactivations"])) > 0 || date(owner["accessAlertResetUntil"]).After(time.Now()) {
return nil
}
email := accountNotificationEmail(owner)
if email == "" {
return nil
}
identity := M{"_id": resource["_id"], "owner": resource["owner"], "status": M{"$nin": []string{"archived", "expired", "expiring", "removed", "removing"}}}
snapshot, err := s.Store.one(ctx, collection(kind), identity)
if err != nil || snapshot == nil {
return err
}
now := time.Now()
attempt := uuid.NewString()
key := alertRecipientKey(email)
if err := s.recoverUnsentOwnerAlerts(ctx, key); err != nil {
return err
}
dispatch := "accessAlertDispatches." + attempt
ownerFilter := M{"_id": owner["_id"], "status": M{"$nin": []string{"removed", "banned"}}, "accessAlertResetRevision": owner["accessAlertResetRevision"], "accessAlertDeactivations.0": M{"$exists": false}, "$or": []M{{"accessAlertResetUntil": M{"$exists": false}}, {"accessAlertResetUntil": M{"$lte": now}}}}
ok, err := s.Store.update(ctx, "users", ownerFilter, M{"$set": M{dispatch: M{"state": "prepared", "claimedAt": now}}})
if err != nil || !ok {
return err
}
started := false
claimed := false
defer func() {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
if !started {
_, _ = s.Store.update(cleanup, "users", M{"_id": owner["_id"], dispatch + ".state": "prepared"}, M{"$set": M{dispatch + ".state": "cancelled"}})
if claimed {
_, _ = s.Store.update(cleanup, collection(kind), M{"_id": resource["_id"], "owner": owner["_id"], "accessAlertAttemptId": attempt}, M{"$unset": M{"accessAlertClaimedAt": 1, "accessAlertAttemptId": 1}, "$inc": M{"accessAlertClaimRevision": 1}})
_, _ = s.Store.DB.Collection(recipientAlerts).DeleteOne(cleanup, M{"_id": key, "attemptId": attempt, "state": M{"$in": []string{"pending", "sending"}}})
}
}
if !started {
_, _ = s.Store.update(cleanup, "users", M{"_id": owner["_id"]}, M{"$unset": M{dispatch: 1}})
}
}()
record := M{"_id": key, "owner": owner["_id"], "resourceKind": alertResourceKind(kind), "resourceId": resource["_id"], "generation": snapshot["accessAlertGeneration"], "resourceRevision": number(snapshot["accessAlertClaimRevision"]), "attemptId": attempt, "claimedAt": now, "state": "pending", "dispatchPrepared": true}
if _, err = s.Store.DB.Collection(recipientAlerts).InsertOne(ctx, record); err != nil {
if mongo.IsDuplicateKeyError(err) {
return nil
}
return err
}
claimed = true
identity["accessAlertGeneration"] = snapshot["accessAlertGeneration"]
identity["accessAlertClaimRevision"] = snapshot["accessAlertClaimRevision"]
ok, err = s.Store.update(ctx, collection(kind), identity, M{"$set": M{"accessAlertClaimedAt": now, "accessAlertAttemptId": attempt}, "$inc": M{"accessAlertClaimRevision": 1}})
if err != nil || !ok {
return err
}
code := cause.Error()
_, err = s.Store.DB.Collection("owner_access_alert_events").InsertOne(ctx, M{"_id": attempt, "attemptId": attempt, "recipientKey": key, "owner": owner["_id"], "resourceKind": alertResourceKind(kind), "resourceId": resource["_id"], "generation": snapshot["accessAlertGeneration"], "state": "prepared", "startedAt": now, "failureCode": code})
if err != nil {
return err
}
ok, err = s.Store.update(ctx, recipientAlerts, M{"_id": key, "attemptId": attempt, "state": "pending"}, M{"$set": M{"state": "sending"}})
if err != nil || !ok {
return err
}
base := s.Config.Hostname
if !strings.HasPrefix(base, "http://") && !strings.HasPrefix(base, "https://") {
base = "https://" + base
}
address, err := url.Parse(base)
if err != nil || address.Host == "" {
return errors.New("invalid_email_origin")
}
address.Path = "/connections"
address.RawQuery = ""
address.Fragment = ""
payload, _ := json.Marshal(M{"from": s.Config.EmailFrom, "to": []string{email}, "subject": "Your Anonymous GitHub connection needs attention", "text": "Anonymous GitHub could not access GitHub using your connection, or could not read a repository.\n\nOpen your connections page to reconnect your account or restore repository access:\n" + address.String() + "\n\nYou are receiving this email because you own content on Anonymous GitHub. You can change your alert address on the connections page.\n"})
work, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(work, "POST", "https://api.resend.com/emails", bytes.NewReader(payload))
if err != nil {
return err
}
request.Header.Set("Authorization", "Bearer "+s.Config.EmailAPIKey)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "owner-access-alert/"+attempt)
ownerFilter[dispatch+".state"] = "prepared"
ok, err = s.Store.update(ctx, "users", ownerFilter, M{"$set": M{dispatch + ".state": "committed"}})
if err != nil || !ok {
return err
}
started = true
client := *s.HTTP
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
response, sendErr := client.Do(request)
state, status := "failed", 0
if sendErr == nil {
status = response.StatusCode
if status >= 200 && status < 300 {
state = "accepted"
}
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
response.Body.Close()
}
completion := M{"attemptId": attempt, "recipientKey": key, "owner": owner["_id"], "resourceKind": alertResourceKind(kind), "resourceId": resource["_id"], "generation": snapshot["accessAlertGeneration"], "state": state, "httpStatus": status, "completedAt": time.Now()}
completion["_id"] = attempt + "/completion"
cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer stop()
_, _ = s.Store.DB.Collection("owner_access_alert_events").InsertOne(cleanup, completion)
_, err = s.Store.update(cleanup, recipientAlerts, M{"_id": key, "attemptId": attempt, "state": "sending"}, M{"$set": M{"state": state, "httpStatus": status, "completedAt": completion["completedAt"]}})
if err == nil {
_, _ = s.Store.update(cleanup, "users", M{"_id": owner["_id"], dispatch + ".state": "committed"}, M{"$unset": M{dispatch: 1}})
}
return err
}
func (s *Server) beginAlertDeactivation(ctx context.Context, owner any) (func(), error) {
token := uuid.NewString()
_, err := s.Store.update(ctx, "users", M{"_id": owner}, M{"$addToSet": M{"accessAlertDeactivations": token}, "$inc": M{"accessAlertResetRevision": 1}})
if err != nil {
return nil, err
}
return func() {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_, _ = s.Store.update(cleanup, "users", M{"_id": owner}, M{"$pull": M{"accessAlertDeactivations": token}})
}, nil
}
// Cancel expired preparation against the same owner document used by the
// sender's final commit. A committed/ambiguous delivery is never retried.
func (s *Server) recoverUnsentOwnerAlerts(ctx context.Context, key string) error {
filter := M{"dispatchPrepared": true, "state": M{"$in": []string{"pending", "sending", "cancelled"}}, "claimedAt": M{"$lte": time.Now().Add(-time.Minute)}}
if key != "" {
filter["_id"] = key
}
cursor, err := s.Store.DB.Collection(recipientAlerts).Find(ctx, filter)
if err != nil {
return err
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var record M
if err := cursor.Decode(&record); err != nil {
return err
}
attempt := str(record["attemptId"])
if _, err := uuid.Parse(attempt); err != nil {
continue
}
dispatch := "accessAlertDispatches." + attempt
cancelled, err := s.Store.update(ctx, "users", M{"_id": record["owner"], dispatch + ".state": "prepared"}, M{"$set": M{dispatch + ".state": "cancelled"}})
if err != nil {
return err
}
if !cancelled {
owner, err := s.Store.one(ctx, "users", M{"_id": record["owner"]})
if err != nil {
return err
}
if owner == nil || str(obj(obj(owner["accessAlertDispatches"])[attempt])["state"]) == "committed" {
continue
}
}
matched, err := s.Store.update(ctx, recipientAlerts, M{"_id": record["_id"], "attemptId": attempt, "state": record["state"]}, M{"$set": M{"state": "cancelled"}})
if err != nil {
return err
}
if !matched {
continue
}
kind := map[string]string{"repository": "repo", "pull-request": "pr", "gist": "gist"}[str(record["resourceKind"])]
if kind != "" {
_, err = s.Store.update(ctx, collection(kind), M{"_id": record["resourceId"], "owner": record["owner"], "accessAlertAttemptId": attempt}, M{"$unset": M{"accessAlertClaimedAt": 1, "accessAlertAttemptId": 1}, "$inc": M{"accessAlertClaimRevision": 1}})
if err != nil {
return err
}
}
if _, err = s.Store.DB.Collection(recipientAlerts).DeleteOne(ctx, M{"_id": record["_id"], "attemptId": attempt, "state": "cancelled"}); err != nil {
return err
}
if _, err = s.Store.update(ctx, "users", M{"_id": record["owner"], dispatch + ".state": "cancelled"}, M{"$unset": M{dispatch: 1}}); err != nil {
return err
}
}
return cursor.Err()
}
@@ -101,6 +101,8 @@ func runGitHubPartialTreeIntegration(t *testing.T, s *Server, owner any) {
} else {
payload = M{"truncated": true, "tree": []M{{"path": "docs", "sha": child, "type": "tree"}, {"path": "root.txt", "sha": commit, "type": "blob", "size": 1}, {"path": "submodule", "sha": commit, "type": "commit"}}}
}
case "/repos/owner/repo/contents/submodule":
payload = M{"sha": commit, "submodule_git_url": "https://example.test/owner/private"}
case "/repos/owner/repo/git/trees/" + child:
payload = M{"truncated": true, "tree": []M{{"path": "visible.txt", "sha": commit, "type": "blob", "size": 2}}}
default:
+2 -2
View File
@@ -229,7 +229,7 @@ func (s *Server) buildPathIndex(ctx context.Context, r M, key, token string) err
if err := s.checkPathSnapshot(work, r); err != nil {
return err
}
cursor, e := s.Store.DB.Collection("files").Find(work, M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r)}, options.Find().SetSort(bson.D{{Key: "path", Value: 1}, {Key: "name", Value: 1}}).SetBatchSize(256).SetProjection(M{"path": 1, "name": 1, "size": 1, "sha": 1, "metadataPending": 1, "recoverySnapshot": 1}))
cursor, e := s.Store.DB.Collection("files").Find(work, M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r)}, options.Find().SetSort(bson.D{{Key: "path", Value: 1}, {Key: "name", Value: 1}}).SetBatchSize(256).SetProjection(M{"path": 1, "name": 1, "size": 1, "sha": 1, "upstream": 1, "submodule": 1, "metadataPending": 1, "recoverySnapshot": 1}))
if e != nil {
return e
}
@@ -299,7 +299,7 @@ return 1`, []string{key + ":lock", temp}, batch...).Int()
return fail("invalid_anonymized_path", 422)
}
field := "p:" + p
data, err := json.Marshal(selectFields(row, "path", "name", "size", "sha"))
data, err := json.Marshal(selectFields(row, "path", "name", "size", "sha", "upstream", "submodule"))
if err != nil {
return err
}
+23 -4
View File
@@ -171,13 +171,18 @@ func (g *githubProvider) TreeWithTruncation(ctx context.Context, a provider.Acce
if kind != "blob" && kind != "tree" && kind != "commit" {
continue
}
out = append(out, provider.Entry{Path: str(row["path"]), Revision: str(row["sha"]), Size: number(row["size"]), Directory: kind != "blob"})
entry := provider.Entry{Path: str(row["path"]), Revision: str(row["sha"]), Size: number(row["size"]), Directory: kind != "blob"}
if kind == "commit" {
entry.Submodule = "unsupported"
}
out = append(out, entry)
}
return out, truncated, nil
out, err := g.expandSubmodules(ctx, a, token, out)
return out, truncated, err
}
func (g *githubProvider) Open(ctx context.Context, a provider.Access, f provider.Entry) (io.ReadCloser, error) {
dir, name := path.Split(f.Path)
return g.server.githubBlob(ctx, providerRecord(a), M{"path": strings.TrimSuffix(dir, "/"), "name": name, "sha": f.Revision, "size": f.Size})
return g.server.githubBlob(ctx, providerRecord(a), M{"path": strings.TrimSuffix(dir, "/"), "name": name, "sha": f.Revision, "size": f.Size, "upstream": originDocument(f.Origin)})
}
func (g *githubProvider) PublicURL(r provider.Ref) string {
if !safeRepositoryName(r.Name) {
@@ -209,8 +214,19 @@ func (s *Server) githubBlob(ctx context.Context, r, row M) (io.ReadCloser, error
if err != nil {
return nil, err
}
if origin := upstreamOrigin(row["upstream"]); origin != nil {
if !validFileOrigin(origin) {
return nil, fail("invalid_source", 400)
}
name, token = origin.Repository, ""
r = M{"source": M{"repositoryName": name, "commit": origin.Commit}}
dir, base := path.Split(origin.Path)
row = M{"path": strings.TrimSuffix(dir, "/"), "name": base, "sha": sha, "size": row["size"]}
}
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.github.com/repos/"+name+"/git/blobs/"+sha, nil)
req.Header.Set("Authorization", "Bearer "+token)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
req.Header.Set("Accept", "application/vnd.github.raw+json")
req.Header.Set("User-Agent", "Anonymous-GitHub")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
@@ -258,6 +274,9 @@ func (g *githubProvider) Branch(ctx context.Context, a provider.Access, name str
}
func (g *githubProvider) FileMetadata(ctx context.Context, a provider.Access, requested string) (*provider.Entry, error) {
if path.Base(requested) == ".gitmodules" {
return nil, fail("file_not_found", 404)
}
relative, err := security.RelativePath(requested)
if err != nil || relative != requested || !safeRepositoryName(a.Ref.Name) || !commitID.MatchString(a.Ref.Commit) {
return nil, fail("invalid_source", 400)
@@ -30,7 +30,14 @@ func (g *githubProvider) VerifyContent(ctx context.Context, a provider.Access, e
if err != nil {
return nil, err
}
return g.server.githubPointer(ctx, a.Ref.Name, entry.Revision, token)
name := a.Ref.Name
if entry.Origin != nil {
if !validFileOrigin(entry.Origin) {
return nil, fail("invalid_source", 400)
}
name, token = entry.Origin.Repository, ""
}
return g.server.githubPointer(ctx, name, entry.Revision, token)
})
}
@@ -47,7 +54,9 @@ func (s *Server) githubPointer(ctx context.Context, name, revision, token string
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
req.Header.Set("Accept", "application/vnd.github.raw+json")
req.Header.Set("User-Agent", "Anonymous-GitHub")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+35 -1
View File
@@ -25,6 +25,24 @@ func (s *Server) quota(q *request) (any, error) {
if err != nil {
return nil, err
}
var limits M
if s.Config.Billing.Enabled {
limits, err = s.billingAllowance(q.ctx(), q.Identity.ID, "", "")
if err != nil {
return nil, err
}
funded := []M{}
for _, row := range rows {
allowance, e := s.billingAllowance(q.ctx(), q.Identity.ID, str(row["repoId"]), str(row["conference"]))
if e != nil {
return nil, e
}
if allowance["scope"] == limits["scope"] {
funded = append(funded, row)
}
}
rows = funded
}
var used, files float64
uncached := []M{}
matches := []M{}
@@ -59,5 +77,21 @@ func (s *Server) quota(q *request) (any, error) {
}
}
}
return M{"storage": M{"used": used, "total": int64(2) * 1024 * 1024 * 1024 * 8}, "file": M{"used": files, "total": 0}, "repository": M{"used": len(rows), "total": 20}}, nil
if limits != nil {
count := int64(len(rows))
reserved, e := s.Store.one(q.ctx(), "billingquotas", M{"_id": limits["scope"]})
if e != nil {
return nil, e
}
if reserved != nil {
used = 0
allocations := arr(reserved["allocations"])
count = int64(len(allocations))
for _, value := range allocations {
used += decimal(obj(value)["bytes"])
}
}
return M{"storage": M{"unit": "bytes", "used": used, "total": limits["storage"]}, "file": M{"used": files, "total": 0}, "repository": M{"used": count, "total": limits["repositories"]}}, nil
}
return M{"storage": M{"unit": "legacy", "used": used, "total": int64(2) * 1024 * 1024 * 1024 * 8}, "file": M{"used": files, "total": 0}, "repository": M{"used": len(rows), "total": 20}}, nil
}
+3 -1
View File
@@ -44,7 +44,9 @@ func (s *Server) rawBlob(ctx context.Context, r, row M, token string) (io.ReadCl
parts[i] = url.PathEscape(p)
}
req, _ := http.NewRequestWithContext(ctx, "GET", "https://github.com/"+name+"/raw/"+commit+"/"+strings.Join(parts, "/"), nil)
req.Header.Set("Authorization", "Bearer "+token)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
req.Header.Set("User-Agent", "Anonymous-GitHub")
client := *s.HTTP
client.CheckRedirect = func(next *http.Request, via []*http.Request) error {
+9
View File
@@ -11,6 +11,15 @@ import (
// A durable compare-and-swap claim prevents simultaneous viewers from starting
// competing refreshes. Failure leaves the saved tree intact.
func (s *Server) autoRefresh(ctx context.Context, r M) error {
if boolean(r["billingManaged"]) {
allowed, err := s.billingAutomaticUpdates(ctx, str(r["owner"]), str(r["repoId"]), str(r["conference"]))
if err != nil {
return err
}
if !allowed {
return nil
}
}
return s.updateRepository(ctx, r, false, "")
}
func refreshRevisionFilter(r M, token string) M {
@@ -0,0 +1,81 @@
package server
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
// Missing email permissions and provider outages must not prevent login.
func (s *Server) saveRegistrationEmail(ctx context.Context, user M, token string) {
if accountNotificationEmail(user) != "" {
return
}
work, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
r, err := http.NewRequestWithContext(work, "GET", "https://api.github.com/user/emails?per_page=100", nil)
if err != nil {
return
}
r.Header.Set("Authorization", "Bearer "+token)
r.Header.Set("Accept", "application/vnd.github+json")
r.Header.Set("X-GitHub-Api-Version", "2022-11-28")
r.Header.Set("User-Agent", "Anonymous-GitHub")
client := *s.HTTP
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
response, err := client.Do(r)
if err != nil {
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
return
}
raw, err := io.ReadAll(io.LimitReader(response.Body, 1024*1024+1))
if err != nil || len(raw) > 1024*1024 {
return
}
var entries []M
if json.Unmarshal(raw, &entries) != nil {
return
}
chosen := ""
for _, entry := range entries {
if entry["verified"] != true {
continue
}
email := normalizeNotificationEmail(entry["email"])
if email == "" {
continue
}
domain := strings.ToLower(strings.SplitN(email, "@", 2)[1])
if domain == "users.noreply.github.com" || domain == "noreply.github.com" {
continue
}
if chosen == "" || entry["primary"] == true {
chosen = email
}
if entry["primary"] == true {
break
}
}
if chosen == "" {
return
}
previous := user["emails"]
if previous == nil {
previous = []any{}
}
alternatives := []M{{"emails": previous}}
if len(arr(previous)) == 0 {
alternatives = append(alternatives, M{"emails": M{"$exists": false}})
}
emails := []M{{"email": chosen, "default": true}}
ok, err := s.Store.update(work, "users", M{"_id": user["_id"], "notificationEmail": user["notificationEmail"], "$or": alternatives}, M{"$set": M{"emails": emails}})
if err == nil && ok {
user["emails"] = emails
}
}
+83 -1
View File
@@ -224,6 +224,12 @@ func (s *Server) publicOptions(kind string) handler {
if err != nil {
return nil, err
}
if sub == nil {
sub, err = s.Store.one(q.ctx(), "files", M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r), "submodule": M{"$exists": true, "$ne": "included"}})
if err != nil {
return nil, err
}
}
out["hasSubmodules"] = sub != nil
}
return out, nil
@@ -251,6 +257,22 @@ func (s *Server) preview(q *request) (any, error) {
if json.Unmarshal(b, &opt) != nil {
return nil, fail("invalid_options", 400)
}
preserved, err := anonymize.NormalizePreserveFiles(obj(q.Body["options"])["preserveFiles"])
if err != nil {
return nil, fail(err.Error(), 400)
}
file, present := obj(q.Body["options"])["filePath"]
if present {
value, ok := file.(string)
if !ok || !safeSourcePath(value) {
return nil, fail("invalid_path", 400)
}
if anonymize.PreservedPath(value, preserved) {
opt.Terms = []string{}
}
}
q.W.Header().Set("Cache-Control", "private, no-store")
e, err := anonymize.New(opt, anonymize.Context{Mask: s.Config.Mask, Hostname: s.Config.Hostname})
if err != nil {
return nil, fail(err.Error(), 400)
@@ -304,7 +326,7 @@ func validatedOptions(kind string, body M) (M, error) {
fields := []string{"expirationMode", "expirationDate", "update", "image", "link"}
switch kind {
case "repo":
fields = append(fields, "pdf", "notebook", "page", "pageSource")
fields = append(fields, "pdf", "notebook", "page", "pageSource", "preserveFiles")
case "gist", "pr":
fields = append(fields, "title", "body", "comments", "origin", "username", "date")
if kind == "gist" {
@@ -314,6 +336,13 @@ func validatedOptions(kind string, body M) (M, error) {
}
}
opt := selectFields(obj(body["options"]), fields...)
if kind == "repo" {
patterns, err := anonymize.NormalizePreserveFiles(opt["preserveFiles"])
if err != nil {
return nil, fail(err.Error(), 400)
}
opt["preserveFiles"] = patterns
}
castStringField := func(fields M, key string) error {
value, exists := fields[key]
if !exists || value == nil {
@@ -430,6 +459,43 @@ func (s *Server) saveResource(kind string, create bool) handler {
return nil, fail("invalid_"+idKey(kind), 400)
}
billingFields := M{}
if kind == "repo" && s.Config.Billing.Enabled {
owner := q.Identity.ID
if previous != nil {
owner = str(previous["owner"])
}
managed := previous == nil || boolean(previous["billingManaged"])
oldSource := obj(previous["source"])
sourceChanged := previous == nil || str(body["fullName"]) != str(oldSource["repositoryName"]) || str(source["branch"]) != str(oldSource["branch"]) || str(source["commit"]) != str(oldSource["commit"])
needsAdmission := sourceChanged || oldConference != newConference || shouldReactivateRepository(str(previous["status"]), opt, time.Now())
if managed {
billingFields, err = s.billingResourceSettings(q.ctx(), owner, id, newConference, opt, previous)
if err != nil {
return nil, err
}
} else if opt["expirationMode"] == "never" && (obj(previous["options"])["expirationMode"] != "never" || previous["billingNeverExpiresUntil"] != nil) {
existing := time.Time{}
if obj(previous["options"])["expirationMode"] == "never" {
existing = date(previous["billingNeverExpiresUntil"])
}
deadline, e := s.billingNeverDeadline(q.ctx(), owner, id, existing)
if e != nil {
return nil, e
}
billingFields["billingNeverExpiresUntil"] = deadline
}
if needsAdmission {
if err = s.billingConferenceAdmission(q.ctx(), owner, id, newConference); err != nil {
return nil, err
}
if managed {
if err = s.reserveBillingRepository(q.ctx(), owner, id, number(obj(previous["size"])["storage"]), newConference, "", 0); err != nil {
return nil, err
}
}
}
}
_, reconnectRequested := body["reconnectRepositoryId"]
// Settings-only saves must not need a working GitHub grant or replace its identity binding.
if kind == "repo" && previous != nil && !reconnectRequested {
@@ -438,6 +504,9 @@ func (s *Server) saveResource(kind string, create bool) handler {
if same {
now := membershipSaveTime(previous)
set := M{"options": opt, "conference": str(body["conference"]), "settingsSavedAt": now}
for key, value := range billingFields {
set[key] = value
}
recordConferenceMembership(set, oldConference, newConference, now)
reactivating := shouldReactivateRepository(str(previous["status"]), opt, now)
if reactivating {
@@ -486,6 +555,9 @@ func (s *Server) saveResource(kind string, create bool) handler {
now := membershipSaveTime(previous)
record := M{idKey(kind): id, "owner": owner, "source": savedSource, "options": opt, "conference": str(body["conference"]), "settingsSavedAt": now, "anonymizeDate": now, "status": "preparing", "statusDate": now, "githubAccess": binding}
for key, value := range billingFields {
record[key] = value
}
if id, e := sourceProvider(savedSource); e == nil && id != "github" {
delete(record, "githubAccess")
record["providerAccess"] = binding
@@ -548,6 +620,11 @@ func (s *Server) lifecycle(kind, action string) handler {
return s.extendResource(q.ctx(), kind, r)
}
if action == "refresh" && q.Identity.ID == str(r["owner"]) {
if err = s.resetOwnerAlerts(q.ctx(), r["owner"], kind, r["_id"]); err != nil {
return nil, err
}
}
if action == "refresh" && kind != "repo" {
if err = s.refreshEmbedded(q.ctx(), kind, r); err != nil {
return nil, err
@@ -562,6 +639,11 @@ func (s *Server) lifecycle(kind, action string) handler {
if !q.Identity.Owns(str(r["owner"])) {
return nil, fail("not_authorized", 403)
}
finish, e := s.beginAlertDeactivation(q.ctx(), r["owner"])
if e != nil {
return nil, e
}
defer finish()
status, job = "removing", "remove"
}
if (str(r["status"]) == "removing" || str(r["status"]) == "expiring") && !(kind == "repo" && action == "remove") {
+186
View File
@@ -0,0 +1,186 @@
package server
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"net/http"
"regexp"
"strings"
"sync"
"time"
)
type reviewKey struct {
digest []byte
from, until time.Time
}
type reviewRate struct {
minute int64
count int
}
type reviewRegistry struct {
keys map[string]reviewKey
mu sync.Mutex
rates map[string]reviewRate
}
var reviewClient = regexp.MustCompile(`^[a-f0-9]{32}$`)
var reviewKeyID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
var reviewSecret = regexp.MustCompile(`^[a-f0-9]{64}$`)
func parseReviewRegistry(raw *string) (*reviewRegistry, error) {
if raw == nil {
return nil, nil
}
invalid := errors.New("invalid_REVIEW_SERVICE_KEYS")
var config M
if len(*raw) > 65536 || json.Unmarshal([]byte(*raw), &config) != nil || len(config) != 2 || config["version"] != float64(1) {
return nil, invalid
}
entries, ok := config["keys"].([]any)
if !ok || len(entries) < 1 || len(entries) > 64 {
return nil, invalid
}
registry := &reviewRegistry{keys: map[string]reviewKey{}, rates: map[string]reviewRate{}}
clients, digests := map[string]int{}, map[string]bool{}
for _, entry := range entries {
key := obj(entry)
client, id, digest := str(key["clientId"]), str(key["keyId"]), str(key["tokenSHA256"])
if len(key) != 5 || !reviewClient.MatchString(client) || !reviewKeyID.MatchString(id) || !reviewSecret.MatchString(digest) {
return nil, invalid
}
dates := []time.Time{}
for _, field := range []string{"notBefore", "notAfter"} {
value := str(key[field])
parsed, err := time.Parse("2006-01-02T15:04:05Z", value)
if err != nil || !strings.HasPrefix(value, "20") || parsed.Format("2006-01-02T15:04:05Z") != value {
return nil, invalid
}
dates = append(dates, parsed)
}
name := client + ":" + id
_, exists := registry.keys[name]
clients[client]++
if exists || digests[digest] || clients[client] > 16 || len(clients) > 32 || !dates[1].After(dates[0]) {
return nil, invalid
}
decoded, _ := hex.DecodeString(digest)
registry.keys[name] = reviewKey{decoded, dates[0], dates[1]}
digests[digest] = true
}
return registry, nil
}
func (s *Server) reviewCapabilities(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
reject := func(status int, code string, retry int) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
out := M{"contract": "4open.artifacts/1", "code": code, "requestId": strings.ReplaceAll(uuid.NewString(), "-", "")}
if retry > 0 {
w.Header().Set("Retry-After", fmt.Sprint(retry))
out["retryAfterSeconds"] = retry
}
w.WriteHeader(status)
writeJSON(w, out)
}
if s.review == nil || r.URL.RequestURI() != "/service/v1/capabilities" {
reject(404, "not-found", 0)
return
}
if r.Method != "GET" {
reject(405, "invalid-request", 0)
return
}
for _, h := range []string{"Cookie", "Origin", "Referer", "Sec-Fetch-Site", "Sec-Fetch-Mode", "Sec-Fetch-Dest", "Sec-Fetch-User"} {
if _, ok := r.Header[http.CanonicalHeaderKey(h)]; ok {
reject(403, "forbidden", 0)
return
}
}
_, hasContentType := r.Header["Content-Type"]
if len(r.TransferEncoding) > 0 || hasContentType || r.ContentLength > 0 || (r.Header.Get("Content-Length") != "" && r.Header.Get("Content-Length") != "0") {
reject(400, "invalid-request", 0)
return
}
single := func(name string) string {
values := r.Header.Values(name)
if len(values) != 1 {
return ""
}
return values[0]
}
client, keyID, auth := single("X-4open-artifact-client-id"), single("X-4open-artifact-service-key-id"), single("Authorization")
if !reviewClient.MatchString(client) || !reviewKeyID.MatchString(keyID) || len(auth) != 71 || !strings.EqualFold(auth[:7], "Bearer ") || !reviewSecret.MatchString(auth[7:]) {
reject(401, "unauthorized", 0)
return
}
key, exists := s.review.keys[client+":"+keyID]
expected := key.digest
if !exists {
expected = make([]byte, 32)
}
digest := sha256.Sum256([]byte(auth[7:]))
equal := subtle.ConstantTimeCompare(digest[:], expected)
now := time.Now()
if !exists || equal != 1 || now.Before(key.from) || !now.Before(key.until) {
reject(401, "unauthorized", 0)
return
}
s.review.mu.Lock()
minute := now.Unix() / 60
rate := s.review.rates[client]
if rate.minute != minute {
rate = reviewRate{minute: minute}
}
limited := rate.count >= 60
if !limited {
rate.count++
s.review.rates[client] = rate
}
s.review.mu.Unlock()
if limited {
reject(429, "rate-limited", 60-int(now.Unix()%60))
return
}
writeJSON(w, M{"contract": "4open.artifacts/1", "clientId": client, "contracts": []string{"4open.artifacts/1"}, "available": []string{}})
}
func reviewConsentPath(path string) bool {
return strings.TrimRight(strings.ToLower(path), "/") == "/review-link"
}
func (s *Server) reviewConsentPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
if r.URL.RequestURI() != "/review-link" || (r.Method != "GET" && r.Method != "HEAD") {
writeError(w, fail("not_found", 404))
return
}
manifest := map[string]string{}
if data, err := s.public.ReadFile("asset-manifest.json"); err == nil {
_ = json.Unmarshal(data, &manifest)
}
asset := func(name string) string {
value := manifest[name]
extension := ".js"
if strings.HasSuffix(name, ".css") {
extension = ".css"
}
if !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]*$`).MatchString(value) || !strings.HasSuffix(value, extension) {
return name
}
return value
}
page := fmt.Sprintf(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><meta name="review-consent-page" content="1"><title>Artifact consent · Anonymous GitHub</title><link rel="stylesheet" href="/css/%s"></head><body><div id="app"></div><script src="/script/%s"></script><script defer src="/script/%s"></script></body></html>`, asset("all.min.css"), asset("core.min.js"), asset("vendor.min.js"))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Content-Length", fmt.Sprint(len(page)))
if r.Method != "HEAD" {
_, _ = w.Write([]byte(page))
}
}
+16 -4
View File
@@ -10,6 +10,14 @@ import (
func queryEscape(s string) string { return url.QueryEscape(s) }
func (s *Server) register() {
s.registerAdmin()
s.add("GET", "/api/admin/billing/grants", "admin", s.billingGrantReport)
s.add("GET", "/api/admin/billing/summary", "admin", s.billingSummaryReport)
s.add("POST", "/api/billing/webhook", "", s.billingWebhook)
s.add("GET", "/api/billing", "user", s.billingAPI)
s.add("GET", "/api/billing/draft/:id", "user", s.billingAPI)
for _, action := range []string{"draft", "checkout", "portal", "refresh"} {
s.add("POST", "/api/billing/"+action, "user", s.billingAPI)
}
s.add("GET", "/api/providers", "user", s.providerCapabilities)
s.add("GET", "/api/providers/:provider/gist/:id", "user", s.embeddedSource("gist"))
s.add("GET", "/api/providers/:provider/pr/:id", "user", s.embeddedSource("pr"))
@@ -44,7 +52,7 @@ func (s *Server) register() {
s.add("POST", "/github/connections/migrate", "user", s.connections)
s.add("POST", "/github/connections/disconnect-oauth", "user", s.connections)
s.add("DELETE", "/api/user", "user", s.deleteAccount)
s.add("GET", "/api/conferences/plans", "user", func(q *request) (any, error) { return plans, nil })
s.add("GET", "/api/conferences/plans", "user", func(q *request) (any, error) { return s.offeredConferencePlans(), nil })
for _, method := range []string{"GET", "POST"} {
s.add(method, "/api/conferences", "user", s.conferences)
}
@@ -67,9 +75,9 @@ func (s *Server) register() {
return M{"required": number(flow["expires"]) > time.Now().UnixMilli()}, nil
})
s.add("GET", "/api/user/logout", "user", s.logout)
s.add("GET", "/api/user", "user", func(q *request) (any, error) {
return userProfile(q.User), nil
})
s.add("GET", "/api/user", "user", s.accountProfile)
s.add("GET", "/github/connections/email", "user", s.accountEmail)
s.add("POST", "/github/connections/email", "user", s.accountEmail)
s.add("GET", "/api/user/default", "user", func(q *request) (any, error) { return userDefaults(q.User), nil })
s.add("POST", "/api/user/default", "user", func(q *request) (any, error) {
value, err := castUserDefaults(q.Body)
@@ -114,6 +122,10 @@ func (s *Server) register() {
s.add("DELETE", "/api/repo/:id/coauthors/:username", "user", s.coauthors)
s.add("GET", "/api/repo/:id/file/*path", "", s.file)
s.add("GET", "/api/repo/:id/zip", "", s.zip)
s.add("GET", "/api/repo/:owner/:repo/tree", "user", s.sourcePreview)
s.add("GET", "/api/repo/:owner/:repo/file", "user", s.sourcePreview)
s.add("GET", "/api/providers/:provider/repository/tree", "user", s.sourcePreview)
s.add("GET", "/api/providers/:provider/repository/file", "user", s.sourcePreview)
s.add("GET", "/api/repo/:owner/:repo/branches", "user", s.sourceRepository("branches"))
s.add("GET", "/api/repo/:owner/:repo/readme", "user", s.sourceRepository("readme"))
s.add("GET", "/api/repo/:owner/:repo", "user", s.sourceRepository("metadata"))
+4
View File
@@ -205,6 +205,10 @@ func (s *Server) sharedSourceRead(ctx context.Context, r M, p provider.Repositor
context.AfterFunc(work, func() { bounded.Close() })
return bounded, nil
}
if err = s.reserveBillingExpansion(ctx, a.Ref.AnonymousID, entry.Path, reader.Record().Size-entry.Size); err != nil {
reader.Close()
return nil, err
}
if reader.Record().Size > anonymize.MaxInput {
reader.Close()
return nil, fail("file_too_big", 413)
-1
View File
@@ -102,7 +102,6 @@ func sendSharedBlob(ctx context.Context, w http.ResponseWriter, body *blobcache.
record = encoded.Record()
}
h := w.Header()
h.Set("Accept-Ranges", "none")
if record.Encoding == "gzip" && response.encoding == "gzip" {
h.Set("Content-Encoding", "gzip")
h.Set("Content-Length", strconv.FormatInt(record.Stored, 10))
+187
View File
@@ -0,0 +1,187 @@
package server
import (
"context"
"encoding/base64"
"errors"
"net/url"
"regexp"
"sort"
"strings"
"github.com/tdurieux/anonymous_github/backend/internal/filetype"
"github.com/tdurieux/anonymous_github/backend/internal/provider"
)
var previewCommit = regexp.MustCompile(`^[0-9a-fA-F]{6,40}$`)
func safeSourcePath(value string) bool {
if value == "" || len(value) > 4096 || strings.Contains(value, "\\") {
return false
}
for _, c := range value {
if c < 32 {
return false
}
}
for _, part := range strings.Split(value, "/") {
if part == "" || part == "." || part == ".." {
return false
}
}
return true
}
func (s *Server) sourcePreview(q *request) (any, error) {
query := parseExtendedQuery(q.R.URL.RawQuery).object
commit, ok := query["commit"].scalarValue()
id := q.Params["provider"]
if id == "" {
id = "github"
}
validCommit := commit != "" && len(commit) <= 512 && !strings.ContainsAny(commit, "\r\n\x00")
if id == "github" {
validCommit = previewCommit.MatchString(commit)
}
if !ok || !validCommit {
return nil, fail("invalid_commit_format", 400)
}
isFile := strings.HasSuffix(q.R.URL.Path, "/file")
path, _ := query["path"].scalarValue()
if isFile && !safeSourcePath(path) {
return nil, fail("invalid_path", 400)
}
adapter, err := s.providers.Get(id)
if err != nil {
return nil, providerFailure(err)
}
repositories, ok := adapter.(provider.Repositories)
if !ok {
return nil, providerFailure(provider.ErrCapability)
}
previews, ok := adapter.(provider.SourcePreviews)
if !ok {
return nil, providerFailure(provider.ErrCapability)
}
name := q.Params["owner"] + "/" + q.Params["repo"]
if q.Params["provider"] != "" {
name, _ = query["repository"].scalarValue()
}
access, err := s.previewRepositoryAccess(q, repositories, id, name)
if err != nil {
return nil, err
}
if err = repositories.Authorize(q.ctx(), access); err != nil {
return nil, err
}
access.Ref.Commit = commit
q.W.Header().Set("Cache-Control", "private, no-store")
if !isFile {
entries, truncated, err := previews.PreviewTree(q.ctx(), access, 20000)
if err != nil {
return nil, err
}
files, binaryFiles := []string{}, []string{}
for _, entry := range entries {
if entry.Directory || entry.Path == ".gitmodules" || !safeSourcePath(entry.Path) {
continue
}
text, known := filetype.ClassifyName(entry.Path)
if known && !text {
binaryFiles = append(binaryFiles, entry.Path)
} else {
files = append(files, entry.Path)
}
}
sort.Strings(files)
sort.Strings(binaryFiles)
return M{"files": files, "binaryFiles": binaryFiles, "truncated": truncated}, nil
}
content, size, binary, err := previews.PreviewFile(q.ctx(), access, path, 1024*1024)
if err != nil {
return nil, err
}
q.W.Header().Set("X-Content-Type-Options", "nosniff")
if binary {
return M{"binary": true, "size": size}, nil
}
return q.text(strings.ToValidUTF8(string(content), "\uFFFD")), nil
}
func sourcePreviewError(err error, file bool) error {
var upstream *githubHTTPError
if errors.As(err, &upstream) && (upstream.status == 404 || upstream.status == 422 || (!file && upstream.status == 409)) {
if file {
return fail("file_not_found", 404)
}
return fail("repo_not_found", 404)
}
return err
}
func (g *githubProvider) PreviewTree(ctx context.Context, a provider.Access, limit int) ([]provider.Entry, bool, error) {
token, err := g.token(ctx, a)
if err != nil {
return nil, false, err
}
commit := a.Ref.Commit
if len(commit) != 40 {
row, e := g.server.githubObject(ctx, "GET", "/repos/"+a.Ref.Name+"/commits/"+segment(commit), token, nil)
if e != nil {
return nil, false, sourcePreviewError(e, false)
}
commit = str(row["sha"])
if len(commit) != 40 || !previewCommit.MatchString(commit) {
return nil, false, fail("invalid_source", 502)
}
}
row, err := g.server.githubObject(ctx, "GET", "/repos/"+a.Ref.Name+"/git/trees/"+segment(commit)+"?recursive=true", token, nil)
if err != nil {
return nil, false, sourcePreviewError(err, false)
}
entries := []provider.Entry{}
for _, raw := range arr(row["tree"]) {
entry := obj(raw)
p := str(entry["path"])
if entry["type"] != "blob" || p == ".gitmodules" || !safeSourcePath(p) {
continue
}
if len(entries) == limit {
return entries, true, nil
}
entries = append(entries, provider.Entry{Path: p, Revision: str(entry["sha"]), Size: number(entry["size"])})
}
return entries, boolean(row["truncated"]), nil
}
func (g *githubProvider) PreviewFile(ctx context.Context, a provider.Access, path string, limit int64) ([]byte, int64, bool, error) {
token, err := g.token(ctx, a)
if err != nil {
return nil, 0, false, err
}
parts := strings.Split(path, "/")
for i := range parts {
parts[i] = segment(parts[i])
}
row, err := g.server.githubObject(ctx, "GET", "/repos/"+a.Ref.Name+"/contents/"+strings.Join(parts, "/")+"?ref="+url.QueryEscape(a.Ref.Commit), token, nil)
if err != nil {
return nil, 0, false, sourcePreviewError(err, true)
}
if row["type"] != "file" {
return nil, 0, false, fail("file_not_found", 404)
}
size := number(row["size"])
if text, known := filetype.ClassifyName(path); known && !text {
return nil, size, true, nil
}
if size > limit || (size > 0 && row["encoding"] == "none") {
return nil, 0, false, fail("file_too_big", 413)
}
content := []byte(str(row["content"]))
if row["encoding"] == "base64" {
content, err = base64.StdEncoding.DecodeString(strings.ReplaceAll(str(row["content"]), "\n", ""))
if err != nil {
return nil, 0, false, fail("invalid_source", 502)
}
}
if int64(len(content)) > limit {
return nil, 0, false, fail("file_too_big", 413)
}
return content, size, len(content) > 0 && !filetype.Text(path, content), nil
}
+9
View File
@@ -66,16 +66,25 @@ func (r *measuredSource) Close() error {
func (s *Server) openMeasuredSource(ctx context.Context, p provider.Repositories, access provider.Access, entry provider.Entry) (io.ReadCloser, error) {
done := s.startStage(ctx, "upstream")
body, err := p.Open(ctx, access, entry)
if err != nil {
s.scheduleOwnerAlert(access.OwnerID, access.Ref.AnonymousID, err)
}
if err != nil {
done(err)
return nil, err
}
if s.Config.Billing.Enabled && access.Ref.AnonymousID != "" {
body = &billingContentReader{ReadCloser: body, s: s, ctx: ctx, repoID: access.Ref.AnonymousID, key: entry.Path, expected: entry.Size}
}
return &measuredSource{ReadCloser: body, done: done}, nil
}
func (s *Server) authorizeMeasured(ctx context.Context, p provider.Repositories, access provider.Access) error {
done := s.startStage(ctx, "authorization")
err := p.Authorize(ctx, access)
if err != nil {
s.scheduleOwnerAlert(access.OwnerID, access.Ref.AnonymousID, err)
}
done(err)
return err
}
+172
View File
@@ -0,0 +1,172 @@
package server
import (
"context"
"errors"
"github.com/tdurieux/anonymous_github/backend/internal/provider"
"net/url"
"path"
"regexp"
"strings"
)
var submoduleOwner = regexp.MustCompile(`^[A-Za-z0-9-]+$`)
var submoduleRepo = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`)
func submoduleRepository(raw, parent string) string {
normalized := raw
for _, prefix := range []string{"git@github.com:", "ssh://git@github.com/", "git://github.com/"} {
if strings.HasPrefix(raw, prefix) {
normalized = "https://github.com/" + strings.TrimPrefix(raw, prefix)
}
}
u, err := url.Parse(normalized)
if err != nil {
return ""
}
if strings.HasPrefix(raw, "./") || strings.HasPrefix(raw, "../") {
base, _ := url.Parse("https://github.com/" + parent + "/")
u = base.ResolveReference(u)
}
if u.Scheme != "https" || u.Host != "github.com" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return ""
}
name := strings.TrimSuffix(strings.TrimSuffix(strings.TrimPrefix(u.Path, "/"), "/"), ".git")
parts := strings.Split(name, "/")
if len(parts) != 2 || !submoduleOwner.MatchString(parts[0]) || !submoduleRepo.MatchString(parts[1]) || parts[1] == "." || parts[1] == ".." {
return ""
}
return name
}
func upstreamOrigin(value any) *provider.FileOrigin {
row := obj(value)
if len(row) == 0 {
return nil
}
return &provider.FileOrigin{Provider: "github", Repository: str(row["organization"]) + "/" + str(row["repoName"]), Commit: str(row["commit"]), Path: str(row["path"])}
}
func validFileOrigin(origin *provider.FileOrigin) bool {
return origin != nil && origin.Provider == "github" && submoduleRepository("https://github.com/"+origin.Repository, "") == origin.Repository && gitBlobSHA.MatchString(origin.Commit) && safeSourcePath(origin.Path)
}
func originDocument(origin *provider.FileOrigin) M {
if origin == nil {
return nil
}
parts := strings.SplitN(origin.Repository, "/", 2)
if len(parts) != 2 {
return nil
}
return M{"organization": parts[0], "repoName": parts[1], "commit": origin.Commit, "path": origin.Path}
}
func fileProviderEntry(row M) provider.Entry {
return provider.Entry{Path: path.Join(str(row["path"]), str(row["name"])), Revision: str(row["sha"]), Size: number(row["size"]), Origin: upstreamOrigin(row["upstream"]), Submodule: str(row["submodule"])}
}
func (g *githubProvider) expandSubmodules(ctx context.Context, a provider.Access, token string, entries []provider.Entry) ([]provider.Entry, error) {
out := make([]provider.Entry, 0, len(entries))
for _, entry := range entries {
if path.Base(entry.Path) != ".gitmodules" {
out = append(out, entry)
}
}
count, remaining := 0, 10000
parents := len(out)
for i := 0; i < parents; i++ {
mount := &out[i]
if mount.Submodule == "" {
continue
}
count++
if count > 20 {
mount.Submodule = "limit"
continue
}
if !safeSourcePath(mount.Path) || !gitBlobSHA.MatchString(mount.Revision) {
continue
}
metadata, err := g.server.githubObject(ctx, "GET", "/repos/"+a.Ref.Name+"/contents/"+escapeRepositoryPath(mount.Path)+"?ref="+url.QueryEscape(a.Ref.Commit), token, nil)
if err != nil {
var upstream *githubHTTPError
if errors.As(err, &upstream) && upstream.status == 404 {
mount.Submodule = "unavailable"
continue
}
return nil, err
}
name := submoduleRepository(str(metadata["submodule_git_url"]), a.Ref.Name)
if name == "" || metadata["sha"] != mount.Revision {
continue
}
tree, err := g.server.githubObject(ctx, "GET", "/repos/"+name+"/git/trees/"+mount.Revision+"?recursive=1", "", nil)
if err != nil {
var upstream *githubHTTPError
if errors.As(err, &upstream) && (upstream.status == 404 || upstream.status == 422) {
mount.Submodule = "unavailable"
continue
}
return nil, err
}
rows := arr(tree["tree"])
if boolean(tree["truncated"]) || len(rows) > remaining {
mount.Submodule = "limit"
continue
}
safe := true
for _, raw := range rows {
if !safeSourcePath(str(obj(raw)["path"])) {
safe = false
break
}
}
if !safe {
mount.Submodule = "unsupported"
continue
}
remaining -= len(rows)
mount.Submodule = "included"
prefix, commit := mount.Path, mount.Revision
mount.Origin = &provider.FileOrigin{Provider: "github", Repository: name, Commit: commit}
for _, raw := range rows {
row := obj(raw)
relative := str(row["path"])
if path.Base(relative) == ".gitmodules" {
continue
}
entry := provider.Entry{Path: prefix + "/" + relative, Revision: str(row["sha"]), Size: number(row["size"]), Directory: row["type"] != "blob"}
if row["type"] == "commit" {
entry.Submodule = "nested"
}
if row["type"] == "blob" {
entry.Origin = &provider.FileOrigin{Provider: "github", Repository: name, Commit: commit, Path: relative}
}
out = append(out, entry)
}
}
return out, nil
}
func escapeRepositoryPath(value string) string {
parts := strings.Split(value, "/")
for i := range parts {
parts[i] = segment(parts[i])
}
return strings.Join(parts, "/")
}
func (s *Server) assertFileOrigin(ctx context.Context, row M) error {
if row["upstream"] == nil {
return nil
}
origin := upstreamOrigin(row["upstream"])
if !validFileOrigin(origin) {
return fail("invalid_source", 400)
}
// This check deliberately carries no parent credential: a private dependency
// cannot acquire access merely because its parent repository is authorized.
_, err := s.githubObject(ctx, "GET", "/repos/"+origin.Repository+"/commits/"+origin.Commit, "", nil)
if err != nil {
var upstream *githubHTTPError
if errors.As(err, &upstream) && (upstream.status == 404 || upstream.status == 422) {
return fail("submodule_not_available", 404)
}
return err
}
return nil
}
+8
View File
@@ -13,6 +13,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"repositories": [],
"status": "active",
@@ -33,6 +34,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"repositories": [],
"status": "active",
@@ -105,6 +107,7 @@
"Alice"
]
},
"emailPromptNever": false,
"repositories": [],
"_id": "111111111111111111111111",
"username": "sample",
@@ -168,6 +171,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"status": "active",
"_id": "111111111111111111111111",
@@ -250,6 +254,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"status": "active",
"_id": "111111111111111111111111",
@@ -323,6 +328,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"status": "active",
"_id": "111111111111111111111111",
@@ -399,6 +405,7 @@
"expected": {
"externalIDs": null,
"default": null,
"emailPromptNever": false,
"_id": "111111111111111111111111",
"username": "sample",
"dateOfEntry": "2030-01-01T12:00:00.000Z",
@@ -427,6 +434,7 @@
"default": {
"terms": []
},
"emailPromptNever": false,
"isAdmin": false,
"repositories": [],
"status": "active",
+140 -74
View File
@@ -422,7 +422,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/missing billing",
@@ -436,7 +439,7 @@
}
},
"expected": {
"code": "billing_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -453,7 +456,7 @@
"billing": {}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -477,7 +480,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -501,7 +504,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -525,7 +528,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -549,7 +552,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -572,7 +575,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/email/null",
@@ -594,7 +600,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -618,7 +624,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -642,7 +648,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -666,7 +672,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -689,7 +695,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/address/null",
@@ -711,7 +720,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -735,7 +744,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -759,7 +768,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -783,7 +792,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -806,7 +815,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/city/null",
@@ -828,7 +840,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -852,7 +864,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -876,7 +888,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -900,7 +912,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -923,7 +935,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/zip/null",
@@ -945,7 +960,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -969,7 +984,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -993,7 +1008,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1017,7 +1032,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1040,7 +1055,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "premium_conference/country/null",
@@ -1062,7 +1080,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1086,7 +1104,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1110,7 +1128,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1134,7 +1152,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1157,7 +1175,10 @@
"country": " "
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/valid",
@@ -1178,7 +1199,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/missing billing",
@@ -1192,7 +1216,7 @@
}
},
"expected": {
"code": "billing_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1209,7 +1233,7 @@
"billing": {}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1233,7 +1257,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1257,7 +1281,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1281,7 +1305,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1305,7 +1329,7 @@
}
},
"expected": {
"code": "billing_name_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1328,7 +1352,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/email/null",
@@ -1350,7 +1377,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1374,7 +1401,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1398,7 +1425,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1422,7 +1449,7 @@
}
},
"expected": {
"code": "billing_email_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1445,7 +1472,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/address/null",
@@ -1467,7 +1497,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1491,7 +1521,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1515,7 +1545,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1539,7 +1569,7 @@
}
},
"expected": {
"code": "billing_address_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1562,7 +1592,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/city/null",
@@ -1584,7 +1617,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1608,7 +1641,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1632,7 +1665,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1656,7 +1689,7 @@
}
},
"expected": {
"code": "billing_city_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1679,7 +1712,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/zip/null",
@@ -1701,7 +1737,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1725,7 +1761,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1749,7 +1785,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1773,7 +1809,7 @@
}
},
"expected": {
"code": "billing_zip_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1796,7 +1832,10 @@
"country": "Country"
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "unlimited_conference/country/null",
@@ -1818,7 +1857,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1842,7 +1881,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1866,7 +1905,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1890,7 +1929,7 @@
}
},
"expected": {
"code": "billing_country_missing",
"code": "invalid_plan",
"status": 400
}
},
@@ -1913,7 +1952,10 @@
"country": " "
}
},
"expected": null
"expected": {
"code": "invalid_plan",
"status": 400
}
},
{
"name": "startDate/date/\"March 1 2031\"",
@@ -1984,7 +2026,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "startDate/date/{}",
@@ -1997,7 +2042,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "startDate/date/{\"toString\":\"bad\"}",
@@ -2028,7 +2076,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "startDate/date/[\"2031\",\"1\",\"1\"]",
@@ -2097,7 +2148,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "endDate/date/\"March 1 2031\"",
@@ -2165,7 +2219,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "endDate/date/{}",
@@ -2178,7 +2235,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "endDate/date/{\"toString\":\"bad\"}",
@@ -2209,7 +2269,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "endDate/date/[\"2031\",\"1\",\"1\"]",
@@ -2284,7 +2347,10 @@
"planID": "free_conference"
}
},
"expected": null
"expected": {
"code": "conf_start_date_invalid",
"status": 400
}
},
{
"name": "invalid start before expired end",
+44 -10
View File
@@ -17,7 +17,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -46,7 +47,8 @@
"false",
"-42",
"0"
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "Alice XXXX-5 XXXX-XXXX-1 XXXX-4 XXXX-2 XXXX-3 XXXX-5.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -73,7 +75,8 @@
"1e-7",
"100000000000000000000",
"1e+21"
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "Alice 0 1 -42 true false XXXX-1 XXXX-2 XXXX-3 1e+21 keep"
@@ -98,7 +101,8 @@
"",
"false",
"Alice"
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-3 0 1 -42 true XXXX-2 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -123,7 +127,8 @@
"0",
"1.25",
"9007199254740992"
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "Alice XXXX-1 1 -42 true false XXXX-1.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -169,6 +174,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationMode": "never",
"update": true,
"image": true,
@@ -225,6 +231,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationMode": "never",
"update": false,
"image": false,
@@ -274,6 +281,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": null,
"image": null,
"pdf": null,
@@ -318,6 +326,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": false,
"image": false,
"pdf": false,
@@ -362,6 +371,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": true,
"image": true,
"pdf": true,
@@ -406,6 +416,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": false,
"image": false,
"pdf": false,
@@ -450,6 +461,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": true,
"image": true,
"pdf": true,
@@ -494,6 +506,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": true,
"image": true,
"pdf": true,
@@ -538,6 +551,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": false,
"image": false,
"pdf": false,
@@ -582,6 +596,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": true,
"image": true,
"pdf": true,
@@ -626,6 +641,7 @@
"Alice",
""
],
"preserveFiles": [],
"update": false,
"image": false,
"pdf": false,
@@ -656,7 +672,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -681,7 +698,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -706,7 +724,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -731,7 +750,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
@@ -757,6 +777,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "1970-01-01T00:00:00.001Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -783,6 +804,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "1970-01-01T00:00:00.001Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -809,6 +831,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "1969-12-31T23:59:59.999Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -835,6 +858,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2023-11-14T22:13:20.123Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -861,6 +885,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-06-01T12:30:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -887,6 +912,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "0001-01-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -913,6 +939,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-03-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -939,6 +966,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-03-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -965,6 +993,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-03-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -995,6 +1024,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-03-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -1023,6 +1053,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-03-01T00:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -1049,6 +1080,7 @@
"Alice",
""
],
"preserveFiles": [],
"expirationDate": "2026-02-28T23:00:00.000Z"
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
@@ -1215,6 +1247,7 @@
"Alice",
""
],
"preserveFiles": [],
"pageSource": {
"branch": "docs",
"path": "/"
@@ -1244,7 +1277,8 @@
"terms": [
"Alice",
""
]
],
"preserveFiles": []
},
"input": "Alice 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep",
"output": "XXXX-1 0 1 -42 true false 0.000001 1e-7 100000000000000000000 1e+21 keep"
+94 -94
View File
@@ -9,7 +9,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -24,7 +24,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -39,7 +39,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -54,7 +54,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -69,7 +69,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -84,7 +84,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -99,7 +99,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -114,7 +114,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -129,7 +129,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -144,7 +144,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -159,7 +159,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -204,7 +204,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -234,7 +234,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -249,7 +249,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -264,7 +264,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -294,7 +294,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -309,7 +309,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -324,7 +324,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -339,7 +339,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -354,7 +354,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -369,7 +369,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -384,7 +384,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -399,7 +399,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -414,7 +414,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -429,7 +429,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -444,7 +444,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -459,7 +459,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -474,7 +474,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -489,7 +489,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -504,7 +504,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -519,7 +519,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -534,7 +534,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -549,7 +549,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -564,7 +564,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -579,7 +579,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -594,7 +594,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -609,7 +609,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -639,7 +639,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -654,7 +654,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -669,7 +669,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -684,7 +684,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -700,7 +700,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -715,7 +715,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -730,7 +730,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -745,7 +745,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -761,7 +761,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -776,7 +776,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -792,7 +792,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -807,7 +807,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -823,7 +823,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -868,7 +868,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -899,7 +899,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -914,7 +914,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -930,7 +930,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -960,7 +960,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -976,7 +976,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -992,7 +992,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1008,7 +1008,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1024,7 +1024,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1039,7 +1039,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1054,7 +1054,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1070,7 +1070,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1086,7 +1086,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1101,7 +1101,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1117,7 +1117,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1133,7 +1133,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1149,7 +1149,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1165,7 +1165,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1180,7 +1180,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1196,7 +1196,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1211,7 +1211,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1227,7 +1227,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1243,7 +1243,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1259,7 +1259,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1274,7 +1274,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1290,7 +1290,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1320,7 +1320,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948"
}
@@ -1335,7 +1335,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1351,7 +1351,7 @@
"encoding": "",
"length": "0",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1366,7 +1366,7 @@
"encoding": "",
"length": "0",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1381,7 +1381,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1411,7 +1411,7 @@
"encoding": "",
"length": "17",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 17,
"sha256": "d04fd59f3d9a1fd424c47874ae1dab0dde54fa73ba474245bfac79279afe6df7"
}
@@ -1426,7 +1426,7 @@
"encoding": "",
"length": "17",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 17,
"sha256": "d04fd59f3d9a1fd424c47874ae1dab0dde54fa73ba474245bfac79279afe6df7"
}
@@ -1441,7 +1441,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 17,
"sha256": "d04fd59f3d9a1fd424c47874ae1dab0dde54fa73ba474245bfac79279afe6df7"
}
@@ -1472,7 +1472,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Origin, Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1489,7 +1489,7 @@
"encoding": "gzip",
"length": "37",
"vary": "accept-encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1506,7 +1506,7 @@
"encoding": "gzip",
"length": "37",
"vary": "*",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1523,7 +1523,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Origin, Accept-Language, Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 2250,
"sha256": "2a7e6391e9ddb195fc5a11d2bf20cac2f435bb3622799a38b3690f75dd8af948",
"wire": "H4sIAAAAAAAAA6uoGAWjYBSMglEwCkbBKBiqAAAHzkXWyggAAA=="
@@ -1539,7 +1539,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1554,7 +1554,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1569,7 +1569,7 @@
"encoding": "gzip",
"length": "",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1599,7 +1599,7 @@
"encoding": "",
"length": "2250",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1614,7 +1614,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
@@ -1629,7 +1629,7 @@
"encoding": "gzip",
"length": "37",
"vary": "Accept-Encoding",
"ranges": "none",
"ranges": "",
"bodyBytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
+18 -6
View File
@@ -11,7 +11,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": null
@@ -128,7 +130,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": null
@@ -512,7 +516,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": {
@@ -532,7 +538,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": {
@@ -552,7 +560,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": {
@@ -572,7 +582,9 @@
"repositoryFullName": "owner/repo",
"pullRequestId": 42
},
"options": {},
"options": {
"preserveFiles": []
},
"terms": []
},
"expected": null
@@ -86,7 +86,7 @@ func runUserDefaultsIntegration(t *testing.T, s *Server) {
if err := json.Unmarshal(w.Body.Bytes(), &profile); err != nil {
t.Fatal(err)
}
if w.Code != 200 || !reflect.DeepEqual(profile, M{"username": "user-defaults-fixture", "isAdmin": false}) {
if w.Code != 200 || !reflect.DeepEqual(profile, M{"username": "user-defaults-fixture", "isAdmin": false, "emailNotificationsEnabled": false, "notificationEmail": "", "showEmailPrompt": false}) {
t.Fatal("absent photo", w.Code, w.Body)
}
if _, err := s.Store.update(ctx, "users", M{"_id": id}, M{"$set": M{"photo": nil}}); err != nil {
+1 -1
View File
@@ -31,7 +31,7 @@ func (s *Server) cachedPlainWebFile(key string) M {
return row
}
func (s *Server) cachePlainWebFile(key string, row M) {
data, err := json.Marshal(selectFields(row, "path", "name", "size", "sha"))
data, err := json.Marshal(selectFields(row, "path", "name", "size", "sha", "upstream", "submodule"))
if err != nil {
return
}
+4 -1
View File
@@ -155,7 +155,7 @@ func (s *Server) webview(q *request) (any, error) {
if ext != ".md" {
delivery = response
}
reader, cleanup, _, e := s.transformedResponse(q.ctx(), r, selected, delivery)
reader, cleanup, isText, e := s.transformedResponse(q.ctx(), r, selected, delivery)
if response.eligible {
sharedVary(q.W.Header())
}
@@ -168,6 +168,9 @@ func (s *Server) webview(q *request) (any, error) {
return nil, e
}
defer cleanup()
if isText {
q.W.Header().Set("Accept-Ranges", "none")
}
if current, e := s.Store.one(q.ctx(), collection("repo"), contentRevisionFilter(r)); e != nil {
return nil, e
} else if current == nil {
+5 -2
View File
@@ -183,6 +183,9 @@ func (s *Server) readArchiveInputs(ctx context.Context, r M, p provider.Reposito
seen[relative] = true
dir, name := path.Split(relative)
dir = strings.TrimSuffix(dir, "/")
if name == ".gitmodules" {
continue
}
if !fileAllowed(name, obj(r["options"])) {
continue
}
@@ -226,7 +229,7 @@ func (s *Server) readArchiveInputs(ctx context.Context, r M, p provider.Reposito
}
// Git export-ignore can omit tracked blobs. Retrieve only those exceptional
// entries via the regular provider path, preserving the existing ZIP output.
rows, err := s.Store.DB.Collection("files").Find(ctx, M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r), "size": M{"$ne": nil}}, options.Find().SetBatchSize(128).SetProjection(M{"path": 1, "name": 1, "sha": 1, "size": 1}))
rows, err := s.Store.DB.Collection("files").Find(ctx, M{"repoId": r["repoId"], "treeGeneration": activeGeneration(r), "size": M{"$ne": nil}}, options.Find().SetBatchSize(128).SetProjection(M{"path": 1, "name": 1, "sha": 1, "size": 1, "upstream": 1, "submodule": 1}))
if err != nil {
return err
}
@@ -279,7 +282,7 @@ func spoolArchiveInput(ctx context.Context, body io.Reader, size int64, row M, p
return archiveInput{}, err
}
err = nil // An empty file has a valid empty prefix.
entry := provider.Entry{Path: path.Join(str(row["path"]), str(row["name"])), Revision: str(row["sha"]), Size: number(row["size"])}
entry := fileProviderEntry(row)
proof := provider.ContentProof{GitSHA: hex.EncodeToString(gitHash.Sum(nil)), SHA256: hex.EncodeToString(digest.Sum(nil)), Size: n}
if verifier, exists := p.(provider.ArchiveContentVerifier); exists {
err = verifier.VerifyArchiveContent(ctx, access, entry, proof, prefix[:count])