AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
perf(tcr): build images inside Tencent Cloud
tianma-if87e0c1e6d4b7
diff --git a/.cnb.yml b/.cnb.ymlnew file mode 100644index 00000000..2d863835--- /dev/null+++ b/.cnb.yml@@ -0,0 +1,25 @@+main:+ push:+ - name: build-tcr-main+ runner:+ cpus: 2+ services:+ - docker+ imports:+ - https://cnb.cool/tianma-if/edgeever-secrets/-/blob/main/tcr.yml+ stages:+ - name: Build and publish main image inside Tencent Cloud+ script: bash scripts/publish-tcr-image.sh++"v*":+ tag_push:+ - name: build-tcr-release+ runner:+ cpus: 2+ services:+ - docker+ imports:+ - https://cnb.cool/tianma-if/edgeever-secrets/-/blob/main/tcr.yml+ stages:+ - name: Build and publish release image inside Tencent Cloud+ script: bash scripts/publish-tcr-image.shdiff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.ymlindex c322cc83..77156d19 100644--- a/.github/workflows/docker-image.yml+++ b/.github/workflows/docker-image.yml@@ -19,6 +19,10 @@ on:- "tailwind.config.ts"- "tsconfig.json"- ".github/workflows/docker-image.yml"+ - ".github/workflows/docker-tcr-mirror.yml"+ - ".cnb.yml"+ - "scripts/publish-tcr-image.sh"+ - "scripts/prune-tcr-sha-tags.mjs"push:branches:- main@@ -39,6 +43,10 @@ on:- "tailwind.config.ts"- "tsconfig.json"- ".github/workflows/docker-image.yml"+ - ".github/workflows/docker-tcr-mirror.yml"+ - ".cnb.yml"+ - "scripts/publish-tcr-image.sh"+ - "scripts/prune-tcr-sha-tags.mjs"workflow_dispatch:inputs:release_tag:diff --git a/.github/workflows/docker-tcr-mirror.yml b/.github/workflows/docker-tcr-mirror.ymlindex 3e59399a..b818db78 100644--- a/.github/workflows/docker-tcr-mirror.yml+++ b/.github/workflows/docker-tcr-mirror.yml@@ -1,4 +1,4 @@-name: Mirror Docker image to Tencent TCR+name: Build Tencent TCR image through CNBon:workflow_run:@@ -11,31 +11,24 @@ on:- publishedworkflow_dispatch:inputs:- source_tag:- description: "Immutable GHCR tag to mirror"+ source_ref:+ description: "Git ref or SHA already verified by the GHCR workflow"required: truetype: string- destination_tags:- description: "Comma-separated TCR tags"+ destination_ref:+ description: "CNB destination: main or a formal vX.Y.Z tag"required: truetype: stringpermissions:contents: read- packages: read--env:- GHCR_IMAGE_NAME: ghcr.io/tianma-if/edgeever- TCR_IMAGE_NAME: ccr.ccs.tencentyun.com/edgeever/edgeeverconcurrency:- group: docker-tcr-mirror- # A release/manual promotion takes priority over an older main mirror. Main- # mirrors queue behind an active release instead of cancelling it.- cancel-in-progress: ${{ github.event_name == 'release' || github.event_name == 'workflow_dispatch' }}+ group: docker-tcr-cnb-source-sync+ cancel-in-progress: falsejobs:- mirror:+ sync-source:if: >-github.repository == 'tianma-if/edgeever' &&(@@ -47,123 +40,64 @@ jobs:github.event.workflow_run.event == 'push'))- name: Mirror public image without blocking releases+ name: Trigger asynchronous Tencent-side image buildruns-on: ubuntu-latest- timeout-minutes: 60+ timeout-minutes: 5steps:- - name: Resolve immutable source and destination tags- id: image+ - name: Resolve verified source and CNB destination+ id: sourceenv:EVENT_NAME: ${{ github.event_name }}RELEASE_TAG: ${{ github.event.release.tag_name }}- SOURCE_SHA: ${{ github.event.workflow_run.head_sha }}- INPUT_SOURCE_TAG: ${{ inputs.source_tag }}- INPUT_DESTINATION_TAGS: ${{ inputs.destination_tags }}+ WORKFLOW_SHA: ${{ github.event.workflow_run.head_sha }}+ INPUT_SOURCE_REF: ${{ inputs.source_ref }}+ INPUT_DESTINATION_REF: ${{ inputs.destination_ref }}run: |if [[ "${EVENT_NAME}" == "release" ]]; then- source_tag="${RELEASE_TAG}"- destination_tags="${RELEASE_TAG},${RELEASE_TAG#v},latest"+ source_ref="${RELEASE_TAG}"+ destination_ref="${RELEASE_TAG}"elif [[ "${EVENT_NAME}" == "workflow_run" ]]; then- source_tag="sha-${SOURCE_SHA:0:12}"- destination_tags="${source_tag},main"+ source_ref="${WORKFLOW_SHA}"+ destination_ref="main"else- source_tag="${INPUT_SOURCE_TAG}"- destination_tags="${INPUT_DESTINATION_TAGS}"+ source_ref="${INPUT_SOURCE_REF}"+ destination_ref="${INPUT_DESTINATION_REF}"fi- if [[ ! "${source_tag}" =~ ^[A-Za-z0-9._-]+$ ]]; then- echo "Invalid source tag" >&2+ if [[ "${destination_ref}" != "main" ]] && [[ ! "${destination_ref}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "destination_ref must be main or vX.Y.Z" >&2exit 1fi- IFS=',' read -ra tags <<< "${destination_tags}"- primary_tag="${tags[0]}"- for image_tag in "${tags[@]}"; do- if [[ ! "${image_tag}" =~ ^[A-Za-z0-9._-]+$ ]]; then- echo "Invalid destination tag: ${image_tag}" >&2- exit 1- fi- done{- echo "source_tag=${source_tag}"- echo "primary_tag=${primary_tag}"- echo "destination_tags=${destination_tags}"+ echo "source_ref=${source_ref}"+ echo "destination_ref=${destination_ref}"} >> "${GITHUB_OUTPUT}"- - name: Sign in to GitHub Container Registry- uses: docker/login-action@v3- with:- registry: ghcr.io- username: ${{ github.actor }}- password: ${{ secrets.GITHUB_TOKEN }}-- - name: Sign in to Tencent Cloud Container Registry- uses: docker/login-action@v3+ - name: Check out the GHCR-verified source+ uses: actions/checkout@v5with:- registry: ccr.ccs.tencentyun.com- username: ${{ secrets.TENCENT_TCR_USERNAME }}- password: ${{ secrets.TENCENT_TCR_PASSWORD }}-- - name: Install registry copy tool- run: |- sudo apt-get update- sudo apt-get install --yes skopeo+ ref: ${{ steps.source.outputs.source_ref }}+ fetch-depth: 0- - name: Mirror immutable image once+ - name: Verify formal source metadata+ if: steps.source.outputs.destination_ref != 'main'env:- SOURCE_TAG: ${{ steps.image.outputs.source_tag }}- PRIMARY_TAG: ${{ steps.image.outputs.primary_tag }}+ RELEASE_TAG: ${{ steps.source.outputs.destination_ref }}run: |- for attempt in 1 2 3; do- if timeout --signal=TERM --kill-after=1m 15m skopeo copy \- --all \- --preserve-digests \- --authfile "${HOME}/.docker/config.json" \- "docker://${GHCR_IMAGE_NAME}:${SOURCE_TAG}" \- "docker://${TCR_IMAGE_NAME}:${PRIMARY_TAG}"; then- break- else- copy_status=$?- fi- if [[ "${attempt}" -eq 3 ]]; then- echo "Failed to mirror ${PRIMARY_TAG} after ${attempt} attempts (status ${copy_status})" >&2- exit 1- fi- echo "Mirror attempt ${attempt} failed for ${PRIMARY_TAG} (status ${copy_status}); retrying" >&2- sleep "$((attempt * 15))"- done+ test "$(jq -r '.version' package.json)" = "${RELEASE_TAG#v}"+ test "$(git rev-parse HEAD)" = "$(git rev-list -n 1 "${RELEASE_TAG}")"- - name: Promote TCR tags without transferring layers+ - name: Push the same Git commit to CNBenv:- PRIMARY_TAG: ${{ steps.image.outputs.primary_tag }}- DESTINATION_TAGS: ${{ steps.image.outputs.destination_tags }}+ CNB_PUSH_TOKEN: ${{ secrets.CNB_TCR_BUILD_PUSH_TOKEN }}+ DESTINATION_REF: ${{ steps.source.outputs.destination_ref }}run: |- primary_inspect="$(docker buildx imagetools inspect "${TCR_IMAGE_NAME}:${PRIMARY_TAG}")"- primary_digest="$(sed -n 's/^Digest:[[:space:]]*//p' <<<"${primary_inspect}" | head -n 1)"- test -n "${primary_digest}"- IFS=',' read -ra tags <<< "${DESTINATION_TAGS}"- for image_tag in "${tags[@]}"; do- if [[ "${image_tag}" == "${PRIMARY_TAG}" ]]; then- continue- fi- docker buildx imagetools create \- --tag "${TCR_IMAGE_NAME}:${image_tag}" \- "${TCR_IMAGE_NAME}@${primary_digest}"- done-- - name: Verify mirrored anonymous image access- env:- SOURCE_TAG: ${{ steps.image.outputs.source_tag }}- DESTINATION_TAGS: ${{ steps.image.outputs.destination_tags }}- run: |- docker logout ghcr.io- docker logout ccr.ccs.tencentyun.com- source_inspect="$(docker buildx imagetools inspect "${GHCR_IMAGE_NAME}:${SOURCE_TAG}")"- source_digest="$(sed -n 's/^Digest:[[:space:]]*//p' <<<"${source_inspect}" | head -n 1)"- test -n "${source_digest}"- IFS=',' read -ra tags <<< "${DESTINATION_TAGS}"- for image_tag in "${tags[@]}"; do- mirror_inspect="$(docker buildx imagetools inspect "${TCR_IMAGE_NAME}:${image_tag}")"- mirror_digest="$(sed -n 's/^Digest:[[:space:]]*//p' <<<"${mirror_inspect}" | head -n 1)"- test "${source_digest}" = "${mirror_digest}"- docker buildx imagetools inspect --raw "${TCR_IMAGE_NAME}:${image_tag}" |- jq -e '([.manifests[].platform.architecture] | index("amd64") != null) and ([.manifests[].platform.architecture] | index("arm64") != null)'- done+ test -n "${CNB_PUSH_TOKEN}"+ auth="$(printf 'cnb:%s' "${CNB_PUSH_TOKEN}" | base64 -w 0)"+ if [[ "${DESTINATION_REF}" == "main" ]]; then+ destination="refs/heads/main"+ else+ destination="refs/tags/${DESTINATION_REF}"+ fi+ git -c http.extraHeader="Authorization: Basic ${auth}" push \+ https://cnb.cool/tianma-if/edgeever \+ "HEAD:${destination}"diff --git a/docs/deploy-docker.md b/docs/deploy-docker.mdindex a2bfc211..da255fd5 100644--- a/docs/deploy-docker.md+++ b/docs/deploy-docker.md@@ -75,10 +75,10 @@ docker compose up -d```The public TCR image requires no `docker login` and supports `linux/amd64` and-`linux/arm64`. Formal releases publish the same version tags and `latest`-multi-platform image to GHCR and TCR; the release audit rejects missing, stale,-or mismatched mirror content. Pin `EDGE_EVER_VERSION` to a release tag in-production.+`linux/arm64`. Formal releases publish the same version tags and `latest` to+GHCR and TCR. TCR is independently built from the same verified Git commit+inside Tencent Cloud, so its registry digest may differ from GHCR. Pin+`EDGE_EVER_VERSION` to a release tag in production.Compose creates one named volume. Everything that must survive a containerreplacement is under `/data`:@@ -101,15 +101,15 @@ data permissions automatically.Common environment variables:-| Variable | Default | Purpose |-| --- | --- | --- |-| `EDGE_EVER_AUTH_USERNAME` | `admin` | Initial administrator username |-| `EDGE_EVER_AUTH_PASSWORD` | none | Initial password; required for a new database |-| `EDGE_EVER_AUTH_PASSWORD_HASH` | none | PBKDF2 hash alternative to the plaintext bootstrap password |-| `EDGE_EVER_SESSION_TTL_DAYS` | `400` | Login session lifetime |-| `EDGE_EVER_IDLE_TIMEOUT_SECONDS` | `120` | Bun streaming idle timeout, from 10 to 255 seconds |-| `EDGE_EVER_STORAGE_ENCRYPTION_KEY` | none | Encrypts saved external object-storage credentials |-| `EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY` | derived | Optional independent AI credential encryption key |+| Variable | Default | Purpose |+| -------------------------------------- | ------- | ----------------------------------------------------------- |+| `EDGE_EVER_AUTH_USERNAME` | `admin` | Initial administrator username |+| `EDGE_EVER_AUTH_PASSWORD` | none | Initial password; required for a new database |+| `EDGE_EVER_AUTH_PASSWORD_HASH` | none | PBKDF2 hash alternative to the plaintext bootstrap password |+| `EDGE_EVER_SESSION_TTL_DAYS` | `400` | Login session lifetime |+| `EDGE_EVER_IDLE_TIMEOUT_SECONDS` | `120` | Bun streaming idle timeout, from 10 to 255 seconds |+| `EDGE_EVER_STORAGE_ENCRYPTION_KEY` | none | Encrypts saved external object-storage credentials |+| `EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY` | derived | Optional independent AI credential encryption key |For secrets, append `_FILE` to a supported variable and point it at a Dockersecret, for example `EDGE_EVER_AUTH_PASSWORD_FILE=/run/secrets/auth_password`.diff --git a/docs/deploy-docker.zh-CN.md b/docs/deploy-docker.zh-CN.mdindex c3fc189c..d5ae3035 100644--- a/docs/deploy-docker.zh-CN.md+++ b/docs/deploy-docker.zh-CN.md@@ -64,9 +64,9 @@ docker compose up -d```腾讯云公共镜像无需执行 `docker login`,支持 `linux/amd64` 与 `linux/arm64`。-正式发布会向 GHCR 和 TCR 同时写入相同的版本标签与 `latest` 多平台镜像;发布-审计会拒绝缺失、滞后或内容不一致的镜像。生产环境应通过-`EDGE_EVER_VERSION` 固定正式版本标签。+正式发布会向 GHCR 和 TCR 写入相同的版本标签与 `latest`。TCR 在腾讯云侧根据+同一个已验证 Git 提交独立构建,因此 Registry Digest 可以与 GHCR 不同。生产+环境应通过 `EDGE_EVER_VERSION` 固定正式版本标签。Compose 会创建一个命名卷。所有需要在容器替换后保留的数据都位于 `/data`:@@ -85,15 +85,15 @@ Compose 会创建一个命名卷。所有需要在容器替换后保留的数据常用环境变量:-| 变量 | 默认值 | 用途 |-| --- | --- | --- |-| `EDGE_EVER_AUTH_USERNAME` | `admin` | 初始管理员用户名 |-| `EDGE_EVER_AUTH_PASSWORD` | 无 | 初始密码;新数据库必须提供 |-| `EDGE_EVER_AUTH_PASSWORD_HASH` | 无 | 可替代明文引导密码的 PBKDF2 hash |-| `EDGE_EVER_SESSION_TTL_DAYS` | `400` | 登录会话有效期 |-| `EDGE_EVER_IDLE_TIMEOUT_SECONDS` | `120` | Bun 流式响应空闲超时,可设为 10 到 255 秒 |-| `EDGE_EVER_STORAGE_ENCRYPTION_KEY` | 无 | 加密保存的外部对象存储凭据 |-| `EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY` | 自动派生 | 可选的独立 AI 凭据加密密钥 |+| 变量 | 默认值 | 用途 |+| -------------------------------------- | -------- | ----------------------------------------- |+| `EDGE_EVER_AUTH_USERNAME` | `admin` | 初始管理员用户名 |+| `EDGE_EVER_AUTH_PASSWORD` | 无 | 初始密码;新数据库必须提供 |+| `EDGE_EVER_AUTH_PASSWORD_HASH` | 无 | 可替代明文引导密码的 PBKDF2 hash |+| `EDGE_EVER_SESSION_TTL_DAYS` | `400` | 登录会话有效期 |+| `EDGE_EVER_IDLE_TIMEOUT_SECONDS` | `120` | Bun 流式响应空闲超时,可设为 10 到 255 秒 |+| `EDGE_EVER_STORAGE_ENCRYPTION_KEY` | 无 | 加密保存的外部对象存储凭据 |+| `EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY` | 自动派生 | 可选的独立 AI 凭据加密密钥 |Secret 可在受支持的变量名后追加 `_FILE`,并指向 Docker secret,例如`EDGE_EVER_AUTH_PASSWORD_FILE=/run/secrets/auth_password`。密码/hash、存储加密diff --git a/docs/release.md b/docs/release.mdindex 3faebccb..616e6c32 100644--- a/docs/release.md+++ b/docs/release.md@@ -58,9 +58,10 @@ previous installation check is actually needed.the desktop application by default; installation remains available as anexplicit option.Demo deployment continues independently after its Actions URL is printed.-- A separate workflow mirrors and audits the public Tencent TCR image- asynchronously after the formal Release is published. Its duration or failure- does not block the GitHub Release or return a published version to Draft.+- A separate workflow sends the same verified Git commit to CNB. CNB builds and+ audits the public Tencent TCR image inside Tencent Cloud after the formal+ Release is published. Its duration or failure does not block the GitHub+ Release or return a published version to Draft.- This command does not authorize or run mobile store delivery itself. AfterDraft native assets are prepared, publication is blocked unless the AndroidAPK uses the Google Play app-signing certificate. If that gate fails, the@@ -71,18 +72,21 @@ previous installation check is actually needed.## Registry Credentials-The official repository must define `TENCENT_TCR_USERNAME` and-`TENCENT_TCR_PASSWORD` Actions secrets. For the TCR Personal Edition registry,-the username is the Tencent Cloud account ID and the password is the fixed-registry password initialized in the TCR console. GHCR is the blocking Release-gate. TCR receives the same tags asynchronously after publication and performs-its own anonymous-access, digest, and architecture checks.+The official GitHub repository must define the `CNB_TCR_BUILD_PUSH_TOKEN`+Actions secret with write access only to the CNB source mirror. The private CNB+key repository provides `TCR_USERNAME` and `TCR_PASSWORD` to the trusted+`push` and `tag_push` pipelines. For TCR Personal Edition, the username is the+Tencent Cloud account ID and the password is the fixed registry password+initialized in the TCR console. GHCR is the blocking Release gate. CNB builds+TCR from the same Git commit, publishes the same public tags asynchronously,+and independently verifies anonymous access and both supported architectures.+Independent builds are not required to have the same registry digest.## Failure and Resume- Validation, Draft asset, or GHCR image failures leave the Release unpublished.-- An asynchronous TCR mirror failure leaves the formal Release intact and is- repaired or rerun in its independent Actions workflow.+- An asynchronous CNB/TCR build failure leaves the formal Release intact and is+ repaired or rerun independently.- Rerunning the same command resumes a matching Draft created by an interruptedrun instead of creating another Issue, commit, or Release.- A failed post-publication native or GHCR audit attempts to return the Release todiff --git a/docs/release.zh-CN.md b/docs/release.zh-CN.mdindex a7243b35..87a2493b 100644--- a/docs/release.zh-CN.md+++ b/docs/release.zh-CN.md@@ -49,8 +49,9 @@ bun run release -- \GHCR 多架构 Docker 镜像、正式发布、关闭 Issue,默认不安装桌面端应用;安装能力作为显式选项保留。输出 Actions 链接后,Demo 部署会独立继续执行。-- 腾讯云 TCR 公共镜像由独立工作流在正式 Release 发布后异步同步和审计;其- 耗时或失败不会阻塞 GitHub Release,也不会把已发布版本恢复为 Draft。+- 独立工作流会把同一个已验证 Git 提交发送到 CNB;正式 Release 发布后,CNB+ 在腾讯云侧异步构建并审计 TCR 公共镜像。其耗时或失败不会阻塞 GitHub+ Release,也不会把已发布版本恢复为 Draft。- 此命令不会自行授权或执行移动端商店交付。Draft 原生资产准备完成后,发布命令会强制核验 Android APK 是否使用 Google Play 应用签名证书;未通过时保持 Draft 并停止。此时先针对同一 Draft 执行@@ -60,15 +61,17 @@ bun run release -- \## 镜像仓库凭据-官方仓库必须配置 `TENCENT_TCR_USERNAME` 和 `TENCENT_TCR_PASSWORD` 两个-Actions Secret。对于 TCR 个人版,用户名是腾讯云账号 ID,密码是在 TCR 控制台-初始化的固定登录密码。GHCR 是正式发布的阻塞门禁;TCR 在发布后异步写入相同-标签并独立执行匿名访问、Digest 和架构检查。+GitHub 官方仓库必须配置 `CNB_TCR_BUILD_PUSH_TOKEN` Actions Secret,该令牌仅+拥有 CNB 源码镜像仓库的写权限。CNB 私有密钥仓库向可信的 `push` 和+`tag_push` 流水线提供 `TCR_USERNAME` 与 `TCR_PASSWORD`。对于 TCR 个人版,+用户名是腾讯云账号 ID,密码是在 TCR 控制台初始化的固定登录密码。GHCR 是正式+发布的阻塞门禁;CNB 根据同一个 Git 提交异步构建 TCR,写入相同的公共标签,+并独立核验匿名访问和双架构。两边独立构建,不要求 Registry Digest 相同。## 失败与续跑- 本地验证、Draft 资产或 GHCR 镜像失败时,Release 保持未发布状态。-- TCR 异步镜像失败时保留正式 Release,并在独立 Actions 工作流中修复、重跑。+- CNB/TCR 异步构建失败时保留正式 Release,并独立修复、重跑。- 中断后重新执行相同命令,会续跑匹配的 Draft,不会重复创建 Issue、提交或Release。- 发布后的原生资产或 GHCR 镜像审计失败时,脚本会尝试将 Release 恢复为diff --git a/package.json b/package.jsonindex 7a4202c2..b4ff734b 100644--- a/package.json+++ b/package.json@@ -22,7 +22,7 @@"dev:api:demo": "bun scripts/local-dev.mjs api demo","dev:self-hosted": "bun --watch scripts/self-hosted-server.mjs","start:self-hosted": "bun scripts/self-hosted-server.mjs",- "test:docker-release": "bun test scripts/docker-release.test.mjs scripts/docker-installer.test.mjs scripts/build-cloudflare-worker.test.mjs tests/storage-adapter.test.ts",+ "test:docker-release": "bun test scripts/docker-release.test.mjs scripts/prune-tcr-sha-tags.test.mjs scripts/docker-installer.test.mjs scripts/build-cloudflare-worker.test.mjs tests/storage-adapter.test.ts","dev:remote": "concurrently -k -n api,web -c cyan,magenta \"bun run dev:api:remote\" \"bun run dev:web\"","dev:api:remote": "bun scripts/run-wrangler.mjs dev --remote --port 8787","dev:web": "vite --config apps/web/vite.config.ts --host 127.0.0.1 --port 5173",diff --git a/scripts/docker-release.test.mjs b/scripts/docker-release.test.mjsindex d0a3d859..cce60f4e 100644--- a/scripts/docker-release.test.mjs+++ b/scripts/docker-release.test.mjs@@ -6,14 +6,19 @@ import { resolve } from "node:path";import { resolveSelfHostedConfig } from "./self-hosted-config.mjs";import { loadSelfHostedEnvironment } from "./self-hosted-secrets.mjs";-const readProjectFile = (path) => readFileSync(resolve(import.meta.dir, "..", path), "utf8");+const readProjectFile = (path) =>+ readFileSync(resolve(import.meta.dir, "..", path), "utf8");describe("self-hosted runtime configuration", () => {test("uses the portable single-volume defaults", () => {const config = resolveSelfHostedConfig({}, "/opt/edgeever");expect(config.dataDirectory).toBe("/opt/edgeever/.edgeever-data");- expect(config.databaseFile).toBe("/opt/edgeever/.edgeever-data/edgeever.sqlite");- expect(config.resourcesDirectory).toBe("/opt/edgeever/.edgeever-data/resources");+ expect(config.databaseFile).toBe(+ "/opt/edgeever/.edgeever-data/edgeever.sqlite",+ );+ expect(config.resourcesDirectory).toBe(+ "/opt/edgeever/.edgeever-data/resources",+ );expect(config.port).toBe(8787);expect(config.storageBackend).toBe("local");});@@ -23,7 +28,9 @@ describe("self-hosted runtime configuration", () => {const secretPath = resolve(directory, "password");try {await writeFile(secretPath, "secret-from-file\n");- const environment = await loadSelfHostedEnvironment({ EDGE_EVER_AUTH_PASSWORD_FILE: secretPath });+ const environment = await loadSelfHostedEnvironment({+ EDGE_EVER_AUTH_PASSWORD_FILE: secretPath,+ });expect(environment.EDGE_EVER_AUTH_PASSWORD).toBe("secret-from-file");expect(environment.EDGE_EVER_AUTH_PASSWORD_FILE).toBeUndefined();} finally {@@ -32,13 +39,15 @@ describe("self-hosted runtime configuration", () => {});test("rejects invalid ports and storage backends", () => {- expect(() => resolveSelfHostedConfig({ EDGE_EVER_PORT: "0" })).toThrow("EDGE_EVER_PORT");- expect(() => resolveSelfHostedConfig({ EDGE_EVER_STORAGE_BACKEND: "r2" })).toThrow(- "either local or s3",- );- expect(() => resolveSelfHostedConfig({ EDGE_EVER_STORAGE_BACKEND: "s3" })).toThrow(- "EDGE_EVER_S3_BUCKET",+ expect(() => resolveSelfHostedConfig({ EDGE_EVER_PORT: "0" })).toThrow(+ "EDGE_EVER_PORT",);+ expect(() =>+ resolveSelfHostedConfig({ EDGE_EVER_STORAGE_BACKEND: "r2" }),+ ).toThrow("either local or s3");+ expect(() =>+ resolveSelfHostedConfig({ EDGE_EVER_STORAGE_BACKEND: "s3" }),+ ).toThrow("EDGE_EVER_S3_BUCKET");});});@@ -48,8 +57,12 @@ describe("Docker release contract", () => {expect(dockerfile).toContain("FROM oven/bun:1.3.14-alpine AS runtime");expect(dockerfile).toContain("COPY patches patches");expect(dockerfile).toContain("COPY docs docs");- expect(dockerfile).toContain("COPY release-summary.json release-summary.json");- expect(dockerfile).toContain("COPY --from=build /app/release-summary.json ./release-summary.json");+ expect(dockerfile).toContain(+ "COPY release-summary.json release-summary.json",+ );+ expect(dockerfile).toContain(+ "COPY --from=build /app/release-summary.json ./release-summary.json",+ );expect(dockerfile).toContain("--filter @edgeever/web");expect(dockerfile).toContain("--production --filter edgeever");expect(dockerfile).toContain("USER bun");@@ -59,7 +72,9 @@ describe("Docker release contract", () => {test("keeps authentication explicit in Compose", () => {const compose = readProjectFile("compose.yaml");- expect(compose).toContain("EDGE_EVER_AUTH_PASSWORD: \"${EDGE_EVER_AUTH_PASSWORD:?");+ expect(compose).toContain(+ 'EDGE_EVER_AUTH_PASSWORD: "${EDGE_EVER_AUTH_PASSWORD:?',+ );expect(compose).toContain("edgeever-data:/data");expect(compose).toContain("no-new-privileges:true");});@@ -68,49 +83,71 @@ describe("Docker release contract", () => {const application = readProjectFile("apps/api/src/index.ts");const selfHosted = readProjectFile("scripts/self-hosted-server.mjs");expect(application).toContain("export const fetchEdgeEverApp");- expect(application).toContain("storage: createCloudflareStorageAdapter(env)");- expect(selfHosted).toContain("fetchEdgeEverApp(request, env, executionContext)");+ expect(application).toContain(+ "storage: createCloudflareStorageAdapter(env)",+ );+ expect(selfHosted).toContain(+ "fetchEdgeEverApp(request, env, executionContext)",+ );expect(selfHosted).not.toContain("worker.fetch(");});test("gates official image publishing and release auditing", () => {const workflow = readProjectFile(".github/workflows/docker-image.yml");- const mirrorWorkflow = readProjectFile(".github/workflows/docker-tcr-mirror.yml");- expect(workflow.match(/github\.repository == 'tianma-if\/edgeever'/g)?.length).toBeGreaterThanOrEqual(2);+ const mirrorWorkflow = readProjectFile(+ ".github/workflows/docker-tcr-mirror.yml",+ );+ const cnbWorkflow = readProjectFile(".cnb.yml");+ const tcrPublisher = readProjectFile("scripts/publish-tcr-image.sh");+ expect(+ workflow.match(/github\.repository == 'tianma-if\/edgeever'/g)?.length,+ ).toBeGreaterThanOrEqual(2);expect(workflow).toContain("release_tag");expect(workflow).toContain("contents: write\n packages: write");- expect(workflow).toContain("name: Publish official multi-platform image\n runs-on: ubuntu-latest\n timeout-minutes: 60");+ expect(workflow).toContain(+ "name: Publish official multi-platform image\n runs-on: ubuntu-latest\n timeout-minutes: 60",+ );expect(workflow).toContain('gh release view "${RELEASE_TAG}"');- expect(workflow).not.toContain('releases/tags/${RELEASE_TAG}');+ expect(workflow).not.toContain("releases/tags/${RELEASE_TAG}");expect(workflow).toContain("docker logout ghcr.io");expect(workflow).toContain("docker buildx imagetools inspect");expect(workflow).not.toContain("TCR_IMAGE_NAME");expect(workflow).not.toContain("TENCENT_TCR_USERNAME");- expect(mirrorWorkflow).toContain("name: Mirror Docker image to Tencent TCR");+ expect(mirrorWorkflow).toContain(+ "name: Build Tencent TCR image through CNB",+ );expect(mirrorWorkflow).toContain("workflow_run:");expect(mirrorWorkflow).toContain("release:");- expect(mirrorWorkflow).toContain("github.event.workflow_run.event == 'push'");- expect(mirrorWorkflow).toContain("TCR_IMAGE_NAME: ccr.ccs.tencentyun.com/edgeever/edgeever");- expect(mirrorWorkflow).toContain("secrets.TENCENT_TCR_USERNAME");- expect(mirrorWorkflow).toContain("secrets.TENCENT_TCR_PASSWORD");- expect(mirrorWorkflow).toContain("sudo apt-get install --yes skopeo");- expect(mirrorWorkflow).toContain("group: docker-tcr-mirror");- expect(mirrorWorkflow).toContain("github.event_name == 'release' || github.event_name == 'workflow_dispatch'");- expect(mirrorWorkflow).toContain('destination_tags="${source_tag},main"');- expect(mirrorWorkflow).toContain('primary_tag="${tags[0]}"');- expect(mirrorWorkflow).toContain('skopeo copy \\');- expect(mirrorWorkflow.match(/skopeo copy \\/g)?.length).toBe(1);- expect(mirrorWorkflow).toContain("--all");- expect(mirrorWorkflow).toContain("--preserve-digests");- expect(mirrorWorkflow).toContain("timeout --signal=TERM --kill-after=1m 15m skopeo copy");- expect(mirrorWorkflow).toContain('"docker://${GHCR_IMAGE_NAME}:${SOURCE_TAG}"');- expect(mirrorWorkflow).toContain('"docker://${TCR_IMAGE_NAME}:${PRIMARY_TAG}"');- expect(mirrorWorkflow).toContain("for attempt in 1 2 3; do");- expect(mirrorWorkflow).toContain('Failed to mirror ${PRIMARY_TAG} after ${attempt} attempts');- expect(mirrorWorkflow).toContain("name: Promote TCR tags without transferring layers");- expect(mirrorWorkflow).toContain("docker buildx imagetools create \\");- expect(mirrorWorkflow).toContain('"${TCR_IMAGE_NAME}@${primary_digest}"');- expect(mirrorWorkflow).toContain('test "${source_digest}" = "${mirror_digest}"');+ expect(mirrorWorkflow).toContain(+ "github.event.workflow_run.event == 'push'",+ );+ expect(mirrorWorkflow).toContain("secrets.CNB_TCR_BUILD_PUSH_TOKEN");+ expect(mirrorWorkflow).toContain("https://cnb.cool/tianma-if/edgeever");+ expect(mirrorWorkflow).toContain('"HEAD:${destination}"');+ expect(mirrorWorkflow).not.toContain("skopeo");+ expect(mirrorWorkflow).not.toContain("ghcr.io");++ expect(cnbWorkflow).toContain("main:\n push:");+ expect(cnbWorkflow).toContain('"v*":\n tag_push:');+ expect(cnbWorkflow).toContain("runner:\n cpus: 2");+ expect(cnbWorkflow).toContain("tianma-if/edgeever-secrets");+ expect(cnbWorkflow).toContain("bash scripts/publish-tcr-image.sh");++ expect(tcrPublisher).toContain(+ 'readonly TCR_IMAGE="${TCR_REGISTRY}/edgeever/edgeever"',+ );+ expect(tcrPublisher).toContain("--platform linux/amd64,linux/arm64");+ expect(tcrPublisher).toContain('primary_tag="sha-${short_sha}"');+ expect(tcrPublisher).toContain('promotion_tags=("${version}" latest)');+ expect(tcrPublisher).toContain(+ '--label "org.opencontainers.image.revision=${CNB_COMMIT}"',+ );+ expect(tcrPublisher).toContain("timeout --signal=TERM --kill-after=1m 45m");+ expect(tcrPublisher).toContain("docker buildx imagetools create \\");+ expect(tcrPublisher).toContain("org.opencontainers.image.revision");+ expect(tcrPublisher).toContain("--format '{{json .Image}}'");+ expect(tcrPublisher).toContain("TCR_SHA_TAGS_TO_KEEP=20");+ expect(tcrPublisher).not.toContain("ghcr.io");});});diff --git a/scripts/prune-tcr-sha-tags.mjs b/scripts/prune-tcr-sha-tags.mjsnew file mode 100644index 00000000..8375ba1f--- /dev/null+++ b/scripts/prune-tcr-sha-tags.mjs@@ -0,0 +1,168 @@+import { createHash, createHmac } from "node:crypto";++const TCR_ENDPOINT = "tcr.tencentcloudapi.com";+const TCR_SERVICE = "tcr";+const TCR_VERSION = "2019-09-24";+const SHA_TAG_PATTERN = /^sha-[0-9a-f]+$/;++const hash = (value) => createHash("sha256").update(value).digest("hex");+const hmac = (key, value, encoding) =>+ createHmac("sha256", key).update(value).digest(encoding);++export const selectTcrShaTagsToDelete = (tagInfo, keep = 20) => {+ if (!Number.isInteger(keep) || keep < 1) {+ throw new Error("keep must be a positive integer");+ }++ return tagInfo+ .filter(({ TagName }) => SHA_TAG_PATTERN.test(TagName))+ .sort((left, right) => {+ const leftTime = left.PushTime || left.CreationTime || "";+ const rightTime = right.PushTime || right.CreationTime || "";+ return (+ rightTime.localeCompare(leftTime) ||+ right.TagName.localeCompare(left.TagName)+ );+ })+ .slice(keep)+ .map(({ TagName }) => TagName);+};++export const createTencentCloudRequest = ({+ action,+ body,+ region,+ secretId,+ secretKey,+ token,+ timestamp = Math.floor(Date.now() / 1000),+}) => {+ const payload = JSON.stringify(body);+ const date = new Date(timestamp * 1000).toISOString().slice(0, 10);+ const canonicalHeaders = [+ "content-type:application/json; charset=utf-8",+ `host:${TCR_ENDPOINT}`,+ `x-tc-action:${action.toLowerCase()}`,+ "",+ ].join("\n");+ const signedHeaders = "content-type;host;x-tc-action";+ const canonicalRequest = [+ "POST",+ "/",+ "",+ canonicalHeaders,+ signedHeaders,+ hash(payload),+ ].join("\n");+ const credentialScope = `${date}/${TCR_SERVICE}/tc3_request`;+ const stringToSign = [+ "TC3-HMAC-SHA256",+ timestamp,+ credentialScope,+ hash(canonicalRequest),+ ].join("\n");+ const secretDate = hmac(`TC3${secretKey}`, date);+ const secretService = hmac(secretDate, TCR_SERVICE);+ const secretSigning = hmac(secretService, "tc3_request");+ const signature = hmac(secretSigning, stringToSign, "hex");+ const authorization = [+ `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}`,+ `SignedHeaders=${signedHeaders}`,+ `Signature=${signature}`,+ ].join(", ");++ return {+ payload,+ headers: {+ Authorization: authorization,+ "Content-Type": "application/json; charset=utf-8",+ Host: TCR_ENDPOINT,+ "X-TC-Action": action,+ "X-TC-Region": region,+ "X-TC-Timestamp": String(timestamp),+ "X-TC-Version": TCR_VERSION,+ ...(token ? { "X-TC-Token": token } : {}),+ },+ };+};++const callTencentCloud = async ({ action, body, credentials }) => {+ const request = createTencentCloudRequest({ action, body, ...credentials });+ const response = await fetch(`https://${TCR_ENDPOINT}`, {+ method: "POST",+ headers: request.headers,+ body: request.payload,+ });+ const result = await response.json();+ const error = result.Response?.Error;+ if (!response.ok || error) {+ throw new Error(+ `${action} failed: ${error?.Code || response.status} ${error?.Message || response.statusText}`,+ );+ }+ return result.Response;+};++export const pruneTcrShaTags = async ({+ repoName,+ keep,+ credentials,+ dryRun = false,+}) => {+ const result = await callTencentCloud({+ action: "DescribeImagePersonal",+ body: { RepoName: repoName, Offset: 0, Limit: 100 },+ credentials,+ });+ const tagsToDelete = selectTcrShaTagsToDelete(+ result.Data?.TagInfo || [],+ keep,+ );++ if (!dryRun) {+ for (let offset = 0; offset < tagsToDelete.length; offset += 20) {+ await callTencentCloud({+ action: "BatchDeleteImagePersonal",+ body: {+ RepoName: repoName,+ Tags: tagsToDelete.slice(offset, offset + 20),+ },+ credentials,+ });+ }+ }++ return tagsToDelete;+};++const isMain =+ process.argv[1] &&+ import.meta.url === new URL(`file://${process.argv[1]}`).href;++if (isMain) {+ const keep = Number.parseInt(process.env.TCR_SHA_TAGS_TO_KEEP || "20", 10);+ const repoName = process.env.TCR_REPOSITORY || "edgeever/edgeever";+ const credentials = {+ region: process.env.TENCENTCLOUD_REGION || "ap-guangzhou",+ secretId: process.env.TENCENTCLOUD_SECRET_ID,+ secretKey: process.env.TENCENTCLOUD_SECRET_KEY,+ token: process.env.TENCENTCLOUD_TOKEN,+ };+ if (!credentials.secretId || !credentials.secretKey) {+ throw new Error(+ "TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY are required",+ );+ }++ const tagsToDelete = await pruneTcrShaTags({+ repoName,+ keep,+ credentials,+ dryRun: process.argv.includes("--dry-run"),+ });+ console.log(+ tagsToDelete.length === 0+ ? `No sha-* tags need pruning; keeping the latest ${keep}.`+ : `${process.argv.includes("--dry-run") ? "Would delete" : "Deleted"} ${tagsToDelete.length} sha-* tags: ${tagsToDelete.join(", ")}`,+ );+}diff --git a/scripts/prune-tcr-sha-tags.test.mjs b/scripts/prune-tcr-sha-tags.test.mjsnew file mode 100644index 00000000..036bdcea--- /dev/null+++ b/scripts/prune-tcr-sha-tags.test.mjs@@ -0,0 +1,66 @@+import { describe, expect, test } from "bun:test";+import {+ createTencentCloudRequest,+ selectTcrShaTagsToDelete,+} from "./prune-tcr-sha-tags.mjs";++describe("TCR sha tag retention", () => {+ test("keeps the newest sha tags without touching release tags", () => {+ const tags = [+ { TagName: "v1.40.0", PushTime: "2026-08-25 13:00:00 +0800 CST" },+ { TagName: "1.40.0", PushTime: "2026-08-25 13:00:00 +0800 CST" },+ { TagName: "latest", PushTime: "2026-08-25 13:00:00 +0800 CST" },+ {+ TagName: "sha-cccccccccccc",+ PushTime: "2026-08-25 12:00:00 +0800 CST",+ },+ {+ TagName: "sha-bbbbbbbbbbbb",+ PushTime: "2026-08-25 11:00:00 +0800 CST",+ },+ {+ TagName: "sha-aaaaaaaaaaaa",+ PushTime: "2026-08-25 10:00:00 +0800 CST",+ },+ ];++ expect(selectTcrShaTagsToDelete(tags, 2)).toEqual(["sha-aaaaaaaaaaaa"]);+ });++ test("uses creation time as a fallback and rejects invalid retention", () => {+ const tags = [+ {+ TagName: "sha-bbbbbbbbbbbb",+ CreationTime: "2026-08-25 12:00:00 +0800 CST",+ },+ {+ TagName: "sha-aaaaaaaaaaaa",+ CreationTime: "2026-08-24 12:00:00 +0800 CST",+ },+ ];++ expect(selectTcrShaTagsToDelete(tags, 1)).toEqual(["sha-aaaaaaaaaaaa"]);+ expect(() => selectTcrShaTagsToDelete(tags, 0)).toThrow("positive integer");+ });++ test("signs requests without exposing the secret key", () => {+ const request = createTencentCloudRequest({+ action: "DescribeImagePersonal",+ body: { RepoName: "edgeever/edgeever", Offset: 0, Limit: 100 },+ region: "ap-guangzhou",+ secretId: "example-secret-id",+ secretKey: "example-secret-key",+ timestamp: 1_788_000_000,+ });++ expect(request.headers.Authorization).toContain(+ "Credential=example-secret-id/",+ );+ expect(request.headers.Authorization).toContain(+ "SignedHeaders=content-type;host;x-tc-action",+ );+ expect(request.headers.Authorization).not.toContain("example-secret-key");+ expect(request.headers["X-TC-Action"]).toBe("DescribeImagePersonal");+ expect(request.headers["X-TC-Region"]).toBe("ap-guangzhou");+ });+});diff --git a/scripts/publish-tcr-image.sh b/scripts/publish-tcr-image.shnew file mode 100644index 00000000..2127a0d9--- /dev/null+++ b/scripts/publish-tcr-image.sh@@ -0,0 +1,98 @@+#!/usr/bin/env bash++set -Eeuo pipefail++readonly TCR_REGISTRY="ccr.ccs.tencentyun.com"+readonly TCR_IMAGE="${TCR_REGISTRY}/edgeever/edgeever"++require_value() {+ local name="$1"+ local value="${!name:-}"+ [[ -n "${value}" ]] || {+ echo "${name} is required" >&2+ exit 1+ }+}++for name in CNB_COMMIT CNB_BRANCH CNB_EVENT TCR_USERNAME TCR_PASSWORD; do+ require_value "${name}"+done++[[ "${CNB_COMMIT}" =~ ^[0-9a-f]{40}$ ]] || {+ echo "CNB_COMMIT must be a full Git SHA" >&2+ exit 1+}+test "$(git rev-parse HEAD)" = "${CNB_COMMIT}"++short_sha="${CNB_COMMIT:0:12}"+if [[ "${CNB_EVENT}" == "push" && "${CNB_BRANCH}" == "main" ]]; then+ version="main"+ primary_tag="sha-${short_sha}"+ promotion_tags=(main)+elif [[ "${CNB_EVENT}" == "tag_push" && "${CNB_BRANCH}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ version="${CNB_BRANCH#v}"+ test "$(jq -r '.version' package.json)" = "${version}"+ primary_tag="${CNB_BRANCH}"+ promotion_tags=("${version}" latest)+else+ echo "Refusing unsupported CNB event ${CNB_EVENT}:${CNB_BRANCH}" >&2+ exit 1+fi++printf '%s' "${TCR_PASSWORD}" | docker login \+ --username "${TCR_USERNAME}" \+ --password-stdin \+ "${TCR_REGISTRY}"++timeout --signal=TERM --kill-after=1m 45m docker buildx build \+ --platform linux/amd64,linux/arm64 \+ --tag "${TCR_IMAGE}:${primary_tag}" \+ --label "org.opencontainers.image.source=https://github.com/tianma-if/edgeever" \+ --label "org.opencontainers.image.revision=${CNB_COMMIT}" \+ --label "org.opencontainers.image.version=${version}" \+ --cache-from "type=registry,ref=${TCR_IMAGE}:buildcache" \+ --cache-to "type=registry,ref=${TCR_IMAGE}:buildcache,mode=max,image-manifest=true,oci-mediatypes=true" \+ --push \+ .++primary_inspect="$(docker buildx imagetools inspect "${TCR_IMAGE}:${primary_tag}")"+primary_digest="$(sed -n 's/^Digest:[[:space:]]*//p' <<<"${primary_inspect}" | head -n 1)"+test -n "${primary_digest}"+docker buildx imagetools inspect --raw "${TCR_IMAGE}:${primary_tag}" |+ jq -e '([.manifests[].platform.architecture] | index("amd64") != null) and ([.manifests[].platform.architecture] | index("arm64") != null)'++for image_tag in "${promotion_tags[@]}"; do+ docker buildx imagetools create \+ --tag "${TCR_IMAGE}:${image_tag}" \+ "${TCR_IMAGE}@${primary_digest}"+done++docker logout "${TCR_REGISTRY}"+for image_tag in "${primary_tag}" "${promotion_tags[@]}"; do+ mirror_inspect="$(docker buildx imagetools inspect "${TCR_IMAGE}:${image_tag}")"+ mirror_digest="$(sed -n 's/^Digest:[[:space:]]*//p' <<<"${mirror_inspect}" | head -n 1)"+ test "${primary_digest}" = "${mirror_digest}"+ docker buildx imagetools inspect --raw "${TCR_IMAGE}:${image_tag}" |+ jq -e '([.manifests[].platform.architecture] | index("amd64") != null) and ([.manifests[].platform.architecture] | index("arm64") != null)'+ image_metadata="$(docker buildx imagetools inspect "${TCR_IMAGE}:${image_tag}" --format '{{json .Image}}')"+ jq -e \+ --arg revision "${CNB_COMMIT}" \+ --arg version "${version}" \+ 'length >= 2 and all(.[]; .config.Labels["org.opencontainers.image.revision"] == $revision and .config.Labels["org.opencontainers.image.version"] == $version)' \+ <<<"${image_metadata}"+done++if [[ "${CNB_EVENT}" == "push" ]] && [[ -n "${TENCENTCLOUD_SECRET_ID:-}" ]] && [[ -n "${TENCENTCLOUD_SECRET_KEY:-}" ]]; then+ docker run --rm \+ --env TENCENTCLOUD_SECRET_ID \+ --env TENCENTCLOUD_SECRET_KEY \+ --env TENCENTCLOUD_REGION="${TENCENTCLOUD_REGION:-ap-guangzhou}" \+ --env TCR_REPOSITORY=edgeever/edgeever \+ --env TCR_SHA_TAGS_TO_KEEP=20 \+ --volume "${PWD}:/workspace" \+ --workdir /workspace \+ oven/bun:1.3.14-alpine \+ bun scripts/prune-tcr-sha-tags.mjs+else+ echo "Skipping sha-* retention until the tag-specific TCR API credential is configured."+fi