Compare commits

...

12 Commits

Author SHA1 Message Date
Arunavo Ray 53f2cf36fc chore: bump version to 3.16.3 2026-05-27 14:53:34 +05:30
ARUNAVO RAY 8ffcf3bdc6 fix: bridge header auth into a real Better Auth session (#303)
Header / forward authentication has been end-to-end broken since the
v3 rewrite. The middleware populated `context.locals.user` from
trusted upstream headers (Authentik / Authelia / oauth2-proxy /
Caddy), but never minted a Better Auth session, and never set a
cookie. Server-rendered pages saw the user, but the React SPA's
`/api/auth/get-session` call hit Better Auth's handler — which only
reads its session cookie — and got `null`. The auth guard then
redirected to `/login`, even though the upstream proxy had already
authenticated the user.

Reported on issue #29 by @lanrat with a clean repro on v3.16.1.

Fix: add a small Better Auth plugin (`header-auth`) that exposes
`POST /api/auth/sign-in/header`. The endpoint validates the trusted
headers via `authenticateWithHeaders`, creates a real session row via
`internalAdapter.createSession`, and attaches the `Set-Cookie` via
`setSessionCookie` — the same pattern the magic-link, anonymous, and
phone-number plugins use after their respective verification steps.

The Astro middleware now calls this endpoint when no cookie session
exists and header auth is enabled, forwards the `Set-Cookie` onto the
outbound response, and populates `context.locals` from the minted
session. After the first request the browser has the cookie; every
subsequent request takes the normal cookie-auth fast path and the
bridge doesn't fire.

Fail-open everywhere: any endpoint failure (header auth disabled,
auth rejected, DB blip, malformed response) returns null from the
bridge and the request proceeds as anonymous. A broken header-auth
configuration must never lock everyone out of the cookie-auth path.

Tests:
- `auth-header.test.ts` — unit tests for `extractUserFromHeaders` and
  `isHeaderAuthEnabled`, including lanrat's reported config shape
  (same header for username and email).
- `auth-header-plugin.test.ts` — locks down plugin id, endpoint key,
  path, and method so an accidental rename can't silently break the
  middleware bridge.
- `auth-header-bridge.test.ts` — covers the cookie-extraction logic
  and the fail-open paths (non-2xx, thrown error, malformed JSON,
  missing fields, no Set-Cookie attached).

Stacks on top of #301 (better-auth 1.6.11 bump).

Refs: #29
2026-05-27 14:53:16 +05:30
ARUNAVO RAY a07af96f84 chore: bump better-auth to 1.6.11 (#301)
Updates `better-auth` and `@better-auth/sso` from 1.5.5 to 1.6.11 to
pick up the patch fixes that have landed since (OAuth state CSRF
verification, scrypt non-blocking password hashing, account cookie
comparison fix, session freshness alignment, etc.). All 270 local
tests pass against the new version.

The only behavioral surface to watch:
  - `freshAge` now aligns with session `createdAt` instead of
    `updatedAt`. Not applicable here — we don't gate anything on
    session freshness.
  - 1.6.2 adds OAuth state-parameter CSRF verification. Applies to
    OIDC/SAML SSO flows; no code changes needed.
  - 1.6 emits a deprecation warning for `oidc-provider` in favor of
    `@better-auth/oauth-provider`. The plugin still works in 1.6.x;
    migrating it is a separate cleanup.

Prep work for an upcoming header-auth fix (issue #29 follow-up).
2026-05-27 14:44:17 +05:30
Arunavo Ray b1daa65228 chore: bump version to 3.16.2 2026-05-26 11:09:31 +05:30
Sean Mousseau dd1c42264e fix: stop snapshot-row zombies + flapping force-push on deleted branches (#300)
* fix: stop snapshot-row zombies + flapping force-push on deleted branches

Two bugs caused Simple-WP-Helpdesk to accumulate one orphan
"Snapshot created" job row per scheduled sync — 7 zombies in 24h
against a deleted GitHub branch (`fix/v4.0.2-webhook-comment-author`).

(1) gitea-enhanced.ts:522 created the post-snapshot job record with
status="syncing". The snapshot was already complete at that point
(createPreSyncBundleBackup had returned), and no later code path
advanced the row to a terminal status — it just lingered. Set
status="synced" to reflect reality.

(2) force-push-detection treated any Gitea branch missing from GitHub
as a "deleted" force-push. But gitea-mirror is one-way (GitHub →
Gitea), so deletions never propagate back to the Gitea mirror —
the branch lingers in Gitea forever, the missing-from-GitHub condition
holds on every subsequent sync, and detection re-fires endlessly.
Each re-fire triggered backupBeforeSync=true to take a fresh snapshot
of the exact same state we already backed up the previous cycle.

Fix: detector accepts an `acknowledgedDeletions: { branch, giteaSha }[]`
list (persisted in RepositoryMetadataState). A Gitea branch missing
from GitHub is suppressed when its current giteaSha matches an entry.
If the giteaSha later changes (branch restored, then re-deleted with
new history), the entry won't match and detection fires again — back
up the new state, then acknowledge the new SHA. After a successful
snapshot, the call site appends each just-backed-up "deleted" branch
to the acknowledged list and persists the metadata blob.

Hoists parseRepositoryMetadataState above the backup-strategy block so
both the detection-time read and post-snapshot append happen against
the same in-memory state object; the existing metadata-mirror block
just stops re-declaring it.

Adds 9 new test cases covering:
  - deleted branch suppressed when acknowledged at matching giteaSha
  - re-flagged when giteaSha differs (restored-then-redeleted)
  - mixed deletions (only matching one suppressed)
  - undefined list = back-compat (existing callers unaffected)
  - acknowledgedDeletions does not suppress "diverged"
  - metadata-state parse/serialize round-trips the new field
  - legacy metadata defaults acknowledgedDeletions to []
  - malformed entries dropped without throwing

All 76 tests in the affected suites pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: acknowledge deletion before backup, not after, to fix concurrent-sync race

When two sync invocations fire for the same repo within the same backup
window (observed in prod via UI trigger pipeline: a single click ends up
producing two parallel processWithResilience callbacks that both run
syncGiteaRepoEnhanced), the second invocation's createPreSyncBundleBackup
short-circuits (file already exists from the first), so the second
invocation never reached the acknowledge-push that lived inside the
backup try block. Then both invocations wrote metadata: invocation A
with acknowledgedDeletions=[forged], invocation B (with its stale
in-memory state) with acknowledgedDeletions=[], and B's write landed
last — overwriting A.

Net result: the deletion never got acknowledged, and the next sync
re-detected it, the next-next sync re-detected it, etc. Same flapping
behavior as before the fix.

Fix: move the acknowledge-push to run right after detection, based on
detectionResult.affectedBranches alone. Semantically correct — once
we've detected the branch is gone from GitHub, we know it's a permanent
deletion; whether THIS particular invocation took a backup or
short-circuited is orthogonal (a previous backup on disk is fine, and
in the rare case where no backup ever succeeded, the user can re-trigger
a manual backup). Both concurrent invocations now push the same entry;
both write the same metadata; race is benign.

Verified locally: 59 tests pass across force-push-detection,
gitea-enhanced, repo-backup.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 11:06:27 +05:30
Arunavo Ray 384fbbbe10 docs: document Header / Forward Authentication setup
Header auth has been a working feature since v2.x but was missing from
SSO-OIDC-SETUP.md, leading users to think it was dropped in the v3
rewrite (see #29). Adds a dedicated section covering env-var config,
Authentik + Authelia examples, lookup order, verification, and the
must-strip-inbound-headers security checklist.
2026-05-25 10:37:39 +05:30
Sean Mousseau 1a54010950 fix: prevent duplicate milestones & labels on every sync (#299)
Paginate /milestones and /labels with Link header + X-Total-Count fallback, and pass state=all on milestones so closed milestones aren't re-POSTed on every sync. Caches newly-created items in the in-memory dedup set.
2026-05-25 08:28:40 +05:30
CrumblyLiquid 9bf22791a9 Regenerated bun.nix (#298) 2026-05-25 08:26:19 +05:30
Arunavo Ray 5d82f22b12 chore: sync version to 3.16.1 2026-05-23 20:25:16 +05:30
Sean Mousseau 6979c3bb32 fix: resume interrupted jobs after startup (not only at boot) (#297)
The previous middleware logic gated recovery behind a
once-per-process flag. After the first request handled the boot-time
recovery check, the resume codepath never fired again — even when
new interruptions appeared later in the process lifetime.

Symptom: a sync that started after server boot, crashed mid-flight
(deadlock retry hitting maxRetries, network blip, container
restart of an upstream service, etc.) and never reached the resume
codepath would sit at `inProgress=true, lastCheckpoint=never`
forever. The periodic detector kept finding the stuck row and
logging `Found 1 interrupted jobs:` on every poll (driven by the
health endpoint via `hasJobsNeedingRecovery`), but the resumer
(`resumeInterruptedJob`) was only invoked from `initializeRecovery`
which the middleware never re-called.

Fix: replace the one-shot gate with an in-flight latch
(`recoveryInFlight`) that's released in a `finally` block. Throttling
of actual recovery work is delegated to the existing 5-minute
`skipIfRecentAttempt` check inside `initializeRecovery()`, which is
the right place for it. `recoveryInitialized` is kept and only used
to control whether the "first run" log lines fire.

Secondary fix: `findInterruptedJobs` previously logged
`Found N interrupted jobs:` unconditionally on every call, including
from passive polls in `hasJobsNeedingRecovery` (which the health
endpoint and middleware probe call frequently). That produced one
log line per poll per stuck job for as long as the job stayed stuck.
Make logging opt-in via a `logFound` parameter, default off; the
active recovery cycle in `initializeRecovery()` opts in so the
operator-facing log still surfaces which jobs are being worked on.

Related: #268 (partially addressed). The PR #280 / v3.15.7 fix was
about a JS scoping bug that made the *initial* migrate call's
catch path crash before transitioning the repo to `failed`. That
was one cause of stuck `mirroring` state; this PR addresses the
follow-on issue that even when a job *is* correctly detectable as
interrupted, the post-startup recovery path never re-engages.

Adds `orchestrator-resume-after-startup.test.ts` using the
structural-source test pattern from
`gitea-mirror-failure-recovery.test.ts` so the four guarantees
(no static gate; in-flight latch released in finally; logging
opt-in; active path opts in) are enforced without heavy mocks.
2026-05-23 20:08:33 +05:30
Sean Mousseau b9f14e55e2 fix: prevent duplicate issues & PRs on retry-after-deadlock + Link-header pagination (#296)
mirrorGitRepoIssuesToGitea and mirrorGitRepoPullRequestsToGitea both
had two compounding bugs that produced duplicate Gitea issues/PR-as-
issue rows on every sync against any non-SQLite backend.

(1) Pagination on existing-issues / existing-PRs / per-issue-comments
was wrong.

The loops paginated with `limit=100` and broke on `pageX.length <
itemsPerPage`. Gitea caps response size at server-side
[api].MAX_RESPONSE_ITEMS (default 50), so the very first page
already looks "short" and pagination terminated after one page. The
existing-issue and existing-PR maps were built from only ~50 items
per repo, so every issue/PR past page 1 was treated as new on every
sync and re-created via the CREATE branch.

Naive removal of the short-page break (relying only on "break on
empty page") doesn't work either: for some Gitea endpoints Gitea
returns the same data on every page when the page is past the
actual end instead of returning [], so the loop runs forever.

Fix: use the Link header (RFC 5988). If `rel="next"` is absent,
terminate pagination. Applied to: existing-issues pre-fetch,
existing-PRs pre-fetch, and per-issue comments fetch.

(2) Retry-after-deadlock duplicated issues/PRs even when the map
was correct.

Gitea's CreateIssue handler commits the issue insert in one
transaction and then deadlocks on the subsequent addLabel /
UPDATE repository transaction. The issue row is committed and
visible, but the in-memory dedup maps are never refreshed between
retries — processWithRetry re-invokes the callback, sees
existingIssue === undefined from the stale map, and creates a fresh
duplicate via httpPost.

Reproduces deterministically on MySQL (Error 1213 / 40001) and
PostgreSQL (40P01); SQLite escapes because writes serialize globally.

Fix: defensive recheck via httpGet by [GH-ISSUE #N] (issues) or
[PR #N] (pull requests) before the create call, with PATCH
fall-through when found. Applied to the issues create path AND
both create paths in the PR mirror (enriched + basic-fallback).
Also cache freshly-created items into the dedup maps after a
successful create so subsequent retries of the same per-item
callback don't lose track of it.

Adds gitea-issue-dedup-on-retry.test.ts using the structural-source
test pattern from gitea-mirror-failure-recovery.test.ts so all
guarantees are enforced without heavy module mocks (8 tests).
2026-05-23 20:08:23 +05:30
github-actions[bot] 2582988f94 chore: sync version to 3.16.0 2026-05-19 07:31:20 +00:00
21 changed files with 1854 additions and 180 deletions
+29 -45
View File
@@ -9,7 +9,7 @@
"@astrojs/mdx": "5.0.0",
"@astrojs/node": "10.0.1",
"@astrojs/react": "^5.0.0",
"@better-auth/sso": "1.5.5",
"@better-auth/sso": "1.6.11",
"@octokit/plugin-throttling": "^11.0.3",
"@octokit/rest": "^22.0.1",
"@radix-ui/react-accordion": "^1.2.12",
@@ -38,7 +38,7 @@
"@types/react-dom": "^19.2.3",
"astro": "^6.0.4",
"bcryptjs": "^3.0.3",
"better-auth": "1.5.5",
"better-auth": "1.6.11",
"buffer": "^6.0.3",
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
@@ -165,23 +165,23 @@
"@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
"@better-auth/core": ["@better-auth/core@1.5.5", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.3.1", "@better-fetch/fetch": "1.1.21", "@cloudflare/workers-types": ">=4", "better-call": "1.3.2", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types"] }, "sha512-1oR/2jAp821Dcf67kQYHUoyNcdc1TcShfw4QMK0YTVntuRES5mUOyvEJql5T6eIuLfaqaN4LOF78l0FtF66HXA=="],
"@better-auth/core": ["@better-auth/core@1.6.11", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.0", "@better-fetch/fetch": "1.1.21", "@cloudflare/workers-types": ">=4", "@opentelemetry/api": "^1.9.0", "better-call": "1.3.5", "jose": "^6.1.0", "kysely": "^0.28.5", "nanostores": "^1.0.1" }, "optionalPeers": ["@cloudflare/workers-types", "@opentelemetry/api"] }, "sha512-LrwidLCV8azdMGjvtwp30nj9tIv1BwI3VhtC0UaGSjQkAVWw4bN42I8qwbxRziPeSQoj+zUVkOpxZzAWBDARtQ=="],
"@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0", "drizzle-orm": ">=0.41.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-HAi9xAP40oDt48QZeYBFTcmg3vt1Jik90GwoRIfangd7VGbxesIIDBJSnvwMbZ52GBIc6+V4FRw9lasNiNrPfw=="],
"@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "drizzle-orm": "^0.45.2" }, "optionalPeers": ["drizzle-orm"] }, "sha512-4jpkETIGZOHCf7BK4jnu22fdN6jjomH0/HhEzkaWy3+Eppi5PYlHTF/460jrTmA3Xc+Vqwp9t282ymHiEPypGw=="],
"@better-auth/kysely-adapter": ["@better-auth/kysely-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0", "kysely": "^0.27.0 || ^0.28.0" } }, "sha512-LmHffIVnqbfsxcxckMOoE8MwibWrbVFch+kwPKJ5OFDFv6lin75ufN7ZZ7twH0IMPLT/FcgzaRjP8jRrXRef9g=="],
"@better-auth/kysely-adapter": ["@better-auth/kysely-adapter@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "kysely": "^0.28.17" }, "optionalPeers": ["kysely"] }, "sha512-/g8M9RfIjdcZDnbstSUvQiINkvdNlCeZr248zwqx2/PVksQI1MhQofbzUn3RnQnbPKp0EPwpX/dR3oudRFenUg=="],
"@better-auth/memory-adapter": ["@better-auth/memory-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0" } }, "sha512-4X0j1/2L+nsgmObjmy9xEGUFWUv38Qjthp558fwS3DAp6ueWWyCaxaD6VJZ7m5qPNMrsBStO5WGP8CmJTEWm7g=="],
"@better-auth/memory-adapter": ["@better-auth/memory-adapter@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0" } }, "sha512-hpdfw0BBf8MuzLkIdmbcUZICbY9r/bhLO2RxSnkzT5+/O+0I0u2I8+m0YUP7vNllP/ZCKASHOYgXPLO75Z0f9Q=="],
"@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0", "mongodb": "^6.0.0 || ^7.0.0" } }, "sha512-P1J9ljL5X5k740I8Rx1esPWNgWYPdJR5hf2CY7BwDSrQFPUHuzeCg0YhtEEP55niNateTXhBqGAcy0fVOeamZg=="],
"@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-3Tor8rSv8vSEIMEaV2PFpPEuVhqc1gNoZ6eGvoh3LwExXXuj8madew6ob+H1pH7Aphn3Ar5PQ08AguT8TbwFAA=="],
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.5.5", "", { "peerDependencies": { "@better-auth/core": "1.5.5", "@better-auth/utils": "^0.3.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-CliDd78CXHzzwQIXhCdwGr5Ml53i6JdCHWV7PYwTIJz9EAm6qb2RVBdpP3nqEfNjINGM22A6gfleCgCdZkTIZg=="],
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-Pw+7q7zTp+VSci1V+CYMvuxIbAeVMZLe4lRo46LJoAKMHfjFl5T/ycsyFvWs/DkWC7n9gZZzRDEbHp0I5FiKKw=="],
"@better-auth/sso": ["@better-auth/sso@1.5.5", "", { "dependencies": { "@better-auth/utils": "0.3.1", "@better-fetch/fetch": "1.1.21", "fast-xml-parser": "^5.4.1", "jose": "^6.1.3", "samlify": "^2.10.2", "tldts": "^6.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "1.5.5", "better-auth": "1.5.5", "better-call": "1.3.2" } }, "sha512-G3tvv5oKtEfpmBrt7Db/hSl5A3xttUkB4EhEjb202UhHz/XBiT0Orv5CkRa0kmjRyyAwOzn/lKZzYsd3VrjViA=="],
"@better-auth/sso": ["@better-auth/sso@1.6.11", "", { "dependencies": { "fast-xml-parser": "^5.5.7", "jose": "^6.1.3", "samlify": "~2.10.2", "tldts": "^6.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "@better-fetch/fetch": "1.1.21", "better-auth": "^1.6.11", "better-call": "1.3.5" } }, "sha512-lJHmoCayp9Woh/MPKTHDfGq7k1oQbU2yz5tIOZXl/pzrgLxV7fMGo9aJCyabHkw3GHMjBes4byC6aakHYzpZIg=="],
"@better-auth/telemetry": ["@better-auth/telemetry@1.5.5", "", { "dependencies": { "@better-auth/utils": "0.3.1", "@better-fetch/fetch": "1.1.21" }, "peerDependencies": { "@better-auth/core": "1.5.5" } }, "sha512-1+lklxArn4IMHuU503RcPdXrSG2tlXt4jnGG3omolmspQ7tktg/Y9XO/yAkYDurtvMn1xJ8X1Ov01Ji/r5s9BQ=="],
"@better-auth/telemetry": ["@better-auth/telemetry@1.6.11", "", { "peerDependencies": { "@better-auth/core": "^1.6.11", "@better-auth/utils": "0.4.0", "@better-fetch/fetch": "1.1.21" } }, "sha512-hsjDHc8MZbm6/AHeNdtywrWedXevnBjmdvnHTcZub+rTVjOv+Td0roI8USKuC6uUibmrl//2rJfVCsGbopihNA=="],
"@better-auth/utils": ["@better-auth/utils@0.3.1", "", {}, "sha512-+CGp4UmZSUrHHnpHhLPYu6cV+wSUSvVbZbNykxhUDocpVNTo9uFFxw/NqJlh1iC4wQ9HKKWGCKuZ5wUgS0v6Kg=="],
"@better-auth/utils": ["@better-auth/utils@0.4.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-RpMtLUIQAEWMgdPLNVbIF5ON2mm+CH0U3rCdUCU1VyeAUui4m38DyK7/aXMLZov2YDjG684pS1D0MBllrmgjQA=="],
"@better-fetch/fetch": ["@better-fetch/fetch@1.1.21", "", {}, "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="],
@@ -353,14 +353,14 @@
"@mdx-js/mdx": ["@mdx-js/mdx@3.1.1", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="],
"@mongodb-js/saslprep": ["@mongodb-js/saslprep@1.4.6", "", { "dependencies": { "sparse-bitfield": "^3.0.3" } }, "sha512-y+x3H1xBZd38n10NZF/rEBlvDOOMQ6LKUTHqr8R9VkJ+mmQOYtJFxIlkkK8fZrtOiL6VixbOBWMbZGBdal3Z1g=="],
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.1", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
"@noble/ciphers": ["@noble/ciphers@2.1.1", "", {}, "sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw=="],
"@noble/hashes": ["@noble/hashes@2.0.1", "", {}, "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw=="],
"@nodable/entities": ["@nodable/entities@2.1.0", "", {}, "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA=="],
"@octokit/auth-token": ["@octokit/auth-token@6.0.0", "", {}, "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w=="],
"@octokit/core": ["@octokit/core@7.0.6", "", { "dependencies": { "@octokit/auth-token": "^6.0.0", "@octokit/graphql": "^9.0.3", "@octokit/request": "^10.0.6", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "before-after-hook": "^4.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q=="],
@@ -387,6 +387,8 @@
"@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="],
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.41.1", "", {}, "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA=="],
"@oslojs/encoding": ["@oslojs/encoding@1.1.0", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="],
"@oxc-project/runtime": ["@oxc-project/runtime@0.115.0", "", {}, "sha512-Rg8Wlt5dCbXhQnsXPrkOjL1DTSvXLgb2R/KYfnf1/K+R0k6UMLEmbQXPM+kwrWqSmWA2t0B1EtHy2/3zikQpvQ=="],
@@ -683,10 +685,6 @@
"@types/uuid": ["@types/uuid@11.0.0", "", { "dependencies": { "uuid": "*" } }, "sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA=="],
"@types/webidl-conversions": ["@types/webidl-conversions@7.0.3", "", {}, "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA=="],
"@types/whatwg-url": ["@types/whatwg-url@13.0.0", "", { "dependencies": { "@types/webidl-conversions": "*" } }, "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q=="],
"@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
"@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.1", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ=="],
@@ -769,9 +767,9 @@
"before-after-hook": ["before-after-hook@4.0.0", "", {}, "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ=="],
"better-auth": ["better-auth@1.5.5", "", { "dependencies": { "@better-auth/core": "1.5.5", "@better-auth/drizzle-adapter": "1.5.5", "@better-auth/kysely-adapter": "1.5.5", "@better-auth/memory-adapter": "1.5.5", "@better-auth/mongo-adapter": "1.5.5", "@better-auth/prisma-adapter": "1.5.5", "@better-auth/telemetry": "1.5.5", "@better-auth/utils": "0.3.1", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.3.2", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.11", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": ">=0.41.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-GpVPaV1eqr3mOovKfghJXXk6QvlcVeFbS3z+n+FPDid5rK/2PchnDtiaVCzWyXA9jH2KkirOfl+JhAUvnja0Eg=="],
"better-auth": ["better-auth@1.6.11", "", { "dependencies": { "@better-auth/core": "1.6.11", "@better-auth/drizzle-adapter": "1.6.11", "@better-auth/kysely-adapter": "1.6.11", "@better-auth/memory-adapter": "1.6.11", "@better-auth/mongo-adapter": "1.6.11", "@better-auth/prisma-adapter": "1.6.11", "@better-auth/telemetry": "1.6.11", "@better-auth/utils": "0.4.0", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.3.5", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-Wwt6+q07dwIhsp6XiM7L1qSXVUWBEtNl+eZvwM778CguFqDZFBN9Pt6LtFaHl55t8Z+Zc//5kxcbgDY8/79vFQ=="],
"better-call": ["better-call@1.3.2", "", { "dependencies": { "@better-auth/utils": "^0.3.1", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-4cZIfrerDsNTn3cm+MhLbUePN0gdwkhSXEuG7r/zuQ8c/H7iU0/jSK5TD3FW7U0MgKHce/8jGpPYNO4Ve+4NBw=="],
"better-call": ["better-call@1.3.5", "", { "dependencies": { "@better-auth/utils": "^0.4.0", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-kOFJkBP7utAQLEYrobZm3vkTH8mXq5GNgvjc5/XEST1ilVHaxXUXfeDeFlqoETMtyqS4+3/h4ONX2i++ebZrvA=="],
"bidi-js": ["bidi-js@1.0.3", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw=="],
@@ -781,15 +779,13 @@
"browserslist": ["browserslist@4.28.1", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
"bson": ["bson@7.2.0", "", {}, "sha512-YCEo7KjMlbNlyHhz7zAZNDpIpQbd+wOEHJYezv0nMYTn4x31eIUM2yomNNubclAt63dObUzKHWsBLJ9QcZNSnQ=="],
"buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
"buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
"bun-types": ["bun-types@1.3.10", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
"camelcase": ["camelcase@9.0.0", "", {}, "sha512-TO9xmyXTZ9HUHI8M1OnvExxYB0eYVS/1e5s7IDMTAoIcwUd+aNcFODs6Xk83mobk0velyHFQgA1yIrvYc6wclw=="],
"camelcase": ["camelcase@6.3.0", "", {}, "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA=="],
"caniuse-lite": ["caniuse-lite@1.0.30001779", "", {}, "sha512-U5og2PN7V4DMgF50YPNtnZJGWVLFjjsN3zb6uMT5VGYIewieDj1upwfuVNXf4Kor+89c3iCRJnSzMD5LmTvsfA=="],
@@ -961,7 +957,7 @@
"fast-xml-builder": ["fast-xml-builder@1.2.0", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="],
"fast-xml-parser": ["fast-xml-parser@5.5.6", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.1.3", "strnum": "^2.1.2" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-3+fdZyBRVg29n4rXP0joHthhcHdPUHaIC16cuyyd1iLsuaO6Vea36MPrxgAzbZna8lhvZeRL8Bc9GP56/J9xEw=="],
"fast-xml-parser": ["fast-xml-parser@5.8.0", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.2.0", "path-expression-matcher": "^1.5.0", "strnum": "^2.3.0", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-6bIM7fsJxeo3uXv7OncQYsBAMPJ7V16Slahl/6M98C/i2q+vB1+4a0MtrvYwDFEUrwDSbAmeLDRXsOBwrL7yAg=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
@@ -1181,8 +1177,6 @@
"mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="],
"memory-pager": ["memory-pager@1.5.0", "", {}, "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg=="],
"micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="],
"micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="],
@@ -1259,10 +1253,6 @@
"min-indent": ["min-indent@1.0.1", "", {}, "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg=="],
"mongodb": ["mongodb@7.1.0", "", { "dependencies": { "@mongodb-js/saslprep": "^1.3.0", "bson": "^7.1.1", "mongodb-connection-string-url": "^7.0.0" }, "peerDependencies": { "@aws-sdk/credential-providers": "^3.806.0", "@mongodb-js/zstd": "^7.0.0", "gcp-metadata": "^7.0.1", "kerberos": "^7.0.0", "mongodb-client-encryption": ">=7.0.0 <7.1.0", "snappy": "^7.3.2", "socks": "^2.8.6" }, "optionalPeers": ["@aws-sdk/credential-providers", "@mongodb-js/zstd", "gcp-metadata", "kerberos", "mongodb-client-encryption", "snappy", "socks"] }, "sha512-kMfnKunbolQYwCIyrkxNJFB4Ypy91pYqua5NargS/f8ODNSJxT03ZU3n1JqL4mCzbSih8tvmMEMLpKTT7x5gCg=="],
"mongodb-connection-string-url": ["mongodb-connection-string-url@7.0.1", "", { "dependencies": { "@types/whatwg-url": "^13.0.0", "whatwg-url": "^14.1.0" } }, "sha512-h0AZ9A7IDVwwHyMxmdMXKy+9oNlF0zFoahHiX3vQ8e3KFcSP3VmsmfvtRSuLPxmyv2vjIDxqty8smTgie/SNRQ=="],
"mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
@@ -1281,6 +1271,8 @@
"node-fetch-native": ["node-fetch-native@1.6.7", "", {}, "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q=="],
"node-forge": ["node-forge@1.4.0", "", {}, "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ=="],
"node-mock-http": ["node-mock-http@1.0.4", "", {}, "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ=="],
"node-releases": ["node-releases@2.0.36", "", {}, "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA=="],
@@ -1311,6 +1303,8 @@
"package-manager-detector": ["package-manager-detector@1.6.0", "", {}, "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA=="],
"pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"parse-latin": ["parse-latin@7.0.0", "", { "dependencies": { "@types/nlcst": "^2.0.0", "@types/unist": "^3.0.0", "nlcst-to-string": "^4.0.0", "unist-util-modify-children": "^4.0.0", "unist-util-visit-children": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-mhHgobPPua5kZ98EF4HWiH167JWBfl4pvAIXXdbaVohtK7a6YBOy56kvhCqduqyo/f3yrHFWmqmiMg/BkBkYYQ=="],
@@ -1319,7 +1313,7 @@
"path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
"path-expression-matcher": ["path-expression-matcher@1.1.3", "", {}, "sha512-qdVgY8KXmVdJZRSS1JdEPOKPdTiEK/pi0RkcT2sw1RhXxohdujUlJFPuS1TSkevZ9vzd3ZlL7ULl1MHGTApKzQ=="],
"path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="],
"pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
@@ -1431,7 +1425,7 @@
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"samlify": ["samlify@2.11.0", "", { "dependencies": { "@authenio/xml-encryption": "^2.0.2", "@xmldom/xmldom": "^0.8.11", "camelcase": "^9.0.0", "node-rsa": "^1.1.1", "xml": "^1.0.1", "xml-crypto": "^6.1.2", "xml-escape": "^1.1.0", "xpath": "^0.0.34" } }, "sha512-1C9ukjlf0rRsuyqdzztqikdItqa33j9NCCDZgeBiWk0etU6vxNB+SWJKW4Flk07ZlhXeev/twALEKrPhIAyfDg=="],
"samlify": ["samlify@2.10.2", "", { "dependencies": { "@authenio/xml-encryption": "^2.0.2", "@xmldom/xmldom": "^0.8.6", "camelcase": "^6.2.0", "node-forge": "^1.3.0", "node-rsa": "^1.1.1", "pako": "^1.0.10", "uuid": "^8.3.2", "xml": "^1.0.1", "xml-crypto": "^6.1.2", "xml-escape": "^1.1.0", "xpath": "^0.0.32" } }, "sha512-y5s1cHwclqwP8h7K2Wj9SfP1q+1S9+jrs5OAegYTLAiuFi7nDvuKqbiXLmUTvYPMpzHcX94wTY2+D604jgTKvA=="],
"sax": ["sax@1.5.0", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
@@ -1467,8 +1461,6 @@
"space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],
"sparse-bitfield": ["sparse-bitfield@3.0.3", "", { "dependencies": { "memory-pager": "^1.0.2" } }, "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ=="],
"stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
@@ -1483,7 +1475,7 @@
"strip-indent": ["strip-indent@3.0.0", "", { "dependencies": { "min-indent": "^1.0.0" } }, "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ=="],
"strnum": ["strnum@2.2.0", "", {}, "sha512-Y7Bj8XyJxnPAORMZj/xltsfo55uOiyHcU2tnAVzHUnSJR/KsEX+9RoDeXEnsXtl/CX4fAcrt64gZ13aGaWPeBg=="],
"strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="],
"style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
@@ -1663,7 +1655,7 @@
"xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="],
"xpath": ["xpath@0.0.34", "", {}, "sha512-FxF6+rkr1rNSQrhUNYrAFJpRXNzlDoMxeXN5qI84939ylEv3qqPFKa85Oxr6tDaJKqwW6KKyo2v26TSv3k6LeA=="],
"xpath": ["xpath@0.0.32", "", {}, "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw=="],
"xxhash-wasm": ["xxhash-wasm@1.1.0", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
@@ -1691,8 +1683,6 @@
"@astrojs/react/vite": ["vite@7.3.1", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"@authenio/xml-encryption/xpath": ["xpath@0.0.32", "", {}, "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw=="],
"@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
@@ -1759,14 +1749,10 @@
"dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
"fast-xml-builder/path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="],
"hast-util-from-html/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
"hast-util-raw/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
"mongodb-connection-string-url/whatwg-url": ["whatwg-url@14.2.0", "", { "dependencies": { "tr46": "^5.1.0", "webidl-conversions": "^7.0.0" } }, "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
@@ -1775,6 +1761,8 @@
"rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.9", "", {}, "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw=="],
"samlify/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
"tough-cookie/tldts": ["tldts@7.0.25", "", { "dependencies": { "tldts-core": "^7.0.25" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-keinCnPbwXEUG3ilrWQZU+CqcTTzHq9m2HhoUP2l7Xmi8l1LuijAXLpAJ5zRW+ifKTNscs4NdCkfkDCBYm352w=="],
"tsx/esbuild": ["esbuild@0.27.4", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.4", "@esbuild/android-arm": "0.27.4", "@esbuild/android-arm64": "0.27.4", "@esbuild/android-x64": "0.27.4", "@esbuild/darwin-arm64": "0.27.4", "@esbuild/darwin-x64": "0.27.4", "@esbuild/freebsd-arm64": "0.27.4", "@esbuild/freebsd-x64": "0.27.4", "@esbuild/linux-arm": "0.27.4", "@esbuild/linux-arm64": "0.27.4", "@esbuild/linux-ia32": "0.27.4", "@esbuild/linux-loong64": "0.27.4", "@esbuild/linux-mips64el": "0.27.4", "@esbuild/linux-ppc64": "0.27.4", "@esbuild/linux-riscv64": "0.27.4", "@esbuild/linux-s390x": "0.27.4", "@esbuild/linux-x64": "0.27.4", "@esbuild/netbsd-arm64": "0.27.4", "@esbuild/netbsd-x64": "0.27.4", "@esbuild/openbsd-arm64": "0.27.4", "@esbuild/openbsd-x64": "0.27.4", "@esbuild/openharmony-arm64": "0.27.4", "@esbuild/sunos-x64": "0.27.4", "@esbuild/win32-arm64": "0.27.4", "@esbuild/win32-ia32": "0.27.4", "@esbuild/win32-x64": "0.27.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ=="],
@@ -1927,10 +1915,6 @@
"csso/css-tree/mdn-data": ["mdn-data@2.0.28", "", {}, "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g=="],
"mongodb-connection-string-url/whatwg-url/tr46": ["tr46@5.1.1", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw=="],
"mongodb-connection-string-url/whatwg-url/webidl-conversions": ["webidl-conversions@7.0.0", "", {}, "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="],
"tough-cookie/tldts/tldts-core": ["tldts-core@7.0.25", "", {}, "sha512-ZjCZK0rppSBu7rjHYDYsEaMOIbbT+nWF57hKkv4IUmZWBNrBWBOjIElc0mKRgLM8bm7x/BBlof6t2gi/Oq/Asw=="],
"tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.4", "", { "os": "aix", "cpu": "ppc64" }, "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q=="],
+39 -35
View File
@@ -1409,9 +1409,9 @@
url = "https://registry.npmjs.org/@xmldom/is-dom-node/-/is-dom-node-1.0.1.tgz";
hash = "sha512-CJDxIgE5I0FH+ttq/Fxy6nRpxP70+e2O048EPe85J2use3XKdatVM7dDVvFNjQudd9B49NPoZ+8PG49zj4Er8Q==";
};
"@xmldom/xmldom@0.8.11" = fetchurl {
url = "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz";
hash = "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==";
"@xmldom/xmldom@0.8.13" = fetchurl {
url = "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz";
hash = "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==";
};
"acorn-jsx@5.3.2" = fetchurl {
url = "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz";
@@ -1701,9 +1701,9 @@
url = "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz";
hash = "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==";
};
"defu@6.1.4" = fetchurl {
url = "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz";
hash = "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==";
"defu@6.1.7" = fetchurl {
url = "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz";
hash = "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==";
};
"depd@2.0.0" = fetchurl {
url = "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz";
@@ -1725,9 +1725,9 @@
url = "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz";
hash = "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==";
};
"devalue@5.6.4" = fetchurl {
url = "https://registry.npmjs.org/devalue/-/devalue-5.6.4.tgz";
hash = "sha512-Gp6rDldRsFh/7XuouDbxMH3Mx8GMCcgzIb1pDTvNyn8pZGQ22u+Wa+lGV9dQCltFQ7uVw0MhRyb8XDskNFOReA==";
"devalue@5.8.1" = fetchurl {
url = "https://registry.npmjs.org/devalue/-/devalue-5.8.1.tgz";
hash = "sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw==";
};
"devlop@1.1.0" = fetchurl {
url = "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz";
@@ -1773,9 +1773,9 @@
url = "https://registry.npmjs.org/drizzle-kit/-/drizzle-kit-0.31.9.tgz";
hash = "sha512-GViD3IgsXn7trFyBUUHyTFBpH/FsHTxYJ66qdbVggxef4UBPHRYxQaRzYLTuekYnk9i5FIEL9pbBIwMqX/Uwrg==";
};
"drizzle-orm@0.45.1" = fetchurl {
url = "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.1.tgz";
hash = "sha512-Te0FOdKIistGNPMq2jscdqngBRfBpC8uMFVwqjf6gtTVJHIQ/dosgV/CLBU2N4ZJBsXL5savCba9b0YJskKdcA==";
"drizzle-orm@0.45.2" = fetchurl {
url = "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.2.tgz";
hash = "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==";
};
"dset@3.1.4" = fetchurl {
url = "https://registry.npmjs.org/dset/-/dset-3.1.4.tgz";
@@ -1909,17 +1909,17 @@
url = "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz";
hash = "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==";
};
"fast-uri@3.1.0" = fetchurl {
url = "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz";
hash = "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==";
"fast-uri@3.1.2" = fetchurl {
url = "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz";
hash = "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==";
};
"fast-xml-builder@1.1.3" = fetchurl {
url = "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.3.tgz";
hash = "sha512-1o60KoFw2+LWKQu3IdcfcFlGTW4dpqEWmjhYec6H82AYZU2TVBXep6tMl8Z1Y+wM+ZrzCwe3BZ9Vyd9N2rIvmg==";
"fast-xml-builder@1.2.0" = fetchurl {
url = "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz";
hash = "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==";
};
"fast-xml-parser@5.5.5" = fetchurl {
url = "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.5.tgz";
hash = "sha512-NLY+V5NNbdmiEszx9n14mZBseJTC50bRq1VHsaxOmR72JDuZt+5J1Co+dC/4JPnyq+WrIHNM69r0sqf7BMb3Mg==";
"fast-xml-parser@5.5.6" = fetchurl {
url = "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.6.tgz";
hash = "sha512-3+fdZyBRVg29n4rXP0joHthhcHdPUHaIC16cuyyd1iLsuaO6Vea36MPrxgAzbZna8lhvZeRL8Bc9GP56/J9xEw==";
};
"fdir@6.5.0" = fetchurl {
url = "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz";
@@ -2177,9 +2177,9 @@
url = "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz";
hash = "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==";
};
"kysely@0.28.12" = fetchurl {
url = "https://registry.npmjs.org/kysely/-/kysely-0.28.12.tgz";
hash = "sha512-kWiueDWXhbCchgiotwXkwdxZE/6h56IHAeFWg4euUfW0YsmO9sxbAxzx1KLLv2lox15EfuuxHQvgJ1qIfZuHGw==";
"kysely@0.28.17" = fetchurl {
url = "https://registry.npmjs.org/kysely/-/kysely-0.28.17.tgz";
hash = "sha512-nbD8lB9EB3wNdMhOCdx5Li8DxnLbvKByylRLcJ1h+4SkrowVeECAyZlyiKMThF7xFdRz0jSQ2MoJr+wXux2y0Q==";
};
"lightningcss-android-arm64@1.31.1" = fetchurl {
url = "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.31.1.tgz";
@@ -2305,9 +2305,9 @@
url = "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz";
hash = "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==";
};
"lodash@4.17.21" = fetchurl {
url = "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz";
hash = "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==";
"lodash@4.18.1" = fetchurl {
url = "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz";
hash = "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==";
};
"longest-streak@3.1.0" = fetchurl {
url = "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz";
@@ -2709,6 +2709,10 @@
url = "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.1.3.tgz";
hash = "sha512-qdVgY8KXmVdJZRSS1JdEPOKPdTiEK/pi0RkcT2sw1RhXxohdujUlJFPuS1TSkevZ9vzd3ZlL7ULl1MHGTApKzQ==";
};
"path-expression-matcher@1.5.0" = fetchurl {
url = "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz";
hash = "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==";
};
"pathe@2.0.3" = fetchurl {
url = "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz";
hash = "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==";
@@ -2721,13 +2725,9 @@
url = "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz";
hash = "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==";
};
"picomatch@2.3.1" = fetchurl {
url = "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz";
hash = "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==";
};
"picomatch@4.0.3" = fetchurl {
url = "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz";
hash = "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==";
"picomatch@4.0.4" = fetchurl {
url = "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz";
hash = "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==";
};
"playwright-core@1.58.2" = fetchurl {
url = "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz";
@@ -3421,6 +3421,10 @@
url = "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz";
hash = "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==";
};
"xml-naming@0.1.0" = fetchurl {
url = "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz";
hash = "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==";
};
"xml@1.0.1" = fetchurl {
url = "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz";
hash = "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==";
@@ -3489,4 +3493,4 @@
url = "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz";
hash = "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==";
};
}
}
+75 -3
View File
@@ -4,15 +4,16 @@ This guide explains how to configure Single Sign-On (SSO) and OpenID Connect (OI
## Overview
Gitea Mirror supports three authentication methods:
Gitea Mirror supports four authentication methods:
1. **Email & Password** - Traditional authentication (always enabled)
2. **SSO (Single Sign-On)** - Allow users to authenticate using external OIDC providers
3. **OIDC Provider** - Allow other applications to authenticate users through Gitea Mirror
3. **Header / Forward Authentication** - Trust pre-authenticated requests from a reverse proxy (Authentik, Authelia, oauth2-proxy, etc.)
4. **OIDC Provider** - Allow other applications to authenticate users through Gitea Mirror
## Configuration
All SSO and OIDC settings are managed through the web UI in the Configuration page under the "Authentication" tab.
SSO and OIDC Provider settings are managed through the web UI in the Configuration page under the "Authentication" tab. Header / Forward Authentication is configured via environment variables only — see [Setting up Header / Forward Authentication](#setting-up-header--forward-authentication) below.
## Setting up SSO (Single Sign-On)
@@ -101,6 +102,77 @@ Notes:
- Authentik must report the users email as verified (default behavior) so Gitea Mirror can auto-link accounts.
- If you created an Authentik provider before v3.8.10 you should delete it and re-add it after upgrading; older versions saved incomplete endpoint data which leads to the `url.startsWith` error explained in the Troubleshooting section.
## Setting up Header / Forward Authentication
Header authentication trusts a reverse proxy (Authentik, Authelia, oauth2-proxy, Traefik forward-auth, etc.) to authenticate users upstream and pass identity in HTTP headers. When enabled, Gitea Mirror reads the configured headers on each request and resolves the user automatically — no login form, no callback.
> **Important — operator-controlled by design.** Header auth is configured via environment variables only, not the UI. This is intentional: trusting a header means trusting whatever upstream sets it, and that decision belongs to the operator who controls the reverse proxy, not to a logged-in user inside the app. Make sure your reverse proxy strips these headers from inbound client requests, otherwise anyone can spoof them.
### Environment variables
| Variable | Description | Default |
|----------|-------------|---------|
| `HEADER_AUTH_ENABLED` | Master switch — must be `true` to enable | `false` |
| `HEADER_AUTH_USER_HEADER` | Header containing the username | `X-Authentik-Username` |
| `HEADER_AUTH_EMAIL_HEADER` | Header containing the email address | `X-Authentik-Email` |
| `HEADER_AUTH_NAME_HEADER` | Header containing the display name | `X-Authentik-Name` |
| `HEADER_AUTH_AUTO_PROVISION` | If `true`, create a new user when an unknown username arrives. If `false`, unknown users are rejected. | `false` |
| `HEADER_AUTH_ALLOWED_DOMAINS` | Comma-separated email domain allowlist. Empty = allow any. | _(empty)_ |
See also: [`docs/ENVIRONMENT_VARIABLES.md`](./ENVIRONMENT_VARIABLES.md#header-authentication-reverse-proxy-sso).
### Example: Docker Compose with Authentik
```yaml
services:
gitea-mirror:
image: ghcr.io/raylabshq/gitea-mirror:latest
environment:
HEADER_AUTH_ENABLED: "true"
HEADER_AUTH_USER_HEADER: "X-Authentik-Username"
HEADER_AUTH_EMAIL_HEADER: "X-Authentik-Email"
HEADER_AUTH_NAME_HEADER: "X-Authentik-Name"
HEADER_AUTH_AUTO_PROVISION: "true"
HEADER_AUTH_ALLOWED_DOMAINS: "example.com,example.org"
```
The defaults are Authentik-shaped, so for an Authentik proxy provider you generally only need to set `HEADER_AUTH_ENABLED=true` (and `HEADER_AUTH_AUTO_PROVISION=true` if you want first-login self-registration).
### Example: Authelia
Authelia uses different header names — override them:
```yaml
environment:
HEADER_AUTH_ENABLED: "true"
HEADER_AUTH_USER_HEADER: "Remote-User"
HEADER_AUTH_EMAIL_HEADER: "Remote-Email"
HEADER_AUTH_NAME_HEADER: "Remote-Name"
HEADER_AUTH_AUTO_PROVISION: "true"
```
Then configure Authelia's `authz` rules to protect the gitea-mirror route and inject the `Remote-*` headers.
### Behaviour and lookup order
- The middleware checks for a cookie session **first**. Header auth only fires when there is no existing session, so users who logged in via password or SSO are not affected.
- Lookup is by `HEADER_AUTH_USER_HEADER` value matched against `users.username`; if no match and `HEADER_AUTH_EMAIL_HEADER` is set, a second lookup is tried against `users.email`.
- If neither matches:
- With `HEADER_AUTH_AUTO_PROVISION=true`, a new user row is created (email defaults to `<username>@header-auth.local` if no email header is present).
- With `HEADER_AUTH_AUTO_PROVISION=false`, the request is rejected with a warning logged.
- If `HEADER_AUTH_ALLOWED_DOMAINS` is non-empty and the email header arrives, the email's domain must be in the list or the request is rejected.
### Verifying it's enabled
When header auth is active, the Authentication settings page renders a green "Header Authentication / Via reverse proxy" badge under the auth-methods status block. You can also probe `/api/auth/header-status`, which returns `{ "enabled": true, ... }` once the env vars are set.
### Security checklist
1. **Strip the headers at your edge.** Your reverse proxy must remove inbound `HEADER_AUTH_USER_HEADER` / email / name headers from client requests before re-injecting its own. Otherwise any unauthenticated client can set `X-Authentik-Username: admin` and walk in.
2. **Bind the app to the proxy only.** Don't expose Gitea Mirror's port directly to the network when header auth is on; only the trusted proxy should reach it.
3. **Use HTTPS between proxy and clients.** Headers travel in plaintext on the link they cross.
4. **Be conservative with `HEADER_AUTH_AUTO_PROVISION`.** With it off, you provision users in the UI/DB once and the proxy fills in sessions thereafter — safer for shared deployments.
## Setting up OIDC Provider
The OIDC Provider feature allows other applications to use Gitea Mirror as their authentication provider.
+3 -3
View File
@@ -1,7 +1,7 @@
{
"name": "gitea-mirror",
"type": "module",
"version": "3.15.12",
"version": "3.16.3",
"engines": {
"bun": ">=1.2.9"
},
@@ -58,7 +58,7 @@
"@astrojs/mdx": "5.0.0",
"@astrojs/node": "10.0.1",
"@astrojs/react": "^5.0.0",
"@better-auth/sso": "1.5.5",
"@better-auth/sso": "1.6.11",
"@octokit/plugin-throttling": "^11.0.3",
"@octokit/rest": "^22.0.1",
"@radix-ui/react-accordion": "^1.2.12",
@@ -87,7 +87,7 @@
"@types/react-dom": "^19.2.3",
"astro": "^6.0.4",
"bcryptjs": "^3.0.3",
"better-auth": "1.5.5",
"better-auth": "1.6.11",
"buffer": "^6.0.3",
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, mock, test, beforeEach } from "bun:test";
// Stub `./auth` so we can drive the response shape `mintSessionFromHeaders`
// sees from the plugin endpoint without standing up the full Better Auth
// stack + DB.
const signInWithHeaderMock = mock<(args: unknown) => Promise<Response>>(
async () => new Response(null, { status: 500 }),
);
mock.module("@/lib/auth", () => ({
auth: {
api: {
signInWithHeader: signInWithHeaderMock,
},
},
}));
import { mintSessionFromHeaders } from "./auth-header-bridge";
function makeRequest(headers: Record<string, string> = {}): Request {
return new Request("http://localhost/test", { headers });
}
describe("mintSessionFromHeaders", () => {
beforeEach(() => {
signInWithHeaderMock.mockReset();
});
test("returns user, session, and Set-Cookie values on a 200 response", async () => {
signInWithHeaderMock.mockImplementation(async () => {
const response = new Response(
JSON.stringify({
user: { id: "user-1", email: "u@example.com" },
session: { id: "sess-1", userId: "user-1" },
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
// Modern runtimes coalesce multiple Set-Cookie via append.
response.headers.append("set-cookie", "better-auth-session=abc; Path=/");
response.headers.append("set-cookie", "better-auth-remember=1; Path=/");
return response;
});
const result = await mintSessionFromHeaders(makeRequest());
expect(result).not.toBeNull();
expect(result?.user.id).toBe("user-1");
expect(result?.session.id).toBe("sess-1");
expect(result?.setCookies).toEqual([
"better-auth-session=abc; Path=/",
"better-auth-remember=1; Path=/",
]);
});
test("returns null when the endpoint responds non-2xx (header auth disabled / unauthorized)", async () => {
signInWithHeaderMock.mockImplementation(
async () => new Response("Unauthorized", { status: 401 }),
);
const result = await mintSessionFromHeaders(makeRequest());
expect(result).toBeNull();
});
test("returns null when the endpoint throws (transient failure)", async () => {
signInWithHeaderMock.mockImplementation(async () => {
throw new Error("upstream unreachable");
});
const result = await mintSessionFromHeaders(makeRequest());
expect(result).toBeNull();
});
test("returns null when the response body is missing user or session", async () => {
signInWithHeaderMock.mockImplementation(
async () =>
new Response(JSON.stringify({ token: "abc" }), {
status: 200,
headers: { "content-type": "application/json" },
}),
);
const result = await mintSessionFromHeaders(makeRequest());
expect(result).toBeNull();
});
test("returns null when the body is malformed JSON", async () => {
signInWithHeaderMock.mockImplementation(
async () =>
new Response("not json at all", {
status: 200,
headers: { "content-type": "application/json" },
}),
);
const result = await mintSessionFromHeaders(makeRequest());
expect(result).toBeNull();
});
test("returns an empty setCookies array when no Set-Cookie headers were attached", async () => {
// Defensive — should never happen in practice because the plugin
// always calls setSessionCookie. If it does happen, we still want
// the user/session to come through so SSR works on this request.
signInWithHeaderMock.mockImplementation(
async () =>
new Response(
JSON.stringify({
user: { id: "user-1" },
session: { id: "sess-1" },
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
const result = await mintSessionFromHeaders(makeRequest());
expect(result).not.toBeNull();
expect(result?.setCookies).toEqual([]);
});
});
+56
View File
@@ -0,0 +1,56 @@
import { auth } from "./auth";
export interface BridgeResult {
user: any;
session: any;
setCookies: string[];
}
/**
* Calls the `header-auth` plugin endpoint to mint a real Better Auth
* session from trusted upstream headers (Authentik / Authelia /
* oauth2-proxy / Caddy), and returns the user, session, and the
* `Set-Cookie` headers for the middleware to forward onto the
* outbound response.
*
* Fail-open: returns null on any failure (endpoint disabled, headers
* missing, DB blip, malformed response). The middleware then sets
* locals to null and the request proceeds as anonymous broken
* header auth must never lock everyone out of the cookie-auth path.
*
* Cookie extraction prefers `Response.headers.getSetCookie()` (Node 18+
* fetch, undici). Older runtimes that only expose `get('set-cookie')`
* fall through to the single-header form; that path coalesces all
* Set-Cookie values into one comma-separated string, which is wrong
* for cookies whose attributes contain commas (`Expires` does). We
* accept that risk because: (a) Bun and the supported Node versions
* for this project both implement `getSetCookie`, and (b) the
* fallback only fires on truly ancient runtimes that aren't in our
* support matrix.
*/
export async function mintSessionFromHeaders(
request: Request,
): Promise<BridgeResult | null> {
try {
const response = await auth.api.signInWithHeader({
headers: request.headers,
asResponse: true,
});
if (!response.ok) return null;
const data = await response.json().catch(() => null);
if (!data?.user || !data?.session) return null;
const setCookies =
typeof response.headers.getSetCookie === "function"
? response.headers.getSetCookie()
: response.headers.get("set-cookie")
? [response.headers.get("set-cookie") as string]
: [];
return { user: data.user, session: data.session, setCookies };
} catch {
return null;
}
}
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import { headerAuthPlugin } from "./auth-header-plugin";
describe("headerAuthPlugin", () => {
test("registers the `header-auth` plugin id", () => {
const plugin = headerAuthPlugin();
expect(plugin.id).toBe("header-auth");
});
test("exposes a `signInWithHeader` endpoint", () => {
const plugin = headerAuthPlugin();
expect(plugin.endpoints?.signInWithHeader).toBeDefined();
});
test("mounts the endpoint at POST /sign-in/header", () => {
// The Astro API route is /api/auth/<plugin-path>, so the resolved
// URL the middleware bridge talks to is /api/auth/sign-in/header.
// Locking that path down in a test prevents an accidental rename
// from silently breaking the React SPA's auth flow.
const plugin = headerAuthPlugin();
const endpoint = plugin.endpoints?.signInWithHeader as unknown as {
path: string;
options: { method: string };
};
expect(endpoint.path).toBe("/sign-in/header");
expect(endpoint.options.method).toBe("POST");
});
});
+78
View File
@@ -0,0 +1,78 @@
import type { BetterAuthPlugin } from "better-auth";
import { APIError, createAuthEndpoint } from "better-auth/api";
import { setSessionCookie } from "better-auth/cookies";
import { authenticateWithHeaders, isHeaderAuthEnabled } from "./auth-header";
/**
* Better Auth plugin that bridges header / forward authentication into a
* real Better Auth session.
*
* Why this exists: the Astro middleware historically populated
* `context.locals.user` from trusted upstream headers (Authentik /
* Authelia / oauth2-proxy / Caddy), but never minted a Better Auth
* session. Server-rendered pages saw the user, but the React SPA's
* `/api/auth/get-session` call hit Better Auth's handler which only
* reads its session cookie and got `null`. The auth guard then
* bounced to `/login`, so header auth was end-to-end broken.
*
* This plugin exposes `POST /sign-in/header`, which the middleware
* calls once per cold request (no cookie yet) when header auth is
* enabled. It verifies the trusted headers, creates a real session
* row via `internalAdapter.createSession`, and attaches the
* `Set-Cookie` to the response. The middleware then forwards that
* cookie to the outbound Astro response, so the SPA's next call to
* `get-session` carries the cookie and works.
*
* The endpoint trusts whatever upstream sets the configured headers
* the security model here is "the operator controls the reverse
* proxy." Make sure the proxy strips inbound copies of these headers
* before forwarding (documented in docs/SSO-OIDC-SETUP.md).
*/
export const headerAuthPlugin = () =>
({
id: "header-auth",
endpoints: {
signInWithHeader: createAuthEndpoint(
"/sign-in/header",
{ method: "POST" },
async (ctx) => {
if (!isHeaderAuthEnabled()) {
throw new APIError("NOT_FOUND", {
message: "Header authentication is not enabled",
});
}
const headers = ctx.request?.headers ?? ctx.headers;
if (!headers) {
throw new APIError("BAD_REQUEST", {
message: "Request headers unavailable",
});
}
const user = await authenticateWithHeaders(headers);
if (!user) {
throw new APIError("UNAUTHORIZED", {
message: "Header authentication failed",
});
}
const session = await ctx.context.internalAdapter.createSession(
user.id,
);
if (!session) {
throw new APIError("INTERNAL_SERVER_ERROR", {
message: "Failed to create session",
});
}
await setSessionCookie(ctx, { session, user });
return ctx.json({
token: session.token,
user,
session,
});
},
),
},
}) satisfies BetterAuthPlugin;
+158
View File
@@ -0,0 +1,158 @@
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import {
extractUserFromHeaders,
isHeaderAuthEnabled,
getHeaderAuthConfig,
} from "./auth-header";
// `auth-header` reads config from `process.env` at call time. We snapshot
// the relevant keys and restore them after each test so cases don't bleed.
const HEADER_ENV_KEYS = [
"HEADER_AUTH_ENABLED",
"HEADER_AUTH_AUTO_PROVISION",
"HEADER_AUTH_USER_HEADER",
"HEADER_AUTH_EMAIL_HEADER",
"HEADER_AUTH_NAME_HEADER",
"HEADER_AUTH_ALLOWED_DOMAINS",
] as const;
let savedEnv: Partial<Record<(typeof HEADER_ENV_KEYS)[number], string | undefined>> = {};
function setEnv(vars: Partial<Record<(typeof HEADER_ENV_KEYS)[number], string>>) {
for (const key of HEADER_ENV_KEYS) {
if (key in vars) {
process.env[key] = vars[key]!;
} else {
delete process.env[key];
}
}
}
beforeEach(() => {
savedEnv = Object.fromEntries(
HEADER_ENV_KEYS.map((k) => [k, process.env[k]]),
) as typeof savedEnv;
});
afterEach(() => {
for (const key of HEADER_ENV_KEYS) {
const v = savedEnv[key];
if (v === undefined) delete process.env[key];
else process.env[key] = v;
}
});
describe("isHeaderAuthEnabled", () => {
test("returns false when HEADER_AUTH_ENABLED is unset", () => {
setEnv({});
expect(isHeaderAuthEnabled()).toBe(false);
});
test("returns false when HEADER_AUTH_ENABLED is anything other than the string 'true'", () => {
setEnv({ HEADER_AUTH_ENABLED: "1" });
expect(isHeaderAuthEnabled()).toBe(false);
setEnv({ HEADER_AUTH_ENABLED: "yes" });
expect(isHeaderAuthEnabled()).toBe(false);
});
test("returns true only for HEADER_AUTH_ENABLED='true' exactly", () => {
setEnv({ HEADER_AUTH_ENABLED: "true" });
expect(isHeaderAuthEnabled()).toBe(true);
});
});
describe("extractUserFromHeaders", () => {
test("returns null when header auth is disabled", () => {
setEnv({});
const headers = new Headers({ "X-Authentik-Username": "u" });
expect(extractUserFromHeaders(headers)).toBeNull();
});
test("returns null when the configured user header is absent", () => {
setEnv({ HEADER_AUTH_ENABLED: "true" });
const headers = new Headers({ "X-Some-Other-Header": "u" });
expect(extractUserFromHeaders(headers)).toBeNull();
});
test("returns username, email, and name from default Authentik headers", () => {
setEnv({ HEADER_AUTH_ENABLED: "true" });
const headers = new Headers({
"X-Authentik-Username": "alice",
"X-Authentik-Email": "alice@example.com",
"X-Authentik-Name": "Alice Q",
});
expect(extractUserFromHeaders(headers)).toEqual({
username: "alice",
email: "alice@example.com",
name: "Alice Q",
});
});
test("respects HEADER_AUTH_USER_HEADER override (Caddy / caddy-security style)", () => {
setEnv({
HEADER_AUTH_ENABLED: "true",
HEADER_AUTH_USER_HEADER: "X-Token-User-Email",
HEADER_AUTH_EMAIL_HEADER: "X-Token-User-Email",
HEADER_AUTH_NAME_HEADER: "X-Token-User-Name",
});
const headers = new Headers({
"X-Token-User-Email": "bob@example.com",
"X-Token-User-Name": "Bob",
});
// lanrat's reported config: username and email are both pulled from
// the same header. Both should resolve to that value.
expect(extractUserFromHeaders(headers)).toEqual({
username: "bob@example.com",
email: "bob@example.com",
name: "Bob",
});
});
test("rejects when email domain is not on the allow list", () => {
setEnv({
HEADER_AUTH_ENABLED: "true",
HEADER_AUTH_ALLOWED_DOMAINS: "example.com,corp.example",
});
const headers = new Headers({
"X-Authentik-Username": "evil",
"X-Authentik-Email": "evil@elsewhere.test",
});
expect(extractUserFromHeaders(headers)).toBeNull();
});
test("accepts when email domain matches the allow list", () => {
setEnv({
HEADER_AUTH_ENABLED: "true",
HEADER_AUTH_ALLOWED_DOMAINS: "example.com,corp.example",
});
const headers = new Headers({
"X-Authentik-Username": "alice",
"X-Authentik-Email": "alice@corp.example",
});
expect(extractUserFromHeaders(headers)).toEqual({
username: "alice",
email: "alice@corp.example",
name: undefined,
});
});
});
describe("getHeaderAuthConfig", () => {
test("merges env overrides over defaults without leaking unset env values", () => {
setEnv({
HEADER_AUTH_ENABLED: "true",
HEADER_AUTH_USER_HEADER: "X-Forwarded-User",
});
const config = getHeaderAuthConfig();
expect(config.enabled).toBe(true);
expect(config.userHeader).toBe("X-Forwarded-User");
// Unset overrides should fall back to defaults, not become undefined.
expect(config.emailHeader).toBe("X-Authentik-Email");
expect(config.nameHeader).toBe("X-Authentik-Name");
});
});
+9
View File
@@ -6,6 +6,7 @@ import { db, users } from "./db";
import * as schema from "./db/schema";
import { eq } from "drizzle-orm";
import { withBase } from "./base-path";
import { headerAuthPlugin } from "./auth-header-plugin";
/**
* Resolves the list of trusted origins for Better Auth CSRF validation.
@@ -205,6 +206,14 @@ export const auth = betterAuth({
// Trust email_verified claims from the upstream provider so we can link by matching email
trustEmailVerified: true,
}),
// Header / forward authentication bridge. Exposes
// POST /api/auth/sign-in/header so the middleware can mint a real
// Better Auth session from trusted upstream headers (Authentik /
// Authelia / oauth2-proxy / Caddy). Without this the SPA's
// /api/auth/get-session call returns null on header-auth-only
// requests and bounces the user to /login. See auth-header-plugin.ts.
headerAuthPlugin(),
],
});
+57 -3
View File
@@ -421,9 +421,18 @@ export async function syncGiteaRepoEnhanced({
throw new Error(`Repository ${repository.name} is not a mirror. Cannot sync.`);
}
// Parse repository metadata state up-front. The force-push
// detection below needs the acknowledgedDeletions list to suppress
// already-handled deletions, and a successful snapshot needs to
// record new entries back into the same state object. The
// metadata-mirroring block downstream reuses this same variable.
const metadataState = parseRepositoryMetadataState(repository.metadata);
let metadataUpdated = false;
// ---- Smart backup strategy with force-push detection ----
const backupStrategy = resolveBackupStrategy(config);
let forcePushDetected = false;
let forcePushAffected: ReadonlyArray<{ name: string; reason: string; giteaSha: string }> = [];
if (backupStrategy !== "disabled") {
// Run force-push detection if the strategy requires it
@@ -441,9 +450,11 @@ export async function syncGiteaRepoEnhanced({
octokit: fpOctokit,
githubOwner: repository.owner,
githubRepo: repository.name,
acknowledgedDeletions: metadataState.acknowledgedDeletions,
});
forcePushDetected = detectionResult.detected;
forcePushAffected = detectionResult.affectedBranches;
if (detectionResult.skipped) {
console.log(
@@ -457,6 +468,39 @@ export async function syncGiteaRepoEnhanced({
`[Sync] Force-push detected on ${repository.name}: ${branchNames}`,
);
}
// Record each detected "deleted" branch into the
// acknowledged list. We do this based on detection alone,
// BEFORE the backup attempt below, so that:
// - concurrent sync invocations both add the entry
// (the second one whose `createPreSyncBundleBackup`
// short-circuits would otherwise skip the push and
// race its empty in-memory state onto the metadata
// row, undoing the first invocation's write);
// - if the backup later fails the deletion is still
// acknowledged (the branch is genuinely gone from
// GitHub; not re-detecting it next sync is correct
// regardless of whether THIS invocation's backup
// succeeded — prior backups still exist on disk and
// the user can re-trigger one manually if needed).
const newAcknowledged = forcePushAffected
.filter((b) => b.reason === "deleted")
.map((b) => ({ branch: b.name, giteaSha: b.giteaSha }));
if (newAcknowledged.length > 0) {
const existingKeys = new Set(
metadataState.acknowledgedDeletions.map(
(e) => `${e.branch}@${e.giteaSha}`,
),
);
for (const entry of newAcknowledged) {
const key = `${entry.branch}@${entry.giteaSha}`;
if (!existingKeys.has(key)) {
metadataState.acknowledgedDeletions.push(entry);
existingKeys.add(key);
metadataUpdated = true;
}
}
}
} else {
console.log(
`[Sync] Skipping force-push detection for ${repository.name}: no GitHub token`,
@@ -519,8 +563,17 @@ export async function syncGiteaRepoEnhanced({
repositoryName: repository.name,
message: `Snapshot created for ${repository.name}`,
details: `Pre-sync snapshot created at ${backupResult.bundlePath}.`,
status: "syncing",
// The snapshot is already complete (createPreSyncBundleBackup
// returned above). Using "syncing" here left the row in a
// non-terminal state and there was no later code path to
// advance it, so every force-push-triggered backup leaked an
// orphan row that accumulated on the jobs page forever.
status: "synced",
});
// Note: acknowledging the deletion happens earlier (right
// after detection) so concurrent sync invocations both
// record the entry. Don't move it back here — see the
// detection block above for the rationale.
} catch (backupError) {
const errorMessage =
backupError instanceof Error ? backupError.message : String(backupError);
@@ -584,8 +637,9 @@ export async function syncGiteaRepoEnhanced({
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
});
const metadataState = parseRepositoryMetadataState(repository.metadata);
let metadataUpdated = false;
// metadataState + metadataUpdated are hoisted above the backup
// strategy block so force-push detection can read/write the
// acknowledged-deletions list. Don't shadow them here.
const skipMetadataForStarred =
repository.isStarred && config.githubConfig?.starredCodeOnly;
let metadataOctokit: Octokit | null = null;
+282
View File
@@ -0,0 +1,282 @@
/**
* Regression test for duplicate-issue creation on retry-after-deadlock.
*
* `mirrorGitRepoIssuesToGitea` pre-fetches all existing Gitea issues
* into `giteaIssueByGitHubNumber` ONCE at function entry, then iterates
* per-issue via `processWithRetry`. Each iteration uses the cached map
* to decide CREATE vs PATCH.
*
* The bug: when Gitea's CreateIssue handler commits the issue insert
* in one transaction and then deadlocks on the addLabel / repository
* counter update in a second transaction, the issue row is committed
* and visible but the in-memory map is never refreshed between
* retries. So `processWithRetry` would call the callback again,
* `existingIssue` is still `undefined` from the stale map, and a fresh
* `httpPost` creates a duplicate.
*
* Reproduces deterministically on MySQL (1213/40001) and PostgreSQL
* (40P01). SQLite escapes because writes serialize globally.
*
* This test asserts on the *structure* of the source rather than
* invoking the function, because behavioral tests for the issue-mirror
* pipeline require heavy module mocks that pollute other test files
* (bun's mock.module is process-wide). See
* `gitea-mirror-failure-recovery.test.ts` for the same convention.
*
* The two structural guarantees this test enforces:
* (1) Before the create-issue httpPost call, the code performs a
* defensive recheck via httpGet that queries Gitea by
* `[GH-ISSUE #N]` title marker handles "previous attempt
* committed the issue then threw" scenarios.
* (2) After a successful httpPost create, the new issue is written
* back into `giteaIssueByGitHubNumber` handles "this attempt
* created the issue, but a later step in the same callback
* (e.g. comment sync) throws and triggers another retry"
* scenarios.
*/
import { describe, test, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const SOURCE = readFileSync(join(import.meta.dir, "gitea.ts"), "utf8");
/**
* Locate the body of a function declaration by name. Walks from the
* declaration, balances parens to skip the parameter list (which can
* contain destructured object literals with their own braces), then
* finds the body's opening brace and its matching close.
*
* Same helper as in `gitea-mirror-failure-recovery.test.ts`; kept
* local to keep this test file self-contained.
*/
function extractFunctionBody(source: string, declarationStart: RegExp): string {
const match = source.match(declarationStart);
if (!match) {
throw new Error(`Could not locate declaration ${declarationStart}`);
}
let i = match.index! + match[0].length;
while (i < source.length && source[i] !== "(") i++;
if (source[i] !== "(") {
throw new Error(`No '(' after ${declarationStart}`);
}
let parenDepth = 0;
for (; i < source.length; i++) {
if (source[i] === "(") parenDepth++;
else if (source[i] === ")") {
parenDepth--;
if (parenDepth === 0) {
i++;
break;
}
}
}
while (i < source.length && source[i] !== "{") i++;
if (source[i] !== "{") {
throw new Error(`No body '{' for ${declarationStart}`);
}
let braceDepth = 0;
const startIdx = i;
for (; i < source.length; i++) {
if (source[i] === "{") braceDepth++;
else if (source[i] === "}") {
braceDepth--;
if (braceDepth === 0) {
return source.slice(startIdx, i + 1);
}
}
}
throw new Error(`Unterminated body for ${declarationStart}`);
}
describe("issue dedup on retry-after-deadlock", () => {
const body = extractFunctionBody(
SOURCE,
/export const mirrorGitRepoIssuesToGitea = async\b/
);
test("body contains the per-issue create branch we expect to guard", () => {
// Sanity: make sure the test is looking at the right code path.
// If these strings disappear due to a refactor, this test should
// fail loudly so a human reviews whether the dedup guarantees
// still hold in the new shape.
expect(
body.includes(
"giteaIssueByGitHubNumber.get(issue.number)"
),
"expected the per-issue lookup against giteaIssueByGitHubNumber"
).toBe(true);
expect(
body.match(/await httpPost\(\s*`\$\{config\.giteaConfig!\.url\}\/api\/v1\/repos\/\$\{giteaOwner\}\/\$\{repoName\}\/issues`/),
"expected the create-issue httpPost call"
).toBeTruthy();
});
test("defensive recheck via httpGet runs BEFORE the create httpPost", () => {
// The recheck must query Gitea by [GH-ISSUE #N] marker to catch
// the partial-commit case. Without it, a deadlock-after-insert
// returns 5xx, processWithRetry re-runs the callback, and the
// create call produces a duplicate row.
const recheckIdx = body.search(
/await httpGet\([^)]*\[GH-ISSUE #\$\{issue\.number\}\]/
);
expect(
recheckIdx,
"defensive recheck via httpGet using [GH-ISSUE #N] marker must exist"
).toBeGreaterThanOrEqual(0);
// The recheck must come before the create httpPost in source order.
// The first httpPost on the .../issues endpoint inside this
// function body is the create call; we anchor against it.
const createIdx = body.search(
/await httpPost\(\s*`\$\{config\.giteaConfig!\.url\}\/api\/v1\/repos\/\$\{giteaOwner\}\/\$\{repoName\}\/issues`/
);
expect(createIdx, "create httpPost call must exist").toBeGreaterThanOrEqual(0);
expect(
recheckIdx,
"the recheck must run BEFORE the create call so it can short-circuit on partial-commit duplicates"
).toBeLessThan(createIdx);
});
test("recheck hit short-circuits via PATCH and updates the cache", () => {
// When the recheck finds a hit (i.e. a previous failed attempt
// already created this issue), the code should:
// - cache the hit into giteaIssueByGitHubNumber so subsequent
// retries within this run also find it
// - go down the PATCH path (httpPatch) instead of httpPost
// - log a recognisable line so operators can spot recovery
expect(
body.includes(
"giteaIssueByGitHubNumber.set(issue.number, recheckHit)"
) ||
body.match(/giteaIssueByGitHubNumber\.set\(\s*issue\.number\s*,\s*recheckHit/),
"recheck hit must be written back into giteaIssueByGitHubNumber"
).toBeTruthy();
expect(
body.match(/Recovered orphan from prior failed attempt/i),
"a log line should make the recovery path visible in operator logs"
).toBeTruthy();
});
test("pre-fetch issues pagination uses Link header (not short-page heuristic)", () => {
// The previous `if (pageIssues.length < issuesPerPage) break;`
// heuristic was wrong in both directions:
// - Gitea caps response size at `[api].MAX_RESPONSE_ITEMS`
// (default 50), typically lower than `issuesPerPage` (100),
// so the very first page already looks "short" and
// pagination terminated after 50 items. Every issue past
// that was misclassified as new and duplicated on every sync.
// - Naive removal of that break, relying only on "break on
// empty page", can loop forever because some Gitea endpoints
// return the same data on every page when asked for a page
// past the actual end (instead of returning []).
//
// The correct fix is to use the Link header (RFC 5988): if
// `rel="next"` is absent, we're done.
//
// This test asserts:
// - the broken short-page check is gone
// - the existing-issues loop checks the Link header for next
const issuesPaginationRegion = body.substring(
body.indexOf("existingGiteaIssues.push"),
body.indexOf("issuesPage += 1") + 30
);
expect(
issuesPaginationRegion,
"issues pagination region should be present"
).not.toBe("");
expect(
/\bpageIssues\.length\s*<\s*issuesPerPage\b/.test(issuesPaginationRegion),
"the short-page break (pageIssues.length < issuesPerPage) must be removed"
).toBe(false);
expect(
/existingIssuesRes\.headers\.get\(\s*["']link["']\s*\)/.test(
issuesPaginationRegion
) && /rel="next"/.test(issuesPaginationRegion),
"the issues pagination loop must use the Link header (rel=\"next\") " +
"to decide whether to fetch the next page"
).toBe(true);
});
test("per-issue comments pagination also uses Link header (not short-page heuristic)", () => {
// Same correctness concerns as issues pagination above. The per-
// issue comments endpoint is subject to the same Gitea page-size
// cap, and naive empty-page detection has the same risk.
expect(
/\bpageComments\.length\s*<\s*commentsPerPage\b/.test(body),
"the short-page break (pageComments.length < commentsPerPage) must be removed"
).toBe(false);
// Look only at the comments-fetch region (not the whole file) so
// a future caller using a different response variable name in
// another place won't false-positive this assertion.
const commentsRegion = body.substring(
body.indexOf("existingComments.push"),
body.indexOf("commentsPage += 1") + 30
);
expect(
commentsRegion,
"comments pagination region should be present"
).not.toBe("");
expect(
/existingCommentsRes\.headers\.get\(\s*["']link["']\s*\)/.test(
commentsRegion
) && /rel="next"/.test(commentsRegion),
"the comments pagination loop must use the Link header (rel=\"next\") " +
"to decide whether to fetch the next page"
).toBe(true);
});
describe("PR mirror has the same guarantees", () => {
// mirrorGitRepoPullRequestsToGitea has parallel structure:
// - pre-fetches existing Gitea "issues that are mirrored PRs",
// keyed by `[PR #N]` marker in title
// - per-PR callback decides PATCH vs CREATE
// - same Gitea-side pagination cap and deadlock-after-commit
// risks apply
// The fix mirrors gitea-issues here.
const prBody = extractFunctionBody(
SOURCE,
/export async function mirrorGitRepoPullRequestsToGitea\b/
);
test("PR pre-fetch pagination uses Link header", () => {
expect(
/\bpageIssues\.length\s*<\s*prIssuesPerPage\b/.test(prBody),
"the short-page break (pageIssues.length < prIssuesPerPage) must be removed"
).toBe(false);
// The PR pre-fetch reuses the existingIssuesRes variable name
expect(
/existingIssuesRes\.headers\.get\(\s*["']link["']\s*\)/.test(prBody) &&
/rel="next"/.test(prBody),
"the PR pre-fetch loop must use the Link header (rel=\"next\")"
).toBe(true);
});
test("PR create path defensively rechecks via [PR #N] before httpPost", () => {
// Both the enriched and basic-fallback create paths must have
// a recheck so partial-commit retries don't duplicate the PR.
const rechecks =
prBody.match(/Recovered orphan from prior failed attempt for PR/g) ||
[];
expect(
rechecks.length,
"expected at least two 'Recovered orphan' log lines " +
"(one for the enriched create path, one for the basic-fallback path)"
).toBeGreaterThanOrEqual(2);
});
});
test("successful create caches the new issue into the dedup map", () => {
// Without this, a retry triggered by a *later* step in the same
// per-issue callback (e.g. comment sync throwing) would re-enter
// the create path on the next attempt — same root duplication
// pattern, different trigger.
expect(
body.match(
/giteaIssueByGitHubNumber\.set\(\s*issue\.number\s*,\s*createdIssue\.data\s*\)/
),
"after a successful create, the new issue must be stored in giteaIssueByGitHubNumber"
).toBeTruthy();
});
});
+200
View File
@@ -0,0 +1,200 @@
/**
* Regression test for duplicate milestone & label creation on every sync.
*
* Observed in production (May 2026): a Gitea instance accumulated
* 11,847 duplicate closed milestones across 4 mirrored repos after only
* a handful of scheduled syncs. Two compounding bugs in
* `mirrorGitRepoMilestonesToGitea`:
*
* (1) The existing-milestones GET to Gitea did NOT pass `state=all`.
* Gitea's /milestones endpoint defaults to `state=open`, so the
* `existingMilestones` Set never contained any closed milestone
* title. Every closed GitHub milestone was misclassified as
* missing and re-POSTed on every sync.
*
* (2) The existing-milestones GET was a single unpaginated call.
* Gitea caps response size at `[api].MAX_RESPONSE_ITEMS`
* (default 50), so any repo with more milestones than that
* silently truncates even when (1) is fixed.
*
* `mirrorGitRepoLabelsToGitea` has the same pagination bug (2). It
* doesn't have bug (1) because /labels has no state filter, and it
* hadn't yet shown duplicates in production only because no mirrored
* repo had crossed 50 distinct labels but it would the moment one
* did.
*
* These tests assert on the *structure* of the source rather than
* invoking the functions, because behavioral tests for the metadata
* pipeline require heavy module mocks that pollute other test files
* (bun's mock.module is process-wide). Same convention as
* `gitea-issue-dedup-on-retry.test.ts` and
* `gitea-mirror-failure-recovery.test.ts`.
*/
import { describe, test, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const SOURCE = readFileSync(join(import.meta.dir, "gitea.ts"), "utf8");
/**
* Locate the body of a function declaration by name. Walks from the
* declaration, balances parens to skip the parameter list (which can
* contain destructured object literals with their own braces), then
* finds the body's opening brace and its matching close.
*/
function extractFunctionBody(source: string, declarationStart: RegExp): string {
const match = source.match(declarationStart);
if (!match) {
throw new Error(`Could not locate declaration ${declarationStart}`);
}
let i = match.index! + match[0].length;
while (i < source.length && source[i] !== "(") i++;
if (source[i] !== "(") {
throw new Error(`No '(' after ${declarationStart}`);
}
let parenDepth = 0;
for (; i < source.length; i++) {
if (source[i] === "(") parenDepth++;
else if (source[i] === ")") {
parenDepth--;
if (parenDepth === 0) {
i++;
break;
}
}
}
while (i < source.length && source[i] !== "{") i++;
if (source[i] !== "{") {
throw new Error(`No body '{' for ${declarationStart}`);
}
let braceDepth = 0;
const startIdx = i;
for (; i < source.length; i++) {
if (source[i] === "{") braceDepth++;
else if (source[i] === "}") {
braceDepth--;
if (braceDepth === 0) {
return source.slice(startIdx, i + 1);
}
}
}
throw new Error(`Unterminated body for ${declarationStart}`);
}
describe("milestone dedup on sync", () => {
const body = extractFunctionBody(
SOURCE,
/export async function mirrorGitRepoMilestonesToGitea\b/
);
test("body contains the per-milestone create branch we expect to guard", () => {
// Sanity check: anchor the rest of this suite to the right path.
expect(
body.includes("existingMilestones"),
"expected the existingMilestones set/map used for dedup"
).toBe(true);
expect(
body.match(
/await httpPost\(\s*`\$\{config\.giteaConfig\.url\}\/api\/v1\/repos\/\$\{giteaOwner\}\/\$\{repoName\}\/milestones`/
),
"expected the create-milestone httpPost call"
).toBeTruthy();
});
test("existing-milestones GET must include state=all", () => {
// Without state=all, Gitea returns only open milestones, so every
// closed GitHub milestone is misclassified as missing and re-POSTed
// on every sync. This was the root cause of the production blowup.
const getMatch = body.match(
/httpGet\(\s*`\$\{config\.giteaConfig\.url\}\/api\/v1\/repos\/\$\{giteaOwner\}\/\$\{repoName\}\/milestones\?[^`]*`/
);
expect(
getMatch,
"expected a milestones httpGet call with a query string"
).toBeTruthy();
expect(
/state=all/.test(getMatch![0]),
"the existing-milestones GET must pass state=all (Gitea defaults to state=open)"
).toBe(true);
});
test("existing-milestones GET must paginate with both Link and X-Total-Count fallback", () => {
// Even with state=all, a single unpaginated call only ever sees
// the first 50 milestones (Gitea's MAX_RESPONSE_ITEMS cap).
//
// Gitea's /milestones endpoint does NOT emit a Link header — only
// `X-Total-Count`. A strict Link-only check terminates after page 1
// and re-POSTs every milestone past index 50 on every sync (the
// 9-milestone leak observed on Subnet-Calculator after the
// Link-only version of this fix shipped).
expect(
/milestonesPage\s*\+=\s*1/.test(body),
"expected a page-increment loop for existing milestones"
).toBe(true);
expect(
/\.headers\.get\(\s*["']link["']\s*\)/.test(body) &&
/rel="next"/.test(body),
"the milestones pagination loop must check the Link header (rel=\"next\")"
).toBe(true);
expect(
/\.headers\.get\(\s*["']x-total-count["']\s*\)/.test(body),
"the milestones pagination loop must fall back to X-Total-Count when Link header is absent (Gitea /milestones only emits X-Total-Count)"
).toBe(true);
});
test("newly-created milestone must be cached into existingMilestones", () => {
// Defensive: if `milestones` ever contains a same-named entry
// twice (unlikely but cheap to guard), we shouldn't POST it twice.
expect(
/existingMilestones\.add\(\s*milestone\.title\s*\)/.test(body),
"after a successful create, the new milestone title must be added to existingMilestones"
).toBe(true);
});
});
describe("label dedup on sync", () => {
const body = extractFunctionBody(
SOURCE,
/export async function mirrorGitRepoLabelsToGitea\b/
);
test("body contains the per-label create branch we expect to guard", () => {
expect(
body.includes("existingLabels"),
"expected the existingLabels set used for dedup"
).toBe(true);
expect(
body.match(
/await httpPost\(\s*`\$\{config\.giteaConfig\.url\}\/api\/v1\/repos\/\$\{giteaOwner\}\/\$\{repoName\}\/labels`/
),
"expected the create-label httpPost call"
).toBeTruthy();
});
test("existing-labels GET must paginate with both Link and X-Total-Count fallback", () => {
// Same Gitea MAX_RESPONSE_ITEMS=50 cap as milestones / issues.
// Gitea's /labels endpoint, like /milestones, does NOT emit a Link
// header — only `X-Total-Count`. Strict Link-only check would
// silently truncate after page 1.
expect(
/labelsPage\s*\+=\s*1/.test(body),
"expected a page-increment loop for existing labels"
).toBe(true);
expect(
/\.headers\.get\(\s*["']link["']\s*\)/.test(body) &&
/rel="next"/.test(body),
"the labels pagination loop must check the Link header (rel=\"next\")"
).toBe(true);
expect(
/\.headers\.get\(\s*["']x-total-count["']\s*\)/.test(body),
"the labels pagination loop must fall back to X-Total-Count when Link header is absent (Gitea /labels only emits X-Total-Count)"
).toBe(true);
});
test("newly-created label must be cached into existingLabels", () => {
expect(
/existingLabels\.add\(\s*label\.name\s*\)/.test(body),
"after a successful create, the new label name must be added to existingLabels"
).toBe(true);
});
});
+259 -48
View File
@@ -2146,7 +2146,21 @@ export const mirrorGitRepoIssuesToGitea = async ({
if (!pageIssues.length) break;
existingGiteaIssues.push(...pageIssues);
if (pageIssues.length < issuesPerPage) break;
// Use the Link header (RFC 5988) to decide whether more pages
// exist. The old short-page-length heuristic was wrong in both
// directions:
// - Gitea caps response size at `[api].MAX_RESPONSE_ITEMS`
// (default 50), typically lower than `issuesPerPage` (100),
// so the very first page already looks "short" and
// pagination terminated after 50 items — every issue past
// that was misclassified as new and duplicated on every sync.
// - For some endpoints Gitea returns the same data on every
// page when the page is past the end, so a naive "break on
// empty" alone can loop forever if the server doesn't return
// []. Link header is the safe signal.
const linkHeader = existingIssuesRes.headers.get("link") || "";
if (!/\brel="next"/.test(linkHeader)) break;
issuesPage += 1;
}
@@ -2289,30 +2303,85 @@ export const mirrorGitRepoIssuesToGitea = async ({
}
);
} else {
const createdIssue = await httpPost(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues`,
issuePayload,
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
targetIssueNumber = createdIssue.data.number;
// Defensive recheck before create: a previous retry attempt may
// have already created this issue and then thrown. The common
// trigger is Gitea's CreateIssue handler committing the issue
// insert in one transaction and then deadlocking on the
// addLabel / repository counter update in a second transaction.
// The issue row is committed and visible, but the in-memory
// giteaIssueByGitHubNumber map (built once at function entry)
// doesn't know about it, so without this check processWithRetry
// would create a duplicate every time the create returns 5xx
// after a partial commit.
//
// Reproduces deterministically on MySQL (Error 1213 / 40001)
// and PostgreSQL (40P01); SQLite escapes because writes
// serialize globally.
let recheckHit: any = null;
try {
const recheck = await httpGet(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues?state=all&type=issues&q=${encodeURIComponent(`[GH-ISSUE #${issue.number}]`)}`,
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
const candidates = Array.isArray(recheck.data) ? recheck.data : [];
recheckHit = candidates.find(
(c: any) => extractGitHubIssueNumber(c.title) === issue.number
) ?? null;
} catch (_recheckErr) {
// Best-effort; fall through to create.
}
if (issue.state === "closed" && createdIssue.data.state !== "closed") {
try {
await httpPatch(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues/${targetIssueNumber}`,
{ state: "closed" },
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
} catch (closeError) {
console.error(
`[Issues] Failed to close issue #${targetIssueNumber}: ${
closeError instanceof Error ? closeError.message : String(closeError)
}`
);
if (recheckHit) {
giteaIssueByGitHubNumber.set(issue.number, recheckHit);
existingIssue = recheckHit;
targetIssueNumber = recheckHit.number;
console.log(
`[Issues] Recovered orphan from prior failed attempt for #${issue.number}; switching to PATCH`
);
await httpPatch(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues/${targetIssueNumber}`,
{
title: issuePayload.title,
body: issuePayload.body,
state: issue.state === "closed" ? "closed" : "open",
labels: issuePayload.labels,
},
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
} else {
const createdIssue = await httpPost(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues`,
issuePayload,
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
targetIssueNumber = createdIssue.data.number;
// Cache the new issue immediately so a subsequent retry of
// this callback (e.g. triggered by a later step like comment
// sync failing) doesn't lose track of it.
giteaIssueByGitHubNumber.set(issue.number, createdIssue.data);
if (issue.state === "closed" && createdIssue.data.state !== "closed") {
try {
await httpPatch(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues/${targetIssueNumber}`,
{ state: "closed" },
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
} catch (closeError) {
console.error(
`[Issues] Failed to close issue #${targetIssueNumber}: ${
closeError instanceof Error ? closeError.message : String(closeError)
}`
);
}
}
}
}
@@ -2355,7 +2424,13 @@ export const mirrorGitRepoIssuesToGitea = async ({
: [];
if (!pageComments.length) break;
existingComments.push(...pageComments);
if (pageComments.length < commentsPerPage) break;
// Use the Link header to decide whether more pages exist.
// See note on the existing-issues pagination above; the
// same Gitea behaviors (MAX_RESPONSE_ITEMS cap and
// repeated-data on out-of-bound pages) apply here.
const commentsLinkHeader =
existingCommentsRes.headers.get("link") || "";
if (!/\brel="next"/.test(commentsLinkHeader)) break;
commentsPage += 1;
}
const mirroredCommentIds = new Set<number>();
@@ -2983,7 +3058,12 @@ export async function mirrorGitRepoPullRequestsToGitea({
}
}
if (pageIssues.length < prIssuesPerPage) break;
// See note on the existing-issues pre-fetch above: rely on Link
// header (RFC 5988) rather than short-page heuristic. Gitea caps
// page size at MAX_RESPONSE_ITEMS (default 50), and some
// endpoints repeat data on out-of-bound pages instead of [].
const linkHeader = existingIssuesRes.headers.get("link") || "";
if (!/\brel="next"/.test(linkHeader)) break;
prIssuesPage += 1;
}
@@ -3084,7 +3164,36 @@ export async function mirrorGitRepoPullRequestsToGitea({
closed: pr.state === "closed" || pr.merged_at !== null,
};
const existingPrIssue = existingPrIssuesByNumber.get(pr.number);
let existingPrIssue = existingPrIssuesByNumber.get(pr.number);
// Defensive recheck (see same pattern in mirrorGitRepoIssuesToGitea):
// a previous attempt may have committed the PR-issue row and
// then thrown on the addLabel/repository-counter update. The
// pre-fetched map doesn't know about it, so without this check
// processWithRetry would create a duplicate every retry.
if (!existingPrIssue) {
try {
const recheck = await httpGet(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues?state=all&type=issues&q=${encodeURIComponent(`[PR #${pr.number}]`)}`,
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
const candidates = Array.isArray(recheck.data) ? recheck.data : [];
const hit = candidates.find((c: any) => {
const m = String(c.title || "").match(/\[PR #(\d+)\]/i);
return m && Number.parseInt(m[1], 10) === pr.number;
});
if (hit) {
existingPrIssue = hit;
existingPrIssuesByNumber.set(pr.number, hit);
console.log(
`[Pull Requests] Recovered orphan from prior failed attempt for PR #${pr.number}; switching to PATCH`
);
}
} catch (_recheckErr) {
// Best-effort; fall through to create.
}
}
if (existingPrIssue) {
await httpPatch(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues/${existingPrIssue.number}`,
@@ -3145,7 +3254,34 @@ export async function mirrorGitRepoPullRequestsToGitea({
};
try {
const existingPrIssue = existingPrIssuesByNumber.get(pr.number);
let existingPrIssue = existingPrIssuesByNumber.get(pr.number);
// Defensive recheck — same pattern as the enriched create
// branch above. Without this, the basic-info fallback would
// dup on retry-after-deadlock just like the enriched path.
if (!existingPrIssue) {
try {
const recheck = await httpGet(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues?state=all&type=issues&q=${encodeURIComponent(`[PR #${pr.number}]`)}`,
{
Authorization: `token ${decryptedConfig.giteaConfig!.token}`,
}
);
const candidates = Array.isArray(recheck.data) ? recheck.data : [];
const hit = candidates.find((c: any) => {
const m = String(c.title || "").match(/\[PR #(\d+)\]/i);
return m && Number.parseInt(m[1], 10) === pr.number;
});
if (hit) {
existingPrIssue = hit;
existingPrIssuesByNumber.set(pr.number, hit);
console.log(
`[Pull Requests] Recovered orphan from prior failed attempt for PR #${pr.number} (basic fallback); switching to PATCH`
);
}
} catch (_recheckErr) {
// Best-effort; fall through to create.
}
}
if (existingPrIssue) {
await httpPatch(
`${config.giteaConfig!.url}/api/v1/repos/${giteaOwner}/${repoName}/issues/${existingPrIssue.number}`,
@@ -3272,17 +3408,49 @@ export async function mirrorGitRepoLabelsToGitea({
return;
}
// Get existing labels from Gitea
const giteaLabelsRes = await httpGet(
`${config.giteaConfig.url}/api/v1/repos/${giteaOwner}/${repoName}/labels`,
{
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
// Get existing labels from Gitea. Paginate because Gitea caps
// response size at `[api].MAX_RESPONSE_ITEMS` (default 50), so a
// single unpaginated GET only sees the first 50 labels. Once a repo
// crosses that threshold every label past it would be re-POSTed as a
// duplicate on every sync.
//
// Pagination signal: prefer Link header (RFC 5988) when present, but
// Gitea's /labels and /milestones endpoints do NOT emit Link headers
// — they only emit `X-Total-Count`. Without the fallback, a strict
// Link-only check terminated after page 1 and re-POSTed every label
// past index 50 on every sync. (Repro found during the milestone
// dedup fix: 9 unique milestones leaked past page 1 on a 74-row
// /milestones response.)
const existingLabels = new Set<string>();
const labelsPerPage = 50;
let labelsPage = 1;
let labelsFetched = 0;
while (true) {
const giteaLabelsRes = await httpGet(
`${config.giteaConfig.url}/api/v1/repos/${giteaOwner}/${repoName}/labels?page=${labelsPage}&limit=${labelsPerPage}`,
{
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
const pageLabels = Array.isArray(giteaLabelsRes.data) ? giteaLabelsRes.data : [];
if (!pageLabels.length) break;
for (const lbl of pageLabels) existingLabels.add(lbl.name);
labelsFetched += pageLabels.length;
const existingLabels = new Set(
giteaLabelsRes.data.map((label: any) => label.name)
);
const linkHeader = giteaLabelsRes.headers.get("link") || "";
if (/\brel="next"/.test(linkHeader)) {
labelsPage += 1;
continue;
}
// No Link header (or no rel=next). Fall back to X-Total-Count.
const totalStr = giteaLabelsRes.headers.get("x-total-count");
const total = totalStr ? Number.parseInt(totalStr, 10) : NaN;
if (Number.isFinite(total) && labelsFetched < total) {
labelsPage += 1;
continue;
}
break;
}
let mirroredCount = 0;
for (const label of labels) {
@@ -3299,6 +3467,9 @@ export async function mirrorGitRepoLabelsToGitea({
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
// Track locally so a duplicate in `labels` (shouldn't happen,
// but defensive) doesn't trigger a second POST in the same run.
existingLabels.add(label.name);
mirroredCount++;
} catch (error) {
console.error(
@@ -3372,17 +3543,54 @@ export async function mirrorGitRepoMilestonesToGitea({
return;
}
// Get existing milestones from Gitea
const giteaMilestonesRes = await httpGet(
`${config.giteaConfig.url}/api/v1/repos/${giteaOwner}/${repoName}/milestones`,
{
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
// Get existing milestones from Gitea. Two correctness requirements:
// 1. `state=all` — Gitea's /milestones endpoint defaults to OPEN
// only, so without this every CLOSED GitHub milestone is
// misclassified as missing and re-POSTed on every sync. This
// was the root cause of the 11k+ duplicate-closed-milestone
// blowup observed in production.
// 2. Pagination via Link header (RFC 5988) — Gitea caps response
// size at `[api].MAX_RESPONSE_ITEMS` (default 50), so any repo
// with more than ~50 milestones in a given state silently
// truncates without it. Same Gitea-side cap that bit the
// issues / PRs pre-fetch in commit b76073b.
// Pagination signal: prefer Link header (RFC 5988) when present, but
// Gitea's /milestones endpoint does NOT emit a Link header — it only
// emits `X-Total-Count`. A strict Link-only check terminates after
// page 1 and re-POSTs every milestone past index 50 on every sync.
// (Repro: post-fix deploy on Subnet-Calculator leaked 9 unique
// milestones past page 1 of a 74-row /milestones response.)
const existingMilestones = new Set<string>();
const milestonesPerPage = 50;
let milestonesPage = 1;
let milestonesFetched = 0;
while (true) {
const giteaMilestonesRes = await httpGet(
`${config.giteaConfig.url}/api/v1/repos/${giteaOwner}/${repoName}/milestones?state=all&page=${milestonesPage}&limit=${milestonesPerPage}`,
{
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
const pageMilestones = Array.isArray(giteaMilestonesRes.data)
? giteaMilestonesRes.data
: [];
if (!pageMilestones.length) break;
for (const ms of pageMilestones) existingMilestones.add(ms.title);
milestonesFetched += pageMilestones.length;
const existingMilestones = new Set(
giteaMilestonesRes.data.map((milestone: any) => milestone.title)
);
const linkHeader = giteaMilestonesRes.headers.get("link") || "";
if (/\brel="next"/.test(linkHeader)) {
milestonesPage += 1;
continue;
}
const totalStr = giteaMilestonesRes.headers.get("x-total-count");
const total = totalStr ? Number.parseInt(totalStr, 10) : NaN;
if (Number.isFinite(total) && milestonesFetched < total) {
milestonesPage += 1;
continue;
}
break;
}
let mirroredCount = 0;
for (const milestone of milestones) {
@@ -3400,6 +3608,9 @@ export async function mirrorGitRepoMilestonesToGitea({
Authorization: `token ${decryptedConfig.giteaConfig.token}`,
}
);
// Track locally so a duplicate within `milestones` (shouldn't
// happen, but defensive) doesn't trigger a second POST.
existingMilestones.add(milestone.title);
mirroredCount++;
} catch (error) {
console.error(
+17 -4
View File
@@ -216,9 +216,21 @@ export async function updateMirrorJobProgress({
}
/**
* Finds interrupted jobs that need to be resumed with enhanced criteria
* Finds interrupted jobs that need to be resumed with enhanced criteria.
*
* `logFound` defaults to false because this function is polled from
* passive callers (`hasJobsNeedingRecovery` from the health endpoint
* and middleware checks). Logging on every poll produces log spam at
* one-line-per-poll-per-stuck-job for as long as a job stays stuck.
*
* Callers that intend to act on the result (i.e. immediately resume
* the returned jobs) should pass `logFound: true` so the surfacing
* still happens in the recovery flow.
*/
export async function findInterruptedJobs() {
export async function findInterruptedJobs(
options: { logFound?: boolean } = {}
) {
const { logFound = false } = options;
try {
// Find jobs that are marked as in-progress but haven't been updated recently
const cutoffTime = new Date();
@@ -243,8 +255,9 @@ export async function findInterruptedJobs() {
)
);
// Log details about found jobs for debugging
if (interruptedJobs.length > 0) {
// Log details about found jobs for debugging — opt-in to avoid
// spamming the log when called from periodic passive checks.
if (logFound && interruptedJobs.length > 0) {
console.log(`Found ${interruptedJobs.length} interrupted jobs:`);
interruptedJobs.forEach(job => {
const lastCheckpoint = job.lastCheckpoint ? new Date(job.lastCheckpoint).toISOString() : 'never';
+28
View File
@@ -6,9 +6,22 @@ interface MetadataComponentsState {
milestones: boolean;
}
/**
* One-shot record of a deleted-branch backup we already took, so the
* force-push detector knows to skip the same (branch, giteaSha) pair
* next sync. Without this, deleted-on-GitHub branches that linger in
* the Gitea mirror trip the detector every cycle and create a new
* "Snapshot created" job row forever.
*/
export interface AcknowledgedDeletion {
branch: string;
giteaSha: string;
}
export interface RepositoryMetadataState {
components: MetadataComponentsState;
lastSyncedAt?: string;
acknowledgedDeletions: AcknowledgedDeletion[];
}
const defaultComponents: MetadataComponentsState = {
@@ -22,6 +35,7 @@ const defaultComponents: MetadataComponentsState = {
export function createDefaultMetadataState(): RepositoryMetadataState {
return {
components: { ...defaultComponents },
acknowledgedDeletions: [],
};
}
@@ -65,6 +79,20 @@ export function parseRepositoryMetadataState(
base.lastSyncedAt = parsed.lastMetadataSync;
}
if (Array.isArray(parsed.acknowledgedDeletions)) {
base.acknowledgedDeletions = parsed.acknowledgedDeletions.flatMap(
(entry: unknown): AcknowledgedDeletion[] => {
if (!entry || typeof entry !== "object") return [];
const branch = (entry as { branch?: unknown }).branch;
const giteaSha = (entry as { giteaSha?: unknown }).giteaSha;
if (typeof branch !== "string" || typeof giteaSha !== "string") {
return [];
}
return [{ branch, giteaSha }];
}
);
}
return base;
}
@@ -0,0 +1,128 @@
/**
* Regression test for the "interrupted jobs never resume after
* startup" orchestration bug.
*
* Symptom (before this fix):
* - Server starts cleanly. Middleware runs initial recovery pass,
* finds no interrupted jobs, sets `recoveryAttempted = true` and
* `recoveryInitialized = true`.
* - User triggers a sync at T=N (well after startup). The sync
* creates a `mirrorJobs` row with `inProgress=true`.
* - The sync fails mid-flight (deadlock retry, network blip,
* container restart of an upstream service, etc.) and never
* reaches the resume codepath, so the row stays
* `inProgress=true` with no checkpoint.
* - `findInterruptedJobs` (called periodically from the health
* endpoint via `hasJobsNeedingRecovery`) detects it and logs
* `Found 1 interrupted jobs:` on every poll.
* - But the resumer (`resumeInterruptedJob`) is only invoked from
* `initializeRecovery`, which is gated behind the
* once-per-process `!recoveryAttempted` check in
* `src/middleware.ts`. That check is false after startup, so the
* resumer NEVER fires again. The job is stuck forever.
*
* Root cause: the middleware gate was symmetric "skip recovery if
* we've ever attempted it" — but it should have been "always
* re-evaluate; only the recovery routine's own 5-minute throttle
* (`skipIfRecentAttempt` inside `initializeRecovery`) prevents
* thrashing".
*
* Secondary issue: `findInterruptedJobs` logged unconditionally on
* every call, even from passive checks like `hasJobsNeedingRecovery`,
* producing log spam at one line per poll per stuck job.
*
* This test asserts on the *structure* of the source rather than
* invoking the middleware, because exercising the middleware path
* requires a full Astro request pipeline with heavy mocks. See
* `gitea-mirror-failure-recovery.test.ts` and
* `gitea-issue-dedup-on-retry.test.ts` for the same convention.
*/
import { describe, test, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const MIDDLEWARE_SRC = readFileSync(
join(import.meta.dir, "../middleware.ts"),
"utf8"
);
const HELPERS_SRC = readFileSync(
join(import.meta.dir, "helpers.ts"),
"utf8"
);
const RECOVERY_SRC = readFileSync(
join(import.meta.dir, "recovery.ts"),
"utf8"
);
describe("orchestrator: resume interrupted jobs after startup", () => {
test("middleware no longer gates recovery behind once-per-process `recoveryAttempted`", () => {
// The old gate looked like:
// if (!recoveryInitialized && !recoveryAttempted) {
// recoveryAttempted = true;
// ...
// }
// Once both flags flipped on the first request, recovery never
// ran again — even if jobs got stuck mid-runtime.
expect(
/\brecoveryAttempted\b/.test(MIDDLEWARE_SRC),
"the `recoveryAttempted` once-per-process flag must be removed " +
"from middleware.ts so post-startup interruptions can recover"
).toBe(false);
});
test("middleware uses an in-flight latch (not a one-shot gate) for runtime safety", () => {
// The replacement uses `recoveryInFlight` as a per-request
// mutex — set true at the start, set false in `finally`. The
// actual throttle (5-minute "recent attempt") lives inside
// `initializeRecovery()` in recovery.ts, which is the right
// place for it.
expect(
/\brecoveryInFlight\b/.test(MIDDLEWARE_SRC),
"middleware should use `recoveryInFlight` as the in-flight latch"
).toBe(true);
expect(
/recoveryInFlight\s*=\s*false/.test(MIDDLEWARE_SRC) &&
/\bfinally\s*\{[\s\S]*?recoveryInFlight\s*=\s*false[\s\S]*?\}/.test(
MIDDLEWARE_SRC
),
"the in-flight latch must be released in a `finally` block " +
"so an exception during recovery doesn't permanently jam the latch"
).toBe(true);
});
test("findInterruptedJobs logging is opt-in (default off) to stop poll spam", () => {
// Active recovery callers (initializeRecovery) opt in by passing
// { logFound: true }; passive checks (hasJobsNeedingRecovery,
// health endpoint, etc.) default to silent.
expect(
/export async function findInterruptedJobs\(\s*options[^)]*\)/.test(
HELPERS_SRC
),
"findInterruptedJobs should accept an options object"
).toBe(true);
expect(
/logFound\s*=\s*false/.test(HELPERS_SRC),
"the `logFound` option should default to false " +
"so periodic passive checks (e.g. hasJobsNeedingRecovery) " +
"don't spam the log on every poll"
).toBe(true);
expect(
/if\s*\(\s*logFound\s*&&\s*interruptedJobs\.length\s*>\s*0\s*\)/.test(
HELPERS_SRC
),
"the `Found N interrupted jobs` log must be gated by `logFound`"
).toBe(true);
});
test("active recovery path opts in to per-job logging", () => {
// Without this, the actual recovery cycle would also be silent
// — operators need to see which jobs are being resumed.
expect(
/findInterruptedJobs\(\s*\{\s*logFound:\s*true\s*\}\s*\)/.test(
RECOVERY_SRC
),
"initializeRecovery() must pass { logFound: true } to findInterruptedJobs " +
"so the active recovery cycle still logs which jobs it's working on"
).toBe(true);
});
});
+3 -2
View File
@@ -121,8 +121,9 @@ export async function initializeRecovery(options: {
// Clean up stale jobs first
await cleanupStaleJobs();
// Find interrupted jobs
const interruptedJobs = await findInterruptedJobs();
// Find interrupted jobs (with per-job logging — this is the
// active recovery path that will immediately try to resume them)
const interruptedJobs = await findInterruptedJobs({ logFound: true });
if (interruptedJobs.length === 0) {
console.log('No interrupted jobs found.');
+185
View File
@@ -316,4 +316,189 @@ describe("detectForcePush", () => {
expect(result.skipped).toBe(true);
expect(result.skipReason).toContain("Failed to fetch GitHub branches");
});
// --- acknowledgedDeletions: suppress already-handled deleted branches ---
//
// Production reproduction (Simple-WP-Helpdesk, May 2026): a branch
// deleted on GitHub remained in the Gitea mirror because gitea-mirror
// is one-way. Every 4h sync re-detected it as "deleted" and inserted
// a fresh "Snapshot created" job row — 7 zombies accumulated in 24h.
// Fix: caller threads in the list of (branch, giteaSha) pairs already
// backed up; detector suppresses matching entries.
it("suppresses a deleted branch when acknowledged at the same giteaSha", async () => {
const deps = makeDeps({
giteaBranches: [
{ name: "main", sha: "aaa" },
{ name: "fix/abandoned", sha: "bbb" },
],
githubBranches: [{ name: "main", sha: "aaa" }],
});
const result = await detectForcePush({
...baseArgs,
octokit: dummyOctokit,
acknowledgedDeletions: [{ branch: "fix/abandoned", giteaSha: "bbb" }],
_deps: deps,
});
expect(result.detected).toBe(false);
expect(result.affectedBranches).toHaveLength(0);
});
it("re-flags a previously-acknowledged branch if its giteaSha changed", async () => {
// Edge case: a deleted branch was restored (Gitea picked up the
// new history), then re-deleted. Same name but different giteaSha
// means the acknowledged entry doesn't match — back up the new
// state.
const deps = makeDeps({
giteaBranches: [
{ name: "main", sha: "aaa" },
{ name: "fix/abandoned", sha: "ccc" },
],
githubBranches: [{ name: "main", sha: "aaa" }],
});
const result = await detectForcePush({
...baseArgs,
octokit: dummyOctokit,
acknowledgedDeletions: [{ branch: "fix/abandoned", giteaSha: "bbb" }], // stale SHA
_deps: deps,
});
expect(result.detected).toBe(true);
expect(result.affectedBranches).toHaveLength(1);
expect(result.affectedBranches[0]).toMatchObject({
name: "fix/abandoned",
reason: "deleted",
giteaSha: "ccc",
});
});
it("suppresses only the acknowledged deletion when multiple deletions exist", async () => {
const deps = makeDeps({
giteaBranches: [
{ name: "main", sha: "aaa" },
{ name: "fix/old", sha: "bbb" },
{ name: "fix/new", sha: "ccc" },
],
githubBranches: [{ name: "main", sha: "aaa" }],
});
const result = await detectForcePush({
...baseArgs,
octokit: dummyOctokit,
acknowledgedDeletions: [{ branch: "fix/old", giteaSha: "bbb" }],
_deps: deps,
});
expect(result.detected).toBe(true);
expect(result.affectedBranches).toHaveLength(1);
expect(result.affectedBranches[0]?.name).toBe("fix/new");
});
it("treats undefined acknowledgedDeletions as empty (back-compat with callers that don't pass it)", async () => {
const deps = makeDeps({
giteaBranches: [
{ name: "main", sha: "aaa" },
{ name: "fix/abandoned", sha: "bbb" },
],
githubBranches: [{ name: "main", sha: "aaa" }],
});
const result = await detectForcePush({
...baseArgs,
octokit: dummyOctokit,
// acknowledgedDeletions omitted
_deps: deps,
});
expect(result.detected).toBe(true);
expect(result.affectedBranches[0]?.reason).toBe("deleted");
});
it("does not suppress diverged branches via the acknowledgedDeletions list", async () => {
// The suppression list is specifically for `reason: "deleted"`.
// A divergence at the same name + matching old giteaSha (an
// impossible-in-practice combination, but be explicit about the
// boundary) must still report.
const deps = makeDeps({
giteaBranches: [{ name: "main", sha: "aaa" }],
githubBranches: [{ name: "main", sha: "rewritten" }],
ancestryResult: false,
});
const result = await detectForcePush({
...baseArgs,
octokit: dummyOctokit,
acknowledgedDeletions: [{ branch: "main", giteaSha: "aaa" }],
_deps: deps,
});
expect(result.detected).toBe(true);
expect(result.affectedBranches[0]?.reason).toBe("diverged");
});
});
// --- metadata-state round-trip for the new acknowledgedDeletions field ---
describe("metadata-state acknowledgedDeletions persistence", () => {
it("parse → mutate → serialize → parse round-trips entries cleanly", async () => {
const {
parseRepositoryMetadataState,
serializeRepositoryMetadataState,
createDefaultMetadataState,
} = await import("../metadata-state");
const state = createDefaultMetadataState();
state.acknowledgedDeletions.push(
{ branch: "fix/abandoned", giteaSha: "bbb" },
{ branch: "fix/other", giteaSha: "ccc" },
);
const reparsed = parseRepositoryMetadataState(
serializeRepositoryMetadataState(state),
);
expect(reparsed.acknowledgedDeletions).toEqual([
{ branch: "fix/abandoned", giteaSha: "bbb" },
{ branch: "fix/other", giteaSha: "ccc" },
]);
});
it("defaults acknowledgedDeletions to [] for legacy metadata blobs", async () => {
const { parseRepositoryMetadataState } = await import("../metadata-state");
// Metadata that predates this field — no acknowledgedDeletions key
const legacy = JSON.stringify({
components: {
releases: true,
issues: false,
pullRequests: false,
labels: false,
milestones: false,
},
lastSyncedAt: "2026-05-01T00:00:00Z",
});
expect(parseRepositoryMetadataState(legacy).acknowledgedDeletions).toEqual([]);
});
it("drops malformed acknowledged entries without throwing", async () => {
const { parseRepositoryMetadataState } = await import("../metadata-state");
const malformed = JSON.stringify({
components: {},
acknowledgedDeletions: [
{ branch: "good", giteaSha: "abc" },
{ branch: 42, giteaSha: "abc" }, // bad type
null,
{ branch: "missing-sha" },
],
});
expect(parseRepositoryMetadataState(malformed).acknowledgedDeletions).toEqual([
{ branch: "good", giteaSha: "abc" },
]);
});
});
+27 -1
View File
@@ -11,6 +11,7 @@
import type { Octokit } from "@octokit/rest";
import { httpGet, HttpError } from "@/lib/http-client";
import type { AcknowledgedDeletion } from "@/lib/metadata-state";
// ---- Types ----
@@ -172,6 +173,7 @@ export async function detectForcePush({
octokit,
githubOwner,
githubRepo,
acknowledgedDeletions,
_deps,
}: {
giteaUrl: string;
@@ -181,6 +183,18 @@ export async function detectForcePush({
octokit: Octokit;
githubOwner: string;
githubRepo: string;
/**
* Deleted-branch backups we already took. A Gitea branch missing
* from GitHub is suppressed from `affectedBranches` when its current
* giteaSha matches an entry here. Without this, deleted branches
* trip detection every sync because gitea-mirror is one-way:
* deletions never propagate to the Gitea mirror, so the "branch in
* Gitea, gone from GitHub" condition holds forever and we'd take a
* fresh snapshot on every cycle.
*
* Stored on the repository row via RepositoryMetadataState.
*/
acknowledgedDeletions?: readonly AcknowledgedDeletion[];
/** @internal — test-only dependency injection */
_deps?: {
fetchGiteaBranches: typeof fetchGiteaBranches;
@@ -189,6 +203,9 @@ export async function detectForcePush({
};
}): Promise<ForcePushDetectionResult> {
const deps = _deps ?? { fetchGiteaBranches, fetchGitHubBranches, checkAncestry };
const acknowledged = new Set(
(acknowledgedDeletions ?? []).map((entry) => `${entry.branch}@${entry.giteaSha}`),
);
// 1. Fetch Gitea branches
let giteaBranches: BranchInfo[];
@@ -237,7 +254,16 @@ export async function detectForcePush({
const githubSha = githubBranchMap.get(giteaBranch.name);
if (githubSha === undefined) {
// Branch was deleted on GitHub
// Branch was deleted on GitHub. Suppress if we already took a
// snapshot at this exact giteaSha — the deletion is permanent
// on the GitHub side but the branch lingers in the Gitea
// mirror, so without this check the detector trips every sync.
// If the giteaSha later changes (branch restored, then deleted
// again with new history), the entry won't match and we'll
// back up the new state.
if (acknowledged.has(`${giteaBranch.name}@${giteaBranch.sha}`)) {
continue;
}
affected.push({
name: giteaBranch.name,
reason: "deleted",
+69 -36
View File
@@ -6,7 +6,8 @@ import { startRepositoryCleanupService, stopRepositoryCleanupService } from './l
import { initializeShutdownManager, registerShutdownCallback } from './lib/shutdown-manager';
import { setupSignalHandlers } from './lib/signal-handlers';
import { auth } from './lib/auth';
import { isHeaderAuthEnabled, authenticateWithHeaders } from './lib/auth-header';
import { isHeaderAuthEnabled } from './lib/auth-header';
import { mintSessionFromHeaders } from './lib/auth-header-bridge';
import { initializeConfigFromEnv } from './lib/env-config-loader';
import { db, users } from './lib/db';
import { getBasePath } from './lib/base-path';
@@ -17,9 +18,16 @@ function prefixAstroInternalAssetPaths(html: string, basePath: string): string {
return html.replace(ASTRO_INTERNAL_ASSET_PATH_PATTERN, `$1${basePath}/$2`);
}
// Flag to track if recovery has been initialized
// Flag to track whether the *startup* recovery pass has run. This
// only gates the post-startup chain (cleanup service, scheduler,
// etc.) and the "startup script may not have run" log line — it does
// NOT gate subsequent recovery attempts, see below.
let recoveryInitialized = false;
let recoveryAttempted = false;
// Throttle for runtime recovery retries (separate from the
// initializeRecovery() 5-minute throttle inside recovery.ts, which is
// keyed on `lastRecoveryAttempt`). This prevents one middleware
// invocation from triggering recovery while another is in flight.
let recoveryInFlight = false;
let cleanupServiceStarted = false;
let schedulerServiceStarted = false;
let repositoryCleanupServiceStarted = false;
@@ -30,6 +38,13 @@ let envConfigCheckCount = 0; // Track attempts to avoid excessive checking
export const onRequest = defineMiddleware(async (context, next) => {
const basePath = getBasePath();
// Set-Cookie headers we mint during the header-auth bridge below.
// Forwarded onto the outbound response after `next()` so the browser
// persists the Better Auth session cookie. Until that happens the
// SPA's /api/auth/get-session call returns null and bounces to
// /login — see the bridge block for the full rationale.
let pendingSetCookies: string[] = [];
// First, try Better Auth session (cookie-based)
try {
const session = await auth.api.getSession({
@@ -39,36 +54,26 @@ export const onRequest = defineMiddleware(async (context, next) => {
if (session) {
context.locals.user = session.user;
context.locals.session = session.session;
} else {
// No cookie session, check for header authentication
if (isHeaderAuthEnabled()) {
const headerUser = await authenticateWithHeaders(context.request.headers);
if (headerUser) {
// Create a session-like object for header auth
context.locals.user = {
id: headerUser.id,
email: headerUser.email,
emailVerified: headerUser.emailVerified,
name: headerUser.name || headerUser.username,
username: headerUser.username,
createdAt: headerUser.createdAt,
updatedAt: headerUser.updatedAt,
};
context.locals.session = {
id: `header-${headerUser.id}`,
userId: headerUser.id,
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 1 day
ipAddress: context.request.headers.get('x-forwarded-for') || context.clientAddress,
userAgent: context.request.headers.get('user-agent'),
};
} else {
context.locals.user = null;
context.locals.session = null;
}
} else if (isHeaderAuthEnabled()) {
// No cookie session, but header auth is on. Call the
// header-auth plugin endpoint to mint a real Better Auth
// session from the trusted upstream headers, then forward the
// Set-Cookie onto the outbound response so the SPA's next
// /api/auth/get-session call carries the cookie. Without this
// bridge the React app sees null on mount and redirects to
// /login even though server-rendered code paths know the user.
const bridge = await mintSessionFromHeaders(context.request);
if (bridge) {
context.locals.user = bridge.user;
context.locals.session = bridge.session;
pendingSetCookies = bridge.setCookies;
} else {
context.locals.user = null;
context.locals.session = null;
}
} else {
context.locals.user = null;
context.locals.session = null;
}
} catch (error) {
// If there's an error getting the session, set to null
@@ -118,17 +123,30 @@ export const onRequest = defineMiddleware(async (context, next) => {
}
}
// Initialize recovery system only once when the server starts
// This is a fallback in case the startup script didn't run
if (!recoveryInitialized && !recoveryAttempted) {
recoveryAttempted = true;
// Run recovery if jobs need it.
//
// The previous implementation used a once-per-process gate, so
// any mid-runtime interruption (a sync that started after boot,
// crashed mid-flight, and never got back to the resume path)
// would sit at `in_progress=true` forever — the periodic detector
// kept finding it, but the resumer never re-fired. This block
// now re-evaluates on every request, gated by `recoveryInFlight`
// (per-process) plus the 5-minute throttle inside
// `initializeRecovery()` (which prevents thrashing if a resume
// cycle keeps failing).
if (!recoveryInFlight) {
recoveryInFlight = true;
try {
// Check if recovery is actually needed before attempting
const needsRecovery = await hasJobsNeedingRecovery();
if (needsRecovery) {
console.log('⚠️ Middleware detected jobs needing recovery (startup script may not have run)');
if (!recoveryInitialized) {
console.log('⚠️ Middleware detected jobs needing recovery (startup script may not have run)');
} else {
console.log('⚠️ Middleware detected jobs needing recovery mid-run (sync interrupted after startup)');
}
console.log('Attempting recovery from middleware...');
// Run recovery with a shorter timeout since this is during request handling
@@ -148,7 +166,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
} else {
console.log('⚠️ Middleware recovery completed with some issues');
}
} else {
} else if (!recoveryInitialized) {
// Only log this on the first request; otherwise we'd spam
// it on every request.
console.log('✅ No recovery needed (startup script likely handled it)');
}
@@ -161,7 +181,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
const status = getRecoveryStatus();
console.log('Recovery status:', status);
recoveryInitialized = true; // Mark as attempted to avoid retries
recoveryInitialized = true;
} finally {
recoveryInFlight = false;
}
}
@@ -228,6 +250,17 @@ export const onRequest = defineMiddleware(async (context, next) => {
// Continue with the request
const response = await next();
// Forward any Set-Cookie headers minted by the header-auth bridge
// onto the outbound response. Done before the early returns below so
// every return path (basePath rewrite, non-HTML responses, etc.)
// carries the cookie. The body-rewrite branch further down clones
// `response.headers`, so anything appended here survives the clone.
if (pendingSetCookies.length > 0) {
for (const cookie of pendingSetCookies) {
response.headers.append("set-cookie", cookie);
}
}
if (basePath === "/") {
return response;
}