From c201847b838f7ff86e62196f98efbef2f97d8a40 Mon Sep 17 00:00:00 2001 From: Thomas Durieux <5577568+tdurieux@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:12:47 +0000 Subject: [PATCH] feat(go): implement current Node backend features --- .github/workflows/go-backend.yml | 1 + Dockerfile | 2 +- README.md | 2 +- backend/README.md | 22 +- backend/contracts/conference-dates.cjs | 2 +- backend/contracts/conferences.cjs | 10 +- backend/contracts/content-verification.cjs | 4 +- backend/contracts/file-metadata.cjs | 1 + backend/contracts/options.cjs | 2 +- backend/contracts/preserve-files.cjs | 11 + .../contracts/resource-options-database.cjs | 4 +- backend/contracts/routes.json | 287 +- backend/contracts/shared-http.cjs | 2 +- backend/contracts/validation.cjs | 4 +- backend/go.mod | 6 +- backend/go.sum | 4 +- backend/internal/anonymize/anonymize.go | 15 +- backend/internal/anonymize/preserve.go | 131 + backend/internal/anonymize/preserve_glob.go | 259 ++ backend/internal/anonymize/preserve_test.go | 38 + .../anonymize/testdata/preserve-files.json | 3427 +++++++++++++++++ backend/internal/blobcache/schema.sql | 6 +- backend/internal/filetype/filetype.go | 13 +- backend/internal/provider/provider.go | 3 + backend/internal/provider/source_preview.go | 10 + backend/internal/server/account_email.go | 107 + backend/internal/server/admin_user.go | 4 +- backend/internal/server/auth.go | 4 + backend/internal/server/billing_api.go | 301 ++ backend/internal/server/billing_checkout.go | 243 ++ backend/internal/server/billing_client.go | 237 ++ backend/internal/server/billing_config.go | 107 + backend/internal/server/billing_content.go | 51 + backend/internal/server/billing_events.go | 194 + backend/internal/server/billing_expiration.go | 101 + backend/internal/server/billing_grants.go | 253 ++ .../server/billing_integration_test.go | 199 + .../internal/server/billing_maintenance.go | 203 + backend/internal/server/billing_plans.json | 102 + backend/internal/server/billing_quota.go | 218 ++ backend/internal/server/billing_report.go | 199 + backend/internal/server/billing_summary.go | 248 ++ .../conference_options_integration_test.go | 2 +- backend/internal/server/conferences.go | 102 +- .../server/conferences_integration_test.go | 12 +- backend/internal/server/config.go | 16 +- backend/internal/server/connections.go | 15 +- backend/internal/server/extension.go | 17 + backend/internal/server/files.go | 30 +- backend/internal/server/http.go | 38 +- backend/internal/server/indexes.go | 7 +- .../server/indexes_compatibility_test.go | 37 + backend/internal/server/integration_test.go | 2 + backend/internal/server/jobs.go | 22 +- backend/internal/server/new_features_test.go | 215 ++ .../server/oauth_callback_integration_test.go | 2 + .../server/oauth_install_integration_test.go | 3 + backend/internal/server/owner_alerts.go | 346 ++ backend/internal/server/partial_tree_test.go | 2 + backend/internal/server/pathindex.go | 4 +- backend/internal/server/provider_github.go | 27 +- .../server/provider_github_content.go | 13 +- backend/internal/server/quota.go | 36 +- backend/internal/server/raw.go | 4 +- backend/internal/server/refresh.go | 9 + backend/internal/server/registration_email.go | 81 + backend/internal/server/resources.go | 84 +- backend/internal/server/review.go | 186 + backend/internal/server/routes.go | 20 +- backend/internal/server/shared_cache.go | 4 + backend/internal/server/shared_http.go | 1 - backend/internal/server/source_preview.go | 187 + backend/internal/server/stage_metrics.go | 9 + backend/internal/server/submodules.go | 172 + .../internal/server/testdata/admin-user.json | 8 + .../internal/server/testdata/conferences.json | 214 +- backend/internal/server/testdata/options.json | 54 +- .../internal/server/testdata/shared-http.json | 188 +- .../internal/server/testdata/validation.json | 24 +- .../server/user_defaults_integration_test.go | 2 +- backend/internal/server/web_file_cache.go | 2 +- backend/internal/server/webview.go | 5 +- backend/internal/server/zip_archive.go | 7 +- backend/reports/main-alignment.json | 59 +- 84 files changed, 8921 insertions(+), 384 deletions(-) create mode 100644 backend/contracts/preserve-files.cjs create mode 100644 backend/internal/anonymize/preserve.go create mode 100644 backend/internal/anonymize/preserve_glob.go create mode 100644 backend/internal/anonymize/preserve_test.go create mode 100644 backend/internal/anonymize/testdata/preserve-files.json create mode 100644 backend/internal/provider/source_preview.go create mode 100644 backend/internal/server/account_email.go create mode 100644 backend/internal/server/billing_api.go create mode 100644 backend/internal/server/billing_checkout.go create mode 100644 backend/internal/server/billing_client.go create mode 100644 backend/internal/server/billing_config.go create mode 100644 backend/internal/server/billing_content.go create mode 100644 backend/internal/server/billing_events.go create mode 100644 backend/internal/server/billing_expiration.go create mode 100644 backend/internal/server/billing_grants.go create mode 100644 backend/internal/server/billing_integration_test.go create mode 100644 backend/internal/server/billing_maintenance.go create mode 100644 backend/internal/server/billing_plans.json create mode 100644 backend/internal/server/billing_quota.go create mode 100644 backend/internal/server/billing_report.go create mode 100644 backend/internal/server/billing_summary.go create mode 100644 backend/internal/server/indexes_compatibility_test.go create mode 100644 backend/internal/server/new_features_test.go create mode 100644 backend/internal/server/owner_alerts.go create mode 100644 backend/internal/server/registration_email.go create mode 100644 backend/internal/server/review.go create mode 100644 backend/internal/server/source_preview.go create mode 100644 backend/internal/server/submodules.go diff --git a/.github/workflows/go-backend.yml b/.github/workflows/go-backend.yml index f15f1d5..a48fa82 100644 --- a/.github/workflows/go-backend.yml +++ b/.github/workflows/go-backend.yml @@ -64,6 +64,7 @@ jobs: node backend/contracts/resources.cjs --check node backend/contracts/validation.cjs --check node backend/contracts/options.cjs --check + node backend/contracts/preserve-files.cjs --check node backend/contracts/dates.cjs --check node backend/contracts/reactivation.cjs --check node backend/contracts/oauth-tokens.cjs --check diff --git a/Dockerfile b/Dockerfile index 7008d68..d3b0827 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,7 @@ COPY public ./public COPY src ./src RUN npm run build:ui -FROM golang:1.27.3-bookworm AS build +FROM golang:1.27.4-bookworm AS build WORKDIR /src COPY backend/go.mod backend/go.sum ./ RUN --mount=type=cache,target=/go/pkg/mod go mod download diff --git a/README.md b/README.md index 3d03f4c..5673792 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ These tokens cannot access GitHub previews, file downloads, or admin routes. ## Self-hosting -On this migration branch, Docker runs the Go backend, including streaming and background workers. The branch includes current `main` sources, but newer billing, preview, and email APIs still need Go implementations; see the [alignment status](backend/README.md#branch-alignment-status-november-14-2026). See the [Go deployment and cutover guide](backend/README.md#default-deployment) before upgrading an existing installation. It covers queue handoff, storage permissions, staging checks and the preserved Node rollback stack. A full production staging rehearsal is still required before cutover. +On this migration branch, Docker runs the Go backend, including streaming and background workers. The branch includes current `main` sources and Go implementations of billing, source previews, email preferences, access notifications and public submodules; see the [alignment status](backend/README.md#branch-alignment-status-november-14-2026). See the [Go deployment and cutover guide](backend/README.md#default-deployment) before upgrading an existing installation. It covers queue handoff, storage permissions, staging checks and the preserved Node rollback stack. A full production staging rehearsal is still required before cutover. The following Node instructions also support the CLI, asset build and rollback backend. diff --git a/backend/README.md b/backend/README.md index 9675527..21ece2c 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,7 +2,7 @@ ## Branch alignment status, November 14, 2026 -This branch includes `main` through `511dcd7`, with Go restored after the Node-only deployment change. This is a source synchronization, not a completed migration of the newer features. The latest TypeScript route inventory adds 13 routes absent from Go, including billing, admin billing, preview file/tree access, and account email. See [the alignment report](reports/main-alignment.json) for the exact route list. Existing route behavior also needs a new parity audit, including paid hosting and bibliography redaction. Historical compatibility fixtures are retained; the current TypeScript route-inventory check remains blocking. Do not deploy the latest UI with Go as a replacement for current production until these gaps are addressed. +This branch includes `main` through `511dcd7`. Go now implements the 13 APIs added since the previous migration, along with paid hosting, bibliography preservation, account email preferences, access notifications, direct public GitHub submodules, and the mounted review-service capability endpoint. The current 125-route inventory and Node differential contracts are checked in CI. See [the alignment report](reports/main-alignment.json) for validation and remaining staging checks. Route coverage alone does not establish complete behavioral equivalence. This directory implements the API, authentication, repository processing, file serving, storage adapters and background jobs in Go. The existing browser application remains JavaScript. Node is used to build browser assets, run differential tests and perform offline data migration; it is absent from the runtime image. @@ -11,7 +11,7 @@ The root Docker deployment runs Go. The Node backend remains available through t ## Build and test -Use Go 1.27.3, Docker, and the repository's installed Node dependencies for differential checks. +Use Go 1.27.4, Docker, and the repository's installed Node dependencies for differential checks. ```sh cd backend @@ -32,6 +32,7 @@ node backend/contracts/compression.cjs --check node backend/contracts/json-http.cjs --check node backend/contracts/validation.cjs --check node backend/contracts/options.cjs --check +node backend/contracts/preserve-files.cjs --check node backend/contracts/dates.cjs --check node backend/contracts/reactivation.cjs --check node backend/contracts/oauth-tokens.cjs --check @@ -102,7 +103,7 @@ Reports in `reports/` record the comparison and benchmark results. `reports/comp - Integration and race tests exercise creation, tree publication, anonymized file output, access control, scoped and expired tokens, banned sessions, App permission restrictions and revocation during token issuance. - A hardened non-root container passed HTTP smoke checks and browser rendering of a Markdown script-injection fixture. - Tests reject truncated upstream content, unsafe raw-content redirects, filesystem traversal and symlink escapes. S3 protocol tests cover atomic publication and deletion boundaries. -- All 112 mounted TypeScript API routes are extracted from the router AST into `contracts/routes.json`. CI regenerates the inventory in check mode and verifies the first matching Go route template, so a generic route cannot conceal a missing specific endpoint. Healthcheck and webhook dispatch are exercised through HTTP. This checks dispatch, not every status code and JSON response. `/api/admin/cache` reports Go cache events with the TypeScript time windows, latency buckets and row schema. Fifteen contracts execute the TypeScript report to check window coercion and bucket definitions. +- All 125 mounted TypeScript API routes are extracted from the router AST into `contracts/routes.json`. CI regenerates the inventory in check mode and verifies the first matching Go route template, so a generic route cannot conceal a missing specific endpoint. Healthcheck and webhook dispatch are exercised through HTTP. This checks dispatch, not every status code and JSON response. `/api/admin/cache` reports Go cache events with the TypeScript time windows, latency buckets and row schema. Fifteen contracts execute the TypeScript report to check window coercion and bucket definitions. - `govulncheck` found zero reachable vulnerabilities and zero vulnerabilities in imported packages. It reported four advisories in required modules outside the packages used by this application; see `reports/govulncheck.txt`. GitHub HTTP responses are mocked in automated integration tests. S3 tests use an HTTP protocol fixture rather than a production provider. Those tests do not establish compatibility with every provider configuration. @@ -283,7 +284,7 @@ The following differences are deliberate or require staging review: - Repository membership changes carry a durable `conferenceMembership` event until both conference histories are updated. Drain these events before rollback to Node; Node does not replay them. Existing histories are preserved rather than inferred from repository status. - Existing repository rename/reconnect cases, legacy cache retirement, account recovery, conference billing, all admin filters, browser rendering and exact error/output parity are not exhaustively validated. These are production cutover gates, not covered by the route dispatch test. -Conference option persistence has 58 contracts from the actual TypeScript form helper and Mongoose schema. Boolean and string casts, null/empty dates, omitted or empty options, unknown fields and rejected types are checked through Go unit tests and HTTP/database tests. Non-owner responses retain the option representation and omit billing. Conference form validation has 121 contracts extracted from the TypeScript validator. Both creates and edits validate plans and required billing fields in the same order. Editing restores `ready` status and preserves the saved ID, owners, plan, billing and repository history. HTTP integration tests cover rejected edits without mutation, edits of ready/expired/removed conferences, creation and method-specific missing-conference errors. An additional 54 actual TypeScript/Mongoose contracts verify start/end Date construction and persistence. Legacy date strings, overflow dates, arrays, numeric milliseconds and coercion failures use the shared JavaScript date parser. Expiration options follow Mongoose casting, including numeric strings outside the year range and rejected booleans. Invalid stored dates/options return the TypeScript save error, 500 internal_error, without mutating the document. ISO date-only input is parsed as UTC. Listing conferences expires overdue ready conferences before returning, as in TypeScript. Expiry uses open membership records, overrides repository-level `never` expiration, and preserves already inactive statuses and timestamps. Integration tests cover ten repository states and closed or absent membership records. Conference removal waits for file, path-index and storage cleanup before returning. It attempts all open members, preserves archived repositories and closed memberships, and reports partial failure while keeping the conference removed. Tests cover owner authorization, synchronous cleanup, partial failure and repeated removal. History reconciliation preserves BSON document order in its compare-and-swap guard. `contracts/conference-output.cjs` adds 288 exact output cases from TypeScript, covering fractional rates, closed and open intervals, future additions/removals, conference-end caps, missing rates and long date ranges. Billing uses JavaScript millisecond arithmetic and operation order, including null for non-finite totals. Year 0001 is a valid conference end or membership removal date, not a missing-date sentinel. HTTP/database expiry and removal checks preserve memberships closed at year 0001 or the Unix epoch. Repository saves update membership history immediately for any provider. Joining opens an entry, switching closes the prior entry, leaving records a removal date, and rejoining resets the first existing entry as TypeScript does. An unchanged conference preserves its billing date and does not prevent settings edits after the conference expires. HTTP/database tests cover these transitions. A pending membership event is saved atomically with the repository revision. Failed history writes are replayed on later saves, conference reads or maintenance using the original timestamp. Strictly increasing save timestamps and event IDs protect newer transitions from stale replay. Fault-injection integration tests reject conference writes, recover both histories without shifting billing dates, and verify that delayed replay cannot undo a later move. Pending events have a sparse index. +Conference option persistence has 58 contracts from the actual TypeScript form helper and Mongoose schema. Boolean and string casts, null/empty dates, omitted or empty options, unknown fields and rejected types are checked through Go unit tests and HTTP/database tests. Non-owner responses retain the option representation and omit billing. Conference form validation has 121 contracts extracted from the TypeScript validator. Both creates and edits validate plans and required billing fields in the same order. Editing preserves the saved status, ID, owners, plan, billing and repository history; it cannot reactivate an expired or removed conference. HTTP integration tests cover rejected edits without mutation, edits of ready/expired/removed conferences, creation and method-specific missing-conference errors. An additional 54 actual TypeScript/Mongoose contracts verify start/end Date construction and persistence. Legacy date strings, overflow dates, arrays, numeric milliseconds and coercion failures use the shared JavaScript date parser. Expiration options follow Mongoose casting, including numeric strings outside the year range and rejected booleans. Invalid stored dates/options return the TypeScript save error, 500 internal_error, without mutating the document. ISO date-only input is parsed as UTC. Listing conferences expires overdue ready conferences before returning, as in TypeScript. Expiry uses open membership records, overrides repository-level `never` expiration, and preserves already inactive statuses and timestamps. Integration tests cover ten repository states and closed or absent membership records. Conference removal waits for file, path-index and storage cleanup before returning. It attempts all open members, preserves archived repositories and closed memberships, and reports partial failure while keeping the conference removed. Tests cover owner authorization, synchronous cleanup, partial failure and repeated removal. History reconciliation preserves BSON document order in its compare-and-swap guard. `contracts/conference-output.cjs` adds 288 exact output cases from TypeScript, covering fractional rates, closed and open intervals, future additions/removals, conference-end caps, missing rates and long date ranges. Billing uses JavaScript millisecond arithmetic and operation order, including null for non-finite totals. Year 0001 is a valid conference end or membership removal date, not a missing-date sentinel. HTTP/database expiry and removal checks preserve memberships closed at year 0001 or the Unix epoch. Repository saves update membership history immediately for any provider. Joining opens an entry, switching closes the prior entry, leaving records a removal date, and rejoining resets the first existing entry as TypeScript does. An unchanged conference preserves its billing date and does not prevent settings edits after the conference expires. HTTP/database tests cover these transitions. A pending membership event is saved atomically with the repository revision. Failed history writes are replayed on later saves, conference reads or maintenance using the original timestamp. Strictly increasing save timestamps and event IDs protect newer transitions from stale replay. Fault-injection integration tests reject conference writes, recover both histories without shifting billing dates, and verify that delayed replay cannot undo a later move. Pending events have a sparse index. Admin list filters have 111 contracts extracted from the TypeScript route handlers. They cover literal search escaping, owner/conference/date filters, status flags and query output shape. Unknown owners return no repositories. Conference status flags apply, and the repository preparing filter includes preparing/downloading entries. Storage totals appear only on repository responses. HTTP integration tests cover status selection, unknown owners, administrator access and credential exclusion. Another 138 TypeScript contracts cover pagination and sorting. Admin lists parse extended query values with JavaScript integer-prefix and Number rounding behavior, including signed decimal/hexadecimal values and arrays. Page numbers no longer have the former one-million cap. Limit retains TypeScript's upper bound of 1,000. Negative limits use MongoDB's single-batch find behavior for repository/conference lists and fail for the user aggregation. Negative skips fail instead of silently using a default. Sort/direction/CSV selection require scalar values as in TypeScript. The sort pattern is compiled once and rejects operator-prefixed fields and trailing newlines. HTTP tests verify ordered pages, bracketed values, large pages, invalid MongoDB pagination, administrator access and CSV bypass of pagination. Extended filters retain distinct find/count and aggregation semantics, covered below. CSV exports have 45 exact TypeScript output contracts covering empty/minimal rows, leading whitespace, quotes, commas, line breaks, Unicode, dates and numeric formatting. Go matches the empty repository header, filename quoting and lack of a trailing newline. Exports retain the 50,000-row limit and credential exclusion. @@ -633,3 +634,16 @@ ZIP requests have a 30-minute overall deadline. Other API requests retain their Anonymization workers now release execution slots and memory reservations as soon as the child has exited and its output is on disk, including cache hits. Output file handles remain valid until the caller's cleanup. A slow reader therefore cannot hold the only worker slot and cause another transform to hit the 30-second admission timeout. Request transfer limits and the ZIP pipeline's unbuffered handoffs still bound outstanding output files. The worker test keeps multiple cold/cached outputs open with one configured worker and verifies that both execution and memory admission are available before cleanup. Authenticated browser sessions persist for 30 days and renew on activity at most once per day, giving a 29–30 day idle lifetime. Redis expiry and the Secure/HttpOnly/SameSite=Lax cookie are renewed together. Existing valid session cookies upgrade on their next authenticated request. Renewal uses compare-and-set so it cannot resurrect a logged-out session or overwrite concurrent session changes. Account status is still checked on every request. Anonymous OAuth sessions remain browser-session cookies with a 24-hour Redis lifetime; OAuth state still expires after ten minutes. Preserve the session secret and Redis volume across deployments. + + +## Current Node feature additions + +Billing uses the existing Node collections and environment variables described in [paid hosting](../docs/paid-hosting.md). It includes checkout recovery, customer portals, saved drafts, subscriptions and one-time grants, pack fulfillment, signed webhook ingestion, reconciliation, revocation, admin sales reports, and scoped repository/storage quotas. Legacy repositories retain their existing hosting treatment. Paid conference edits retain their plan and status; activation requires payment. Tests use mocked Stripe responses and disposable databases; live Stripe test-mode browser and webhook validation remains a cutover check. + +The source preview capability exposes tree and file previews through both the existing GitHub routes and provider-neutral repository routes. Saved repository access still checks ownership, provider identity and credentials. Direct public GitHub submodules retain their pinned source provenance through file reads, cache verification and streaming ZIP output. Child repositories are read anonymously, without forwarding the parent's credentials. Nested, private, unsupported and oversized submodules remain unavailable. + +`preserveFiles` follows ordered include/exclude glob rules, with 475 Node-generated cases. Matching file contents retain configured terms while filenames, link rewriting and other anonymization settings retain their normal behavior. Pattern execution and expansion are bounded. + +Account profiles and connections support notification preferences, verified GitHub email discovery and the email prompt. Access alerts use recipient-level durable suppression and owner revision fencing. Expired preparations can be recovered only before delivery commitment; ambiguous sends are not retried. Startup imports historical delivery evidence and legacy resource claims. The Go implementation uses a conservative rescan rather than Node's checkpointed migration, so large notification histories can lengthen startup. + +The mounted review capability endpoint accepts only configured service credentials and rejects browser credentials, cookies and origin headers. The review page uses a restricted content-security policy. Other review modules that are not mounted by the current Node server are not exposed by Go. diff --git a/backend/contracts/conference-dates.cjs b/backend/contracts/conference-dates.cjs index 16f647a..009ff39 100644 --- a/backend/contracts/conference-dates.cjs +++ b/backend/contracts/conference-dates.cjs @@ -5,7 +5,7 @@ const schema=require('../../src/core/model/conference/conferences.schema').defau const Model=mongoose.model('conference_date_contract',schema); const source=ts.createSourceFile('conference.ts',fs.readFileSync('src/server/routes/conference.ts','utf8'),ts.ScriptTarget.Latest,true); const apply=source.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name?.text==='applyConferenceForm'); -const mod={exports:{}};vm.runInNewContext(ts.transpile(apply.getText(source)+';module.exports=applyConferenceForm',{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}),{module:mod,exports:{},Date}); +const mod={exports:{}};vm.runInNewContext(ts.transpile(apply.getText(source)+';module.exports=applyConferenceForm',{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}),{module:mod,exports:{},Date,isConferencePlan:id=>["conference","conference_workshop","conference_large"].includes(id)}); const values=['March 1 2031','2031-02-30','0001-01-01','0000-01-01','-000001-01-01','+010000-01-01','2031-01-01T24:00:00Z','2031-01-01T01:00:00+02:00','invalid','',null,false,true,0,1,1.5,-1.5,1924992000000,'1924992000000',8640000000000001,{}, {toString:'bad'}, {valueOf:1},[],['2031','1','1'],[1],[null]]; const cases=[]; for(const field of ['startDate','endDate'])for(const value of values){ diff --git a/backend/contracts/conferences.cjs b/backend/contracts/conferences.cjs index a19417d..e73ba85 100644 --- a/backend/contracts/conferences.cjs +++ b/backend/contracts/conferences.cjs @@ -7,13 +7,17 @@ const path = 'src/server/routes/conference.ts'; const tree = ts.createSourceFile(path, fs.readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true); const validator = tree.statements.find(s => ts.isFunctionDeclaration(s) && s.name?.text === 'validateConferenceForm'); const plans = tree.statements.find(s => ts.isVariableStatement(s) && s.declarationList.declarations.some(d => d.name.getText(tree) === 'plans')); -assert.ok(validator && plans); +assert.ok(validator); +process.env.SESSION_SECRET ||= 'synthetic-conference-contract'; +require('ts-node/register/transpile-only'); +const billing = require('../../src/core/billing/config'); +const helpers=tree.statements.filter(s=>ts.isFunctionDeclaration(s)&&['conferencePlans','offeredConferencePlans'].includes(s.name?.text)); const now = '2030-01-01T00:00:00.000Z'; class FixedDate extends Date { constructor(...args) { super(...(args.length ? args : [now])); } } class AnonymousError extends Error { constructor(code, options) { super(code); this.status = options.httpStatus; } } -const code = ts.transpileModule(`${plans.getText(tree)}\n${validator.getText(tree)}\nmodule.exports = validateConferenceForm;`, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS}}).outputText; +const code = ts.transpileModule(`${helpers.map(s=>s.getText(tree)).join("\n")}\n${validator.getText(tree)}\nmodule.exports = validateConferenceForm;`, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS}}).outputText; const moduleObject = {exports: {}}; -vm.runInNewContext(code, {module: moduleObject, AnonymousError, Date: FixedDate}); +vm.runInNewContext(code, {module: moduleObject, exports:moduleObject.exports, AnonymousError, Date: FixedDate, config:{BILLING_ENABLED:false}, billingPlans:billing.billingPlans, isConferencePlan:billing.isConferencePlan, billingError:(code,status=400)=>new AnonymousError(code,{httpStatus:status})}); const base = {name: 'Conference', conferenceID: 'conference-test', startDate: '2031-01-01', endDate: '2031-02-01', plan: {planID: 'free_conference'}}; const cases = []; function add(name, change) { diff --git a/backend/contracts/content-verification.cjs b/backend/contracts/content-verification.cjs index b366f96..82ac70e 100644 --- a/backend/contracts/content-verification.cjs +++ b/backend/contracts/content-verification.cjs @@ -12,7 +12,7 @@ function visit(node) { ts.forEachChild(node, visit); } visit(tree); assert.ok(expression); -const code=ts.transpileModule(`module.exports=function(expected){return ${expression}}`, {compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText; +const code=ts.transpileModule(`module.exports=function(expected,origin){return ${expression}}`, {compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText; const fixture={exports:{}}; vm.runInNewContext(code,{module:fixture,Buffer,createHash,setTimeout,clearTimeout}); const git = value => createHash('sha1').update(`blob ${Buffer.byteLength(value)}\0`).update(value).digest('hex'); @@ -40,7 +40,7 @@ const inputs=[ for (const [name,pointer,revision=git(pointer)] of inputs) { const row={name,pointer,revision,proof}; let fetched=0; - const verify=fixture.exports.call({data:{getToken:async()=> 'synthetic'},downloadFile:()=>{fetched++;return Readable.from([Buffer.from(pointer)]);}}, {sha:revision}); + const verify=fixture.exports.call({data:{getToken:async()=> 'synthetic'},downloadFile:()=>{fetched++;return Readable.from([Buffer.from(pointer)]);}}, {sha:revision}, {downloadFile:()=>{fetched++;return Readable.from([Buffer.from(pointer)]);}}); try { row.expected=await verify(proof); } catch(error) { row.error=error.message; } row.fetched=fetched;rows.push(row); } diff --git a/backend/contracts/file-metadata.cjs b/backend/contracts/file-metadata.cjs index cb0c3b8..ec86a21 100644 --- a/backend/contracts/file-metadata.cjs +++ b/backend/contracts/file-metadata.cjs @@ -6,6 +6,7 @@ const config={MAX_FILE_SIZE:100*1024*1024,SHARED_CACHE_ENABLED:false}; let current, transfers=0; class File { constructor(){} + async assertContentFile(){} async originalPath(){return current.name} isFileSupported(){return true} async sha(){return 'blob'} diff --git a/backend/contracts/options.cjs b/backend/contracts/options.cjs index 0234eee..0fabd59 100644 --- a/backend/contracts/options.cjs +++ b/backend/contracts/options.cjs @@ -22,7 +22,7 @@ for (const [kind, route, helper, modelName] of [ compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS}, }).outputText; const module = {exports: {}}; - vm.runInNewContext(code, {module, Date}); + vm.runInNewContext(code, {module, Date, normalizePreserveFiles: require("../../src/core/preserve-files").normalizePreserveFiles}); const schema = require(`../../src/core/model/${modelName}/${modelName}.schema.ts`).default; const Model = mongoose.model(`options_contract_${kind}`, schema); const add = (name, options, terms = ['Alice', '']) => { diff --git a/backend/contracts/preserve-files.cjs b/backend/contracts/preserve-files.cjs new file mode 100644 index 0000000..a175918 --- /dev/null +++ b/backend/contracts/preserve-files.cjs @@ -0,0 +1,11 @@ +const fs=require('node:fs'); +const assert=require('node:assert/strict'); +process.env.SESSION_SECRET ||= 'synthetic-preserve-contract'; +require('ts-node/register/transpile-only'); +const {isPreservedPath,normalizePreserveFiles}=require('../../src/core/preserve-files'); +const patterns=[['*.bib'],['/refs.bib'],['paper/**','!paper/private/'],['*.bib','!secret.bib','secret.bib'],['paper/'],['/paper/\\{a,b\\}.bib'],['**/*.{bib,json}'],['file{01..03}.txt'],['file{a..c}.txt'],['@(a|b).bib'],['+(a|b).bib'],['?(a|b).bib'],['*(a|b).bib'],['*.bib','!private/**'],['[!a]*.bib'],['**/.hidden'],['[draft].bib'],['\\[draft\\].bib'],['{a,{b,c}}.bib']]; +const paths=['refs.bib','sub/refs.bib','secret.bib','paper','paper/a.bib','paper/private/a.bib','paper/a.json','paper/{a,b}.bib','file01.txt','file02.txt','file03.txt','file04.txt','filea.txt','fileb.txt','filec.txt','a.bib','b.bib','c.bib','ab.bib','.bib','.hidden','sub/.hidden','[draft].bib','private/a.bib','d.bib']; +const cases=patterns.flatMap(patterns=>paths.map(path=>({patterns,path,expected:isPreservedPath(path,patterns)}))); +const target='backend/internal/anonymize/testdata/preserve-files.json';const output=JSON.stringify(cases,null,2)+'\n'; +if(process.argv.includes('--check'))assert.equal(fs.readFileSync(target,'utf8'),output);else fs.writeFileSync(target,output); +console.log(`${cases.length} preservation cases`); diff --git a/backend/contracts/resource-options-database.cjs b/backend/contracts/resource-options-database.cjs index 50c3a42..8893b27 100644 --- a/backend/contracts/resource-options-database.cjs +++ b/backend/contracts/resource-options-database.cjs @@ -12,12 +12,12 @@ const mongoose=require('mongoose'); const tree=ts.createSourceFile('route-utils.ts',fs.readFileSync('src/server/routes/route-utils.ts','utf8'),ts.ScriptTarget.Latest,true); const errorHelper=tree.statements.find(s=>ts.isFunctionDeclaration(s)&&s.name?.text==='handleError'); const errorModule={exports:{}}; - vm.runInNewContext(ts.transpile(errorHelper.getText(tree).replace(/^export\s+/, '')+';module.exports=handleError',{target:ts.ScriptTarget.ES2022}),{module:errorModule,Error,AnonymousError:require('../../src/core/AnonymousError').default,printError:()=>{}}); + vm.runInNewContext(ts.transpile(errorHelper.getText(tree).replace(/^export\s+/, '')+';module.exports=handleError',{target:ts.ScriptTarget.ES2022}),{module:errorModule,Error,AnonymousError:require('../../src/core/AnonymousError').default,printError:()=>{},isResponseCancellation:()=>false}); const cases=[]; for(const [kind,route,helper,modelName] of [['repo','repository','updateRepoModel','anonymizedRepositories'],['gist','gist','updateGistModel','anonymizedGists'],['pr','pullRequest','updatePullRequestModel','anonymizedPullRequests']]){ const source=ts.createSourceFile(route,fs.readFileSync(`src/server/routes/${route}-private.ts`,'utf8'),ts.ScriptTarget.Latest,true); const fn=source.statements.find(s=>ts.isFunctionDeclaration(s)&&s.name?.text===helper); - const mod={exports:{}};vm.runInNewContext(ts.transpile(fn.getText(source)+';module.exports='+helper,{target:ts.ScriptTarget.ES2022}),{module:mod,Date}); + const mod={exports:{}};vm.runInNewContext(ts.transpile(fn.getText(source)+';module.exports='+helper,{target:ts.ScriptTarget.ES2022}),{module:mod,Date,normalizePreserveFiles:require("../../src/core/preserve-files").normalizePreserveFiles}); const Model=connection.model(modelName,require(`../../src/core/model/${modelName}/${modelName}.schema.ts`).default); const options=[{}, {image:'bad'}, {image:[]}, {image:{}}, {expirationDate:'bad'}, {expirationDate:[]}, {expirationDate:{}}, {expirationDate:{toString:'bad'}}, {expirationDate:1e16}, {expirationDate:'0001-01-01'}, {expirationDate:['2030','3','1']}, {image:'bad',expirationDate:'bad',link:false}, {image:true,link:false}, {expirationMode:0}, {expirationMode:true}, {expirationMode:{}}, {expirationMode:[]}, {expirationMode:{_id:'date'}}, {pageSource:{branch:1,path:false}}, {pageSource:{branch:{},path:'/'}}, {pageSource:{branch:[],path:{}}}, {pageSource:null}, {pageSource:true}, {pageSource:[]}, {pageSource:{unknown:'ignored'}}]; for(const create of [true,false])for(const input of options){ diff --git a/backend/contracts/routes.json b/backend/contracts/routes.json index 88e135f..a90aa4d 100644 --- a/backend/contracts/routes.json +++ b/backend/contracts/routes.json @@ -3,98 +3,161 @@ "method": "POST", "path": "/github/app/webhook", "source": "src/server/routes/github-app.ts", - "line": 267, + "line": 308, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/api/billing/webhook", + "source": "src/server/routes/billing.ts", + "line": 19, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/app/login", "source": "src/server/routes/github-app.ts", - "line": 40, + "line": 49, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/app/callback", "source": "src/server/routes/github-app.ts", - "line": 56, + "line": 65, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/app/install", "source": "src/server/routes/github-app.ts", - "line": 95, + "line": 106, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/app/setup", "source": "src/server/routes/github-app.ts", - "line": 127, + "line": 138, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/connections", "source": "src/server/routes/github-app.ts", - "line": 150, + "line": 162, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/github/connections/email", + "source": "src/server/routes/github-app.ts", + "line": 200, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/github/connections/email", + "source": "src/server/routes/github-app.ts", + "line": 209, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/github/connections/migrate", "source": "src/server/routes/github-app.ts", - "line": 187, + "line": 227, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/github/connections/disconnect-oauth", "source": "src/server/routes/github-app.ts", - "line": 246, + "line": 287, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/account-recovery", "source": "src/server/routes/connection.ts", - "line": 193, + "line": 201, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/login", "source": "src/server/routes/connection.ts", - "line": 198, + "line": 206, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/github/auth", "source": "src/server/routes/connection.ts", - "line": 215, + "line": 223, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/github/login-token", "source": "src/server/routes/connection.ts", - "line": 243, + "line": 251, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/api/billing", + "source": "src/server/routes/billing.ts", + "line": 78, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/api/billing/draft/:id", + "source": "src/server/routes/billing.ts", + "line": 99, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/api/billing/draft", + "source": "src/server/routes/billing.ts", + "line": 111, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/api/billing/checkout", + "source": "src/server/routes/billing.ts", + "line": 119, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/api/billing/portal", + "source": "src/server/routes/billing.ts", + "line": 132, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "POST", + "path": "/api/billing/refresh", + "source": "src/server/routes/billing.ts", + "line": 141, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/maintenance/repositories/:repoId", "source": "src/server/routes/maintenance.ts", - "line": 28, + "line": 34, "verification": "first matching Go handler; behavior verified separately" }, { "method": "PATCH", "path": "/api/maintenance/repositories/:repoId", "source": "src/server/routes/maintenance.ts", - "line": 41, + "line": 47, "verification": "first matching Go handler; behavior verified separately" }, { @@ -139,200 +202,214 @@ "line": 67, "verification": "first matching Go handler; behavior verified separately" }, + { + "method": "GET", + "path": "/api/admin/billing/summary", + "source": "src/server/routes/admin-billing.ts", + "line": 16, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/api/admin/billing/grants", + "source": "src/server/routes/admin-billing.ts", + "line": 24, + "verification": "first matching Go handler; behavior verified separately" + }, { "method": "GET", "path": "/api/admin/performance", "source": "src/server/routes/admin.ts", - "line": 87, + "line": 89, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/cache", "source": "src/server/routes/admin.ts", - "line": 93, + "line": 95, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/:repo_id", "source": "src/server/routes/admin.ts", - "line": 180, + "line": 182, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/admin/queue/:name/:repo_id", "source": "src/server/routes/admin.ts", - "line": 205, + "line": 207, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/retry-failed", "source": "src/server/routes/admin.ts", - "line": 233, + "line": 235, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/drain", "source": "src/server/routes/admin.ts", - "line": 254, + "line": 256, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/pause", "source": "src/server/routes/admin.ts", - "line": 265, + "line": 267, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/resume", "source": "src/server/routes/admin.ts", - "line": 276, + "line": 278, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queue/:name/empty", "source": "src/server/routes/admin.ts", - "line": 287, + "line": 289, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/queues/pause-all", "source": "src/server/routes/admin.ts", - "line": 298, + "line": 300, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/queues/metrics", "source": "src/server/routes/admin.ts", - "line": 354, + "line": 356, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/queues", "source": "src/server/routes/admin.ts", - "line": 369, + "line": 371, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/errors", "source": "src/server/routes/admin.ts", - "line": 430, + "line": 441, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/errors/stats", "source": "src/server/routes/admin.ts", - "line": 475, + "line": 486, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/admin/errors", "source": "src/server/routes/admin.ts", - "line": 606, + "line": 617, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/overview", "source": "src/server/routes/admin.ts", - "line": 636, + "line": 647, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/stats", "source": "src/server/routes/admin.ts", - "line": 821, + "line": 832, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/repos", "source": "src/server/routes/admin.ts", - "line": 850, + "line": 861, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/admin/repos/:repoId", "source": "src/server/routes/admin.ts", - "line": 969, + "line": 980, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/repos/:repoId/github", "source": "src/server/routes/admin.ts", - "line": 984, + "line": 995, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/users", "source": "src/server/routes/admin.ts", - "line": 1077, + "line": 1088, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/users/:username", "source": "src/server/routes/admin.ts", - "line": 1141, + "line": 1152, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/users/:username/repos", "source": "src/server/routes/admin.ts", - "line": 1168, + "line": 1179, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/users/:username/ban", "source": "src/server/routes/admin.ts", - "line": 1189, + "line": 1200, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/users/:username/activate", "source": "src/server/routes/admin.ts", - "line": 1225, + "line": 1236, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/users/:username/promote", "source": "src/server/routes/admin.ts", - "line": 1243, + "line": 1254, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/admin/users/:username/demote", "source": "src/server/routes/admin.ts", - "line": 1261, + "line": 1272, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/admin/conferences", "source": "src/server/routes/admin.ts", - "line": 1279, + "line": 1290, "verification": "first matching Go handler; behavior verified separately" }, { @@ -346,168 +423,168 @@ "method": "GET", "path": "/api/conferences/plans", "source": "src/server/routes/conference.ts", - "line": 44, + "line": 36, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/conferences", "source": "src/server/routes/conference.ts", - "line": 48, + "line": 40, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/conferences/{:conferenceID}", "source": "src/server/routes/conference.ts", - "line": 163, + "line": 159, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/conferences/:conferenceID", "source": "src/server/routes/conference.ts", - "line": 234, + "line": 230, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/conferences/:conferenceID", "source": "src/server/routes/conference.ts", - "line": 272, + "line": 275, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/logout", "source": "src/server/routes/user.ts", - "line": 27, + "line": 31, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user", "source": "src/server/routes/user.ts", - "line": 40, + "line": 44, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/dashboard", "source": "src/server/routes/user.ts", - "line": 53, + "line": 68, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/quota", "source": "src/server/routes/user.ts", - "line": 58, + "line": 73, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/user/project-name", "source": "src/server/routes/user.ts", - "line": 134, + "line": 159, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/default", "source": "src/server/routes/user.ts", - "line": 143, + "line": 168, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/user/default", "source": "src/server/routes/user.ts", - "line": 153, + "line": 178, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/user", "source": "src/server/routes/user.ts", - "line": 175, + "line": 200, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/anonymized_repositories", "source": "src/server/routes/user.ts", - "line": 251, + "line": 281, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/anonymized_gists", "source": "src/server/routes/user.ts", - "line": 269, + "line": 299, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/anonymized_pull_requests", "source": "src/server/routes/user.ts", - "line": 284, + "line": 314, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/search/github-users", "source": "src/server/routes/user.ts", - "line": 301, + "line": 331, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/all_repositories", "source": "src/server/routes/user.ts", - "line": 336, + "line": 366, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/user/:username/all_repositories", "source": "src/server/routes/user.ts", - "line": 347, + "line": 377, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/zip", "source": "src/server/routes/repository-public.ts", - "line": 23, + "line": 27, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/files", "source": "src/server/routes/repository-public.ts", - "line": 184, + "line": 192, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/files/counts", "source": "src/server/routes/repository-public.ts", - "line": 204, + "line": 212, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/files/search", "source": "src/server/routes/repository-public.ts", - "line": 256, + "line": 275, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/options", "source": "src/server/routes/repository-public.ts", - "line": 275, + "line": 294, "verification": "first matching Go handler; behavior verified separately" }, { @@ -521,91 +598,105 @@ "method": "POST", "path": "/api/repo/claim", "source": "src/server/routes/repository-private.ts", - "line": 71, + "line": 79, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/repo/:repoId/refresh", "source": "src/server/routes/repository-private.ts", - "line": 144, + "line": 153, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/repo/:repoId/extend", "source": "src/server/routes/repository-private.ts", - "line": 177, + "line": 187, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/repo/:repoId", "source": "src/server/routes/repository-private.ts", - "line": 240, + "line": 260, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:owner/:repo", "source": "src/server/routes/repository-private.ts", - "line": 267, + "line": 287, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:owner/:repo/branches", "source": "src/server/routes/repository-private.ts", - "line": 286, + "line": 306, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:owner/:repo/readme", "source": "src/server/routes/repository-private.ts", - "line": 310, + "line": 330, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/api/repo/:owner/:repo/tree", + "source": "src/server/routes/repository-private.ts", + "line": 363, + "verification": "first matching Go handler; behavior verified separately" + }, + { + "method": "GET", + "path": "/api/repo/:owner/:repo/file", + "source": "src/server/routes/repository-private.ts", + "line": 386, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId", "source": "src/server/routes/repository-private.ts", - "line": 343, + "line": 412, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/repo/:repoId", "source": "src/server/routes/repository-private.ts", - "line": 490, + "line": 568, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/repo", "source": "src/server/routes/repository-private.ts", - "line": 663, + "line": 788, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/repo/:repoId/coauthors", "source": "src/server/routes/repository-private.ts", - "line": 773, + "line": 905, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/repo/:repoId/coauthors", "source": "src/server/routes/repository-private.ts", - "line": 789, + "line": 921, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/repo/:repoId/coauthors/:username", "source": "src/server/routes/repository-private.ts", - "line": 852, + "line": 984, "verification": "first matching Go handler; behavior verified separately" }, { @@ -626,49 +717,49 @@ "method": "POST", "path": "/api/pr/:pullRequestId/refresh", "source": "src/server/routes/pullRequest-private.ts", - "line": 24, + "line": 25, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/pr/:pullRequestId/extend", "source": "src/server/routes/pullRequest-private.ts", - "line": 43, + "line": 45, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/pr/:pullRequestId", "source": "src/server/routes/pullRequest-private.ts", - "line": 83, + "line": 86, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/pr/:owner/:repository/:pullRequestId", "source": "src/server/routes/pullRequest-private.ts", - "line": 104, + "line": 107, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/pr/:pullRequestId", "source": "src/server/routes/pullRequest-private.ts", - "line": 130, + "line": 133, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/pr/:pullRequestId", "source": "src/server/routes/pullRequest-private.ts", - "line": 218, + "line": 221, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/pr", "source": "src/server/routes/pullRequest-private.ts", - "line": 254, + "line": 258, "verification": "first matching Go handler; behavior verified separately" }, { @@ -689,84 +780,84 @@ "method": "POST", "path": "/api/gist/:gistId/refresh", "source": "src/server/routes/gist-private.ts", - "line": 23, + "line": 24, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/gist/:gistId/extend", "source": "src/server/routes/gist-private.ts", - "line": 42, + "line": 44, "verification": "first matching Go handler; behavior verified separately" }, { "method": "DELETE", "path": "/api/gist/:gistId", "source": "src/server/routes/gist-private.ts", - "line": 80, + "line": 83, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/gist/source/:gistId", "source": "src/server/routes/gist-private.ts", - "line": 102, + "line": 105, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/gist/:gistId", "source": "src/server/routes/gist-private.ts", - "line": 125, + "line": 128, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/gist/:gistId", "source": "src/server/routes/gist-private.ts", - "line": 199, + "line": 202, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/gist", "source": "src/server/routes/gist-private.ts", - "line": 234, + "line": 238, "verification": "first matching Go handler; behavior verified separately" }, { "method": "POST", "path": "/api/anonymize-preview", "source": "src/server/routes/anonymize-preview.ts", - "line": 17, + "line": 19, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/message", "source": "src/server/index.ts", - "line": 259, + "line": 282, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/healthcheck", "source": "src/server/index.ts", - "line": 266, + "line": 289, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/stat", "source": "src/server/index.ts", - "line": 269, + "line": 292, "verification": "first matching Go handler; behavior verified separately" }, { "method": "GET", "path": "/api/stat/history", "source": "src/server/index.ts", - "line": 272, + "line": 295, "verification": "first matching Go handler; behavior verified separately" }, { diff --git a/backend/contracts/shared-http.cjs b/backend/contracts/shared-http.cjs index 2f4412c..078a296 100644 --- a/backend/contracts/shared-http.cjs +++ b/backend/contracts/shared-http.cjs @@ -4,7 +4,7 @@ const express=require('express'),ts=require('typescript'); const fixture={exports:{}}; let active; const results={decision:()=>({digest:active.record.digest,changed:false})}; -const dependencies={zlib,crypto,stream,'stream/promises':require('node:stream/promises'),perf_hooks:require('node:perf_hooks'),'../config':{default:{ANONYMIZATION_MASK:'XXXX',APP_HOSTNAME:'anonymous.test',additionalExtensions:[]}},'./blob-cache':{resultBlobCache:()=>results,CacheAdmissionError:class extends Error{}},'./anonymize-utils':{},'./cache-observability':{observeCache(){}}}; +const dependencies={zlib,crypto,stream,'stream/promises':require('node:stream/promises'),perf_hooks:require('node:perf_hooks'),'../config':{default:{ANONYMIZATION_MASK:'XXXX',APP_HOSTNAME:'anonymous.test',additionalExtensions:[]}},'./blob-cache':{resultBlobCache:()=>results,CacheAdmissionError:class extends Error{}},'./anonymize-utils':{classifyByName:()=>false},'./transformed-cache':{assertTransformScopeActive:async()=>{}},'./cache-observability':{observeCache(){}}}; vm.runInNewContext(ts.transpileModule(fs.readFileSync('src/core/cached-response.ts','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{module:fixture,exports:fixture.exports,require:name=>{assert.ok(dependencies[name],name);return dependencies[name]}}); const cases=[]; const accepts=['','gzip','identity','br','deflate','*','identity, gzip','gzip, identity','gzip;q=.5,identity;q=1','gzip;q=1,identity;q=.5','gzip;q=0','identity;q=0','*;q=0','gzip,identity;q=0','identity;q=0,br','gzip;q=0,*;q=1','*;q=0,gzip;q=1','gzip;q=NaN','gzip;q=-1','gzip;q=2','gzip;q=Infinity','gzip;q=1junk','gzip;q= 0.5','gzip;Q=0','gzip;q =0','gzip;q=0,gzip;q=1','gzip;q=1,gzip;q=0','gzip garbage','GZIP', 'unknown;q=-1,gzip',',,,gzip','gzip,,,','gzip;q="0"','gzip;q="0.5,identity;q=0"','gzip;q="\\0"','gzip;q="0','gzip;q=','gzip;q=;q=0','gzip;q=0;q=1','gzip;Q = "0.5"','gzip;broken;q=0','gzip garbage;q=-1','gzip;level="a,b;c";q=0','identity;q=0,*;q=.5']; diff --git a/backend/contracts/validation.cjs b/backend/contracts/validation.cjs index ee8e858..fc2cda3 100644 --- a/backend/contracts/validation.cjs +++ b/backend/contracts/validation.cjs @@ -2,12 +2,14 @@ const fs=require('node:fs');const vm=require('node:vm');const assert=require('node:assert/strict');const ts=require('typescript'); class AnonymousError extends Error{constructor(message,options){super(message);this.httpStatus=options?.httpStatus}} const specifications=[['repo','repository','validateNewRepo','repoId'],['gist','gist','validateNewGist','gistId'],['pr','pullRequest','validateNewPullRequest','pullRequestId']]; +process.env.SESSION_SECRET ||= 'synthetic-validation';require('ts-node/register/transpile-only'); +const {normalizePreserveFiles}=require('../../src/core/preserve-files'); const cases=[]; for(const [kind,file,name,id] of specifications){ const path=`src/server/routes/${file}-private.ts`;const text=fs.readFileSync(path,'utf8');const tree=ts.createSourceFile(path,text,ts.ScriptTarget.Latest,true); const declaration=tree.statements.find(s=>ts.isFunctionDeclaration(s)&&s.name?.text===name);assert.ok(declaration,name); const code=ts.transpileModule(`${declaration.getText(tree)};module.exports=${name}`,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText; - const module={exports:{}};vm.runInNewContext(code,{module,AnonymousError});const validate=module.exports; + const module={exports:{}};vm.runInNewContext(code,{module,AnonymousError,normalizePreserveFiles});const validate=module.exports; const base={[id]:'example',source:{branch:'main',commit:'abc123',gistId:'snippet',repositoryFullName:'owner/repo',pullRequestId:42},options:{},terms:[]}; const add=(name,change)=>{const body=structuredClone(base);change(body);let expected=null;try{validate(body)}catch(e){assert.ok(e instanceof AnonymousError,`${kind}/${name}: unexpected TS runtime exception`);expected={code:e.message,status:e.httpStatus}}cases.push({name:`${kind}/${name}`,kind,body,expected})}; add('valid',()=>{}); diff --git a/backend/go.mod b/backend/go.mod index f3a039b..83c7e2a 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/tdurieux/anonymous_github/backend -go 1.27.3 +go 1.27.4 require ( github.com/andybalholm/brotli v1.2.7 @@ -9,10 +9,11 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 github.com/dlclark/regexp2 v1.12.0 github.com/google/uuid v1.6.0 - github.com/klauspost/compress v1.19.2 + github.com/klauspost/compress v1.20.2 github.com/redis/go-redis/v9 v9.23.0 go.mongodb.org/mongo-driver/v2 v2.9.2 golang.org/x/sync v0.24.0 + golang.org/x/sys v0.49.0 golang.org/x/text v0.43.0 modernc.org/sqlite v1.61.1 ) @@ -38,7 +39,6 @@ require ( github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect go.uber.org/atomic v1.12.0 // indirect golang.org/x/crypto v0.53.0 // indirect - golang.org/x/sys v0.49.0 // indirect modernc.org/libc v1.79.0 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect diff --git a/backend/go.sum b/backend/go.sum index 2e4d07d..6fcfe89 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -44,8 +44,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= -github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= -github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= diff --git a/backend/internal/anonymize/anonymize.go b/backend/internal/anonymize/anonymize.go index 25a4e39..03f5f10 100644 --- a/backend/internal/anonymize/anonymize.go +++ b/backend/internal/anonymize/anonymize.go @@ -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"` diff --git a/backend/internal/anonymize/preserve.go b/backend/internal/anonymize/preserve.go new file mode 100644 index 0000000..963e6e9 --- /dev/null +++ b/backend/internal/anonymize/preserve.go @@ -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 +} diff --git a/backend/internal/anonymize/preserve_glob.go b/backend/internal/anonymize/preserve_glob.go new file mode 100644 index 0000000..28b8c42 --- /dev/null +++ b/backend/internal/anonymize/preserve_glob.go @@ -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 +} diff --git a/backend/internal/anonymize/preserve_test.go b/backend/internal/anonymize/preserve_test.go new file mode 100644 index 0000000..6fc94d2 --- /dev/null +++ b/backend/internal/anonymize/preserve_test.go @@ -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) + } +} diff --git a/backend/internal/anonymize/testdata/preserve-files.json b/backend/internal/anonymize/testdata/preserve-files.json new file mode 100644 index 0000000..2b29105 --- /dev/null +++ b/backend/internal/anonymize/testdata/preserve-files.json @@ -0,0 +1,3427 @@ +[ + { + "patterns": [ + "*.bib" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "sub/refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "secret.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "*.bib" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "/refs.bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "paper/a.json", + "expected": true + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "paper/**", + "!paper/private/" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "sub/refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "secret.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!secret.bib", + "secret.bib" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "paper/" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "paper/" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "paper/" + ], + "path": "paper/a.json", + "expected": true + }, + { + "patterns": [ + "paper/" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "paper/" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "paper/" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "/paper/\\{a,b\\}.bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "sub/refs.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "secret.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "paper/a.json", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "**/*.{bib,json}" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "file01.txt", + "expected": true + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "file02.txt", + "expected": true + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "file03.txt", + "expected": true + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "file{01..03}.txt" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "filea.txt", + "expected": true + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "fileb.txt", + "expected": true + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "filec.txt", + "expected": true + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "file{a..c}.txt" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "@(a|b).bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "+(a|b).bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "?(a|b).bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "*(a|b).bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "sub/refs.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "secret.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "ab.bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": ".bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "*.bib", + "!private/**" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "refs.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "sub/refs.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "secret.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "paper/{a,b}.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "[!a]*.bib" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": ".hidden", + "expected": true + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "sub/.hidden", + "expected": true + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "**/.hidden" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "[draft].bib" + ], + "path": "d.bib", + "expected": true + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "paper/a.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "paper/private/a.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "a.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "b.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "c.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "[draft].bib", + "expected": true + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "private/a.bib", + "expected": false + }, + { + "patterns": [ + "\\[draft\\].bib" + ], + "path": "d.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "refs.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "sub/refs.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "secret.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "paper", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "paper/a.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "paper/private/a.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "paper/a.json", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "paper/{a,b}.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "file01.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "file02.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "file03.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "file04.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "filea.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "fileb.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "filec.txt", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "a.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "b.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "c.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "ab.bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": ".bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": ".hidden", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "sub/.hidden", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "[draft].bib", + "expected": false + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "private/a.bib", + "expected": true + }, + { + "patterns": [ + "{a,{b,c}}.bib" + ], + "path": "d.bib", + "expected": false + } +] diff --git a/backend/internal/blobcache/schema.sql b/backend/internal/blobcache/schema.sql index d846fe4..cfc7564 100644 --- a/backend/internal/blobcache/schema.sql +++ b/backend/internal/blobcache/schema.sql @@ -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; diff --git a/backend/internal/filetype/filetype.go b/backend/internal/filetype/filetype.go index bf834bb..cb7f95a 100644 --- a/backend/internal/filetype/filetype.go +++ b/backend/internal/filetype/filetype.go @@ -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 diff --git a/backend/internal/provider/provider.go b/backend/internal/provider/provider.go index bd3eb42..6a6601d 100644 --- a/backend/internal/provider/provider.go +++ b/backend/internal/provider/provider.go @@ -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 diff --git a/backend/internal/provider/source_preview.go b/backend/internal/provider/source_preview.go new file mode 100644 index 0000000..d291031 --- /dev/null +++ b/backend/internal/provider/source_preview.go @@ -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) +} diff --git a/backend/internal/server/account_email.go b/backend/internal/server/account_email.go new file mode 100644 index 0000000..9f96e20 --- /dev/null +++ b/backend/internal/server/account_email.go @@ -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 +} diff --git a/backend/internal/server/admin_user.go b/backend/internal/server/admin_user.go index 2a1f552..b4c68f4 100644 --- a/backend/internal/server/admin_user.go +++ b/backend/internal/server/admin_user.go @@ -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) } diff --git a/backend/internal/server/auth.go b/backend/internal/server/auth.go index ff7a22f..e102903 100644 --- a/backend/internal/server/auth.go +++ b/backend/internal/server/auth.go @@ -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 } diff --git a/backend/internal/server/billing_api.go b/backend/internal/server/billing_api.go new file mode 100644 index 0000000..43c4731 --- /dev/null +++ b/backend/internal/server/billing_api.go @@ -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 +} diff --git a/backend/internal/server/billing_checkout.go b/backend/internal/server/billing_checkout.go new file mode 100644 index 0000000..edfcdc4 --- /dev/null +++ b/backend/internal/server/billing_checkout.go @@ -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 +} diff --git a/backend/internal/server/billing_client.go b/backend/internal/server/billing_client.go new file mode 100644 index 0000000..8f9e56e --- /dev/null +++ b/backend/internal/server/billing_client.go @@ -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") diff --git a/backend/internal/server/billing_config.go b/backend/internal/server/billing_config.go new file mode 100644 index 0000000..c076dbe --- /dev/null +++ b/backend/internal/server/billing_config.go @@ -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 +} diff --git a/backend/internal/server/billing_content.go b/backend/internal/server/billing_content.go new file mode 100644 index 0000000..6dec592 --- /dev/null +++ b/backend/internal/server/billing_content.go @@ -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 +} diff --git a/backend/internal/server/billing_events.go b/backend/internal/server/billing_events.go new file mode 100644 index 0000000..201fa56 --- /dev/null +++ b/backend/internal/server/billing_events.go @@ -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< 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 + }) +} diff --git a/backend/internal/server/billing_integration_test.go b/backend/internal/server/billing_integration_test.go new file mode 100644 index 0000000..6a9ef35 --- /dev/null +++ b/backend/internal/server/billing_integration_test.go @@ -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) + } + } +} diff --git a/backend/internal/server/billing_maintenance.go b/backend/internal/server/billing_maintenance.go new file mode 100644 index 0000000..8173e95 --- /dev/null +++ b/backend/internal/server/billing_maintenance.go @@ -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() +} diff --git a/backend/internal/server/billing_plans.json b/backend/internal/server/billing_plans.json new file mode 100644 index 0000000..6f866c5 --- /dev/null +++ b/backend/internal/server/billing_plans.json @@ -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." + } +] diff --git a/backend/internal/server/billing_quota.go b/backend/internal/server/billing_quota.go new file mode 100644 index 0000000..6e06078 --- /dev/null +++ b/backend/internal/server/billing_quota.go @@ -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 +} diff --git a/backend/internal/server/billing_report.go b/backend/internal/server/billing_report.go new file mode 100644 index 0000000..e5fcabd --- /dev/null +++ b/backend/internal/server/billing_report.go @@ -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 +} diff --git a/backend/internal/server/billing_summary.go b/backend/internal/server/billing_summary.go new file mode 100644 index 0000000..815447a --- /dev/null +++ b/backend/internal/server/billing_summary.go @@ -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 +} diff --git a/backend/internal/server/conference_options_integration_test.go b/backend/internal/server/conference_options_integration_test.go index 209ea2b..5709edb 100644 --- a/backend/internal/server/conference_options_integration_test.go +++ b/backend/internal/server/conference_options_integration_test.go @@ -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) } diff --git a/backend/internal/server/conferences.go b/backend/internal/server/conferences.go index 9a078e3..0565d02 100644 --- a/backend/internal/server/conferences.go +++ b/backend/internal/server/conferences.go @@ -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": "
  • Quota is deducted from user account
  • \n
  • No-download
  • \n
  • Conference dashboard
  • "}, - {"id": "premium_conference", "name": "Premium", "pricePerRepo": 0.5, "storagePerRepo": 500 * 8 * 1024, "description": "
  • 500Mo / repository
  • \n
  • Repository download
  • \n
  • Conference dashboard
  • "}, - {"id": "unlimited_conference", "name": "Unlimited", "pricePerRepo": 3, "storagePerRepo": 0, "description": "
  • Unlimited repository size
  • \n
  • Repository download
  • \n
  • Conference dashboard
  • "}, + {"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": "
  • Uses each author's allowance
  • Conference dashboard
  • "}} + } + 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("
  • Up to %d repositories
  • Up to 180 days
  • Prepaid at checkout
  • ", 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) diff --git a/backend/internal/server/conferences_integration_test.go b/backend/internal/server/conferences_integration_test.go index 4394465..be867c2 100644 --- a/backend/internal/server/conferences_integration_test.go +++ b/backend/internal/server/conferences_integration_test.go @@ -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"} { diff --git a/backend/internal/server/config.go b/backend/internal/server/config.go index 2ce70a3..994b73e 100644 --- a/backend/internal/server/config.go +++ b/backend/internal/server/config.go @@ -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 { diff --git a/backend/internal/server/connections.go b/backend/internal/server/connections.go index a9764af..6ab968b 100644 --- a/backend/internal/server/connections.go +++ b/backend/internal/server/connections.go @@ -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 } diff --git a/backend/internal/server/extension.go b/backend/internal/server/extension.go index 12281de..7eb9825 100644 --- a/backend/internal/server/extension.go +++ b/backend/internal/server/extension.go @@ -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 diff --git a/backend/internal/server/files.go b/backend/internal/server/files.go index 88c5805..84c6714 100644 --- a/backend/internal/server/files.go +++ b/backend/internal/server/files.go @@ -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 +} diff --git a/backend/internal/server/http.go b/backend/internal/server/http.go index 2c72d41..16beb46 100644 --- a/backend/internal/server/http.go +++ b/backend/internal/server/http.go @@ -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 diff --git a/backend/internal/server/indexes.go b/backend/internal/server/indexes.go index 3a5ab7d..7dbfad6 100644 --- a/backend/internal/server/indexes.go +++ b/backend/internal/server/indexes.go @@ -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)}}, diff --git a/backend/internal/server/indexes_compatibility_test.go b/backend/internal/server/indexes_compatibility_test.go new file mode 100644 index 0000000..b7e53b2 --- /dev/null +++ b/backend/internal/server/indexes_compatibility_test.go @@ -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) + } + } +} diff --git a/backend/internal/server/integration_test.go b/backend/internal/server/integration_test.go index 20ad5dd..f222a38 100644 --- a/backend/internal/server/integration_test.go +++ b/backend/internal/server/integration_test.go @@ -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) }) diff --git a/backend/internal/server/jobs.go b/backend/internal/server/jobs.go index e5e88af..2e192f5 100644 --- a/backend/internal/server/jobs.go +++ b/backend/internal/server/jobs.go @@ -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() diff --git a/backend/internal/server/new_features_test.go b/backend/internal/server/new_features_test.go new file mode 100644 index 0000000..fd67550 --- /dev/null +++ b/backend/internal/server/new_features_test.go @@ -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) + } + } +} diff --git a/backend/internal/server/oauth_callback_integration_test.go b/backend/internal/server/oauth_callback_integration_test.go index 5764d9a..a689a6f 100644 --- a/backend/internal/server/oauth_callback_integration_test.go +++ b/backend/internal/server/oauth_callback_integration_test.go @@ -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"} diff --git a/backend/internal/server/oauth_install_integration_test.go b/backend/internal/server/oauth_install_integration_test.go index 850160f..b6413ef 100644 --- a/backend/internal/server/oauth_install_integration_test.go +++ b/backend/internal/server/oauth_install_integration_test.go @@ -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 { diff --git a/backend/internal/server/owner_alerts.go b/backend/internal/server/owner_alerts.go new file mode 100644 index 0000000..1ac4e17 --- /dev/null +++ b/backend/internal/server/owner_alerts.go @@ -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() +} diff --git a/backend/internal/server/partial_tree_test.go b/backend/internal/server/partial_tree_test.go index 6c30770..519429e 100644 --- a/backend/internal/server/partial_tree_test.go +++ b/backend/internal/server/partial_tree_test.go @@ -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: diff --git a/backend/internal/server/pathindex.go b/backend/internal/server/pathindex.go index 5c5069e..6fe41a3 100644 --- a/backend/internal/server/pathindex.go +++ b/backend/internal/server/pathindex.go @@ -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 } diff --git a/backend/internal/server/provider_github.go b/backend/internal/server/provider_github.go index e9d1d88..3f37557 100644 --- a/backend/internal/server/provider_github.go +++ b/backend/internal/server/provider_github.go @@ -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) diff --git a/backend/internal/server/provider_github_content.go b/backend/internal/server/provider_github_content.go index 9293df3..54d0d36 100644 --- a/backend/internal/server/provider_github_content.go +++ b/backend/internal/server/provider_github_content.go @@ -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") diff --git a/backend/internal/server/quota.go b/backend/internal/server/quota.go index ecf1876..9d99cf7 100644 --- a/backend/internal/server/quota.go +++ b/backend/internal/server/quota.go @@ -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 } diff --git a/backend/internal/server/raw.go b/backend/internal/server/raw.go index 808db24..bbd27c0 100644 --- a/backend/internal/server/raw.go +++ b/backend/internal/server/raw.go @@ -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 { diff --git a/backend/internal/server/refresh.go b/backend/internal/server/refresh.go index ae38c57..9b6dbb7 100644 --- a/backend/internal/server/refresh.go +++ b/backend/internal/server/refresh.go @@ -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 { diff --git a/backend/internal/server/registration_email.go b/backend/internal/server/registration_email.go new file mode 100644 index 0000000..937c94f --- /dev/null +++ b/backend/internal/server/registration_email.go @@ -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 + } +} diff --git a/backend/internal/server/resources.go b/backend/internal/server/resources.go index 8a77177..28c7b87 100644 --- a/backend/internal/server/resources.go +++ b/backend/internal/server/resources.go @@ -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") { diff --git a/backend/internal/server/review.go b/backend/internal/server/review.go new file mode 100644 index 0000000..2a4f7c9 --- /dev/null +++ b/backend/internal/server/review.go @@ -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(`Artifact consent · Anonymous GitHub
    `, 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)) + } +} diff --git a/backend/internal/server/routes.go b/backend/internal/server/routes.go index fcbd593..f7f80eb 100644 --- a/backend/internal/server/routes.go +++ b/backend/internal/server/routes.go @@ -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")) diff --git a/backend/internal/server/shared_cache.go b/backend/internal/server/shared_cache.go index 61ff5a0..674f563 100644 --- a/backend/internal/server/shared_cache.go +++ b/backend/internal/server/shared_cache.go @@ -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) diff --git a/backend/internal/server/shared_http.go b/backend/internal/server/shared_http.go index 3712fe4..15fc13c 100644 --- a/backend/internal/server/shared_http.go +++ b/backend/internal/server/shared_http.go @@ -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)) diff --git a/backend/internal/server/source_preview.go b/backend/internal/server/source_preview.go new file mode 100644 index 0000000..7b7a3eb --- /dev/null +++ b/backend/internal/server/source_preview.go @@ -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 +} diff --git a/backend/internal/server/stage_metrics.go b/backend/internal/server/stage_metrics.go index 5445b46..0668757 100644 --- a/backend/internal/server/stage_metrics.go +++ b/backend/internal/server/stage_metrics.go @@ -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 } diff --git a/backend/internal/server/submodules.go b/backend/internal/server/submodules.go new file mode 100644 index 0000000..259206c --- /dev/null +++ b/backend/internal/server/submodules.go @@ -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 +} diff --git a/backend/internal/server/testdata/admin-user.json b/backend/internal/server/testdata/admin-user.json index 3e8f846..813b1f7 100644 --- a/backend/internal/server/testdata/admin-user.json +++ b/backend/internal/server/testdata/admin-user.json @@ -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", diff --git a/backend/internal/server/testdata/conferences.json b/backend/internal/server/testdata/conferences.json index 167f5f6..3c974d7 100644 --- a/backend/internal/server/testdata/conferences.json +++ b/backend/internal/server/testdata/conferences.json @@ -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", diff --git a/backend/internal/server/testdata/options.json b/backend/internal/server/testdata/options.json index d0768a6..7ce2505 100644 --- a/backend/internal/server/testdata/options.json +++ b/backend/internal/server/testdata/options.json @@ -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" diff --git a/backend/internal/server/testdata/shared-http.json b/backend/internal/server/testdata/shared-http.json index 9d94140..0c7c0d0 100644 --- a/backend/internal/server/testdata/shared-http.json +++ b/backend/internal/server/testdata/shared-http.json @@ -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" } diff --git a/backend/internal/server/testdata/validation.json b/backend/internal/server/testdata/validation.json index b623fd3..0255305 100644 --- a/backend/internal/server/testdata/validation.json +++ b/backend/internal/server/testdata/validation.json @@ -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 diff --git a/backend/internal/server/user_defaults_integration_test.go b/backend/internal/server/user_defaults_integration_test.go index 2291db6..3ed9cd7 100644 --- a/backend/internal/server/user_defaults_integration_test.go +++ b/backend/internal/server/user_defaults_integration_test.go @@ -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 { diff --git a/backend/internal/server/web_file_cache.go b/backend/internal/server/web_file_cache.go index 2cc3430..43fb9a3 100644 --- a/backend/internal/server/web_file_cache.go +++ b/backend/internal/server/web_file_cache.go @@ -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 } diff --git a/backend/internal/server/webview.go b/backend/internal/server/webview.go index 78384f6..9fc968c 100644 --- a/backend/internal/server/webview.go +++ b/backend/internal/server/webview.go @@ -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 { diff --git a/backend/internal/server/zip_archive.go b/backend/internal/server/zip_archive.go index 83c92b5..78c25da 100644 --- a/backend/internal/server/zip_archive.go +++ b/backend/internal/server/zip_archive.go @@ -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]) diff --git a/backend/reports/main-alignment.json b/backend/reports/main-alignment.json index 2f090ee..c8cb066 100644 --- a/backend/reports/main-alignment.json +++ b/backend/reports/main-alignment.json @@ -1,8 +1,40 @@ { "mainCommit": "511dcd706791e551243fd2682765825f82473afc", "restoredGoFrom": "bff2e343fdc6fc09ff0f373a34bef9716b06bc00^", - "status": "Branch synchronized; current-main behavior parity is not complete", - "newTypeScriptRoutes": [ + "status": "Current-main feature implementation complete; isolated validation recorded below, live cutover checks pending", + "removedTypeScriptRoutes": [], + "notes": [ + "Node reference is committed main 511dcd706791e551243fd2682765825f82473afc, not uncommitted work in another checkout.", + "Route coverage is supplemented by differential fixtures, isolated MongoDB/Redis integration tests and mocked upstream lifecycle tests; it is not a proof of complete behavioral equivalence.", + "Live Stripe test-mode checkout/webhooks, Resend delivery, OAuth/App callbacks and a sanitized production-data upgrade still require staging validation.", + "No production or beta deployment was performed." + ], + "validation": { + "goIntegrationRace": "passed on Go 1.27.4 with disposable MongoDB/Redis; final index-name change additionally passed its focused race test and rebuilt deployment smoke test", + "goVet": "passed on Go 1.27.4", + "nodeContracts": "65 scripts passed on Go 1.27.4", + "routeInventory": "125 current TypeScript routes verified", + "goDockerBuild": "passed with Go 1.27.4 and klauspost/compress v1.20.2", + "deploymentSmoke": "passed: isolated startup, non-root writes, static routes, graceful shutdown, Node rollback compose model", + "reachableVulnerabilities": "none reported by govulncheck v1.9.0; four advisories remain in required modules without reachable calls", + "existingNodeIndexes": "passed with race detector: pre-existing named submodule index and repeated Go startup" + }, + "changes": [ + "Restore Go backend and Go deployment on top of current main", + "Update Node rollback Dockerfile to current main runtime and native dependency checks", + "Migrate shared cache decision classification column and clear stale classification when Go replaces a decision", + "Implement billing checkout, drafts, portal, signed webhooks, reconciliation, grants, revocation, scoped quotas and admin reporting", + "Preserve existing unmanaged hosting and implement paid conference activation/immutable plans", + "Implement source tree/file previews through optional provider capabilities", + "Implement preserveFiles rules for previews, individual files and ZIP output", + "Implement email preferences, verified registration email capture and owner access alerts with durable recipient guards", + "Expand direct public GitHub submodules and retain source provenance without sharing parent credentials", + "Implement mounted review capabilities endpoint and protected review page", + "Refresh current Node contract fixtures and add preservation, billing, review, provider preview, submodule and notification tests", + "Patch reachable vulnerabilities GO-2026-6859 and GO-2026-6865 by updating Go and klauspost/compress", + "Reuse the existing Node submodule index name during Go startup" + ], + "implementedTypeScriptRoutes": [ { "method": "GET", "path": "/api/admin/billing/grants" @@ -56,22 +88,11 @@ "path": "/github/connections/email" } ], - "removedTypeScriptRoutes": [], - "notes": [ - "Historical Go route fixtures remain unchanged. The routes.cjs --check gate detects the new inventory and remains blocking.", - "New TypeScript behavior on existing routes also requires a separate compatibility audit.", - "No production or beta deployment was performed." - ], - "validation": { - "goTest": "passed; database integration tests require their separate Docker runner", - "goVet": "passed", - "npmBuild": "passed", - "routeInventory": "fails: current TypeScript inventory differs from historical Go contract", - "cacheRace": "passed: Node interoperability, replacement classification, capacity and expiry batches" - }, - "changes": [ - "Restore Go backend and Go deployment on top of current main", - "Update Node rollback Dockerfile to current main runtime and native dependency checks", - "Migrate shared cache decision classification column and clear stale classification when Go replaces a decision" + "routeCount": 125, + "contractScripts": 65, + "implementationDifferences": [ + "Owner notification history is conservatively rescanned at startup rather than using Node migration checkpoints.", + "Submodule ZIP entries use bounded per-file source reads after the parent tar stream, rather than a second tar stream for each child.", + "Stripe price display and admin summary responses are not cached; checkout/reconciliation persistence and idempotency are retained." ] }