dsh-session-sync 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +5 -2
- package/CHANGELOG.md +17 -0
- package/README.es.md +5 -2
- package/README.hi.md +5 -2
- package/README.md +26 -4
- package/README.pt.md +5 -2
- package/README.zh.md +5 -2
- package/cordis.patch.yml +9 -2
- package/index.mjs +107 -7
- package/lib/age.mjs +77 -0
- package/lib/backend.mjs +57 -0
- package/lib/constants.mjs +18 -1
- package/lib/encrypted.mjs +523 -0
- package/lib/errors.mjs +12 -2
- package/lib/git.mjs +38 -0
- package/lib/render.mjs +8 -4
- package/package.json +1 -1
- package/types.d.ts +11 -2
package/ARCHITECTURE.md
CHANGED
|
@@ -21,6 +21,9 @@
|
|
|
21
21
|
| `lib/merge.mjs` | Append-only three-way merge classification — pure |
|
|
22
22
|
| `lib/mirror.mjs` | Byte mirror from the session store into the worktree (`node:fs`) |
|
|
23
23
|
| `lib/git.mjs` | Git command layer: verb whitelist + argument assertions, never force-push/reset/rebase/branch-switch |
|
|
24
|
+
| `lib/backend.mjs` | Transport backend seam contract + pure `selectEncryptionMode` (backend/mode/warnings selection) |
|
|
25
|
+
| `lib/age.mjs` | age binary probe (`detectAge`) + file-based `ageEncrypt`/`ageDecrypt` (optional external binary, graceful degrade) |
|
|
26
|
+
| `lib/encrypted.mjs` | `EncryptedBackend`: age-encrypted git transport (encrypt-then-push, decrypt-then-merge on plaintext, plaintext fallback) |
|
|
24
27
|
| `lib/engine.mjs` | Sync orchestration: `push` (mirror → commit → push, reconcile-and-retry once on rejection), `pull` (commit → fetch → three-way merge), `status` |
|
|
25
28
|
| `lib/status.mjs` | Read-only status collection (no fetch, no writes) |
|
|
26
29
|
| `lib/render.mjs` | Result text rendering (pure, JSON-safe inputs) |
|
|
@@ -69,7 +72,7 @@ Every automatic behavior is a Cordis effect, so stop/hot-reload removes it:
|
|
|
69
72
|
|
|
70
73
|
- `autoPullOnStart` — `ctx.effect` pulls once on mount.
|
|
71
74
|
- `autoPushOnTurnEnd` — `ctx.on('session/event')` pushes after `turn/end`.
|
|
72
|
-
- `pullIntervalMinutes` — `ctx.setInterval` periodic pull.
|
|
75
|
+
- `pullIntervalMinutes` — `ctx.effect` wraps a `setInterval` periodic pull (the disposer clears the timer).
|
|
73
76
|
|
|
74
77
|
Auto runs are covered by the config grant and never re-confirm.
|
|
75
78
|
|
|
@@ -83,4 +86,4 @@ Auto runs are covered by the config grant and never re-confirm.
|
|
|
83
86
|
|
|
84
87
|
## Backend vocabulary
|
|
85
88
|
|
|
86
|
-
`backend: git` is the
|
|
89
|
+
`backend: git` is the plaintext mirror transport. `backend: encrypted` wraps the same git transport with an **age** layer above the mirror: the plaintext mirror (`sessions/`) stays local-only (`.gitignore`), each session file is age-encrypted into `encrypted/**/*.age`, and only ciphertext is committed/pushed. Pulls decrypt the remote/base trees back to plaintext and run the same append-only three-way merge locally, then re-encrypt. When `age` is absent or `ageRecipient`/`ageIdentity` is empty, the encrypted backend **degrades to plaintext git** and warns explicitly (status/log) — it never silently claims encryption. `object-storage` is an interface placeholder and fails loud at load.
|
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,23 @@ All notable changes to this project are documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.2.0] - 2026-08-26
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `backend: encrypted` — an age-encrypted git transport that encrypts mirror content before push and decrypts it before merging, with graceful fallback to plaintext git (plus an explicit warning) when `age`/`ageRecipient`/`ageIdentity` is unavailable. `object-storage` remains a reserved placeholder that fails loud at load.
|
|
13
|
+
- Transport backend seam (`lib/backend.mjs`: a documented `status`/`push`/`pull` contract and a pure `selectEncryptionMode`), `lib/age.mjs` (`detectAge` + file-based `ageEncrypt`/`ageDecrypt`), and `lib/encrypted.mjs` (`EncryptedBackend`). The plaintext `git` backend and its zero-dependency default path are unchanged.
|
|
14
|
+
|
|
15
|
+
### Docs
|
|
16
|
+
|
|
17
|
+
- README threat model describing the encryption boundary: age protects the mirror content, while keys/age identities stay user-managed and the remote remains a private repository in practice.
|
|
18
|
+
|
|
19
|
+
## [0.1.4] - 2026-08-23
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- Corrected the stale test count in the Development sections (the repo runs 10 `node --test` files, not 6 suites) across the five-language READMEs and `AGENTS.md`, and fixed `ARCHITECTURE.md`'s periodic-pull description to match the code (`ctx.effect` wrapping `setInterval`, not `ctx.setInterval`). Documentation only — no behavior change.
|
|
24
|
+
|
|
8
25
|
## [0.1.3] - 2026-08-22
|
|
9
26
|
|
|
10
27
|
### Changed
|
package/README.es.md
CHANGED
|
@@ -87,12 +87,15 @@ Todos los ajustes son campos de `Config` de Schemastery (modificables desde cord
|
|
|
87
87
|
| Clave | Valor predeterminado | Significado |
|
|
88
88
|
|---|---|---|
|
|
89
89
|
| `enabled` | `true` | Interruptor maestro; `false` desregistra el comando, las herramientas, los oyentes y los modos automáticos |
|
|
90
|
-
| `backend` | `git` | Backend de sincronización
|
|
90
|
+
| `backend` | `git` | Backend de sincronización: `git` (espejo en texto plano) o `encrypted` (contenido del espejo cifrado con age) |
|
|
91
91
|
| `sessionRoot` | `''` | Raíz del almacén de sesiones; vacío = `$DSH_HOME/sessions` (si faltan ambos, falla la carga) |
|
|
92
92
|
| `repoDir` | `''` | Raíz del árbol de trabajo; vacío = `$DSH_HOME/dsh-session-sync/repo` |
|
|
93
93
|
| `remote` | `''` | Dirección remota (requerida antes de pull/push; status/diff funcionan sin ella) |
|
|
94
94
|
| `branch` | `main` | Nombre de la rama remota |
|
|
95
95
|
| `gitBin` | `git` | Ruta del ejecutable git |
|
|
96
|
+
| `ageBin` | `age` | Ruta del ejecutable age (se sondea con `backend: encrypted`; si falta, degrada a texto plano) |
|
|
97
|
+
| `ageRecipient` | `''` | Destinatario age (clave pública o cadena de identidad); vacío = no se puede cifrar, degrada a texto plano |
|
|
98
|
+
| `ageIdentity` | `''` | Ruta a una clave secreta age sin frase de paso (para descifrar); vacío = degrada a texto plano |
|
|
96
99
|
| `autoPullOnStart` | `false` | Hace pull una vez al montar el plugin (la configuración es la concesión; sin reconfirmar) |
|
|
97
100
|
| `autoPushOnTurnEnd` | `false` | Hace push tras cada turno cerrado |
|
|
98
101
|
| `pullIntervalMinutes` | `0` | Pull periódico cada N minutos (`0` = apagado, máx. `10080`) |
|
|
@@ -159,7 +162,7 @@ Ejemplo de sobrescritura en tu parche de perfil:
|
|
|
159
162
|
```sh
|
|
160
163
|
pnpm install # node ^22.19 || >=24
|
|
161
164
|
pnpm run typecheck && pnpm run typecheck:ci # tsc --checkJs contra los peers 0.1.1-rc.2 publicados
|
|
162
|
-
pnpm test # node --test (
|
|
165
|
+
pnpm test # node --test (12 archivos de test; la suite git del motor se omite sin git)
|
|
163
166
|
pnpm run verify:self-contained # las specs de dependencias resuelven desde el registro
|
|
164
167
|
pnpm run verify:artifacts # archivos publicados presentes + index.mjs importable
|
|
165
168
|
pnpm run check:readmes # consistencia de los cinco README
|
package/README.hi.md
CHANGED
|
@@ -87,12 +87,15 @@ dsh --profile web --dump-config | grep -A2 'id: session-sync'
|
|
|
87
87
|
| कुंजी | डिफ़ॉल्ट | अर्थ |
|
|
88
88
|
|---|---|---|
|
|
89
89
|
| `enabled` | `true` | मास्टर स्विच; `false` कमांड, टूल, लिसनर और स्वचालित मोड हटा देता है |
|
|
90
|
-
| `backend` | `git` | सिंक
|
|
90
|
+
| `backend` | `git` | सिंक बैकएंड: `git` (सादा-पाठ मिरर) या `encrypted` (age-एन्क्रिप्टेड मिरर सामग्री) |
|
|
91
91
|
| `sessionRoot` | `''` | सत्र स्टोर रूट; खाली = `$DSH_HOME/sessions` (दोनों अनुपस्थित होने पर लोड असफल) |
|
|
92
92
|
| `repoDir` | `''` | सिंक वर्कट्री रूट; खाली = `$DSH_HOME/dsh-session-sync/repo` |
|
|
93
93
|
| `remote` | `''` | रिमोट पता (pull/push से पहले आवश्यक; status/diff इसके बिना काम करते हैं) |
|
|
94
94
|
| `branch` | `main` | रिमोट ब्रांच का नाम |
|
|
95
95
|
| `gitBin` | `git` | git एक्ज़ीक्यूटेबल पथ |
|
|
96
|
+
| `ageBin` | `age` | age एक्ज़ीक्यूटेबल पथ (`backend: encrypted` पर जाँचा जाता है; अनुपस्थित होने पर सादे-पाठ पर डाउनग्रेड) |
|
|
97
|
+
| `ageRecipient` | `''` | age प्राप्तकर्ता (सार्वजनिक कुंजी या पहचान स्ट्रिंग); खाली = एन्क्रिप्ट नहीं हो सकता, सादे-पाठ पर डाउनग्रेड |
|
|
98
|
+
| `ageIdentity` | `''` | पासफ़्रेज़-रहित age गुप्त कुंजी का पथ (डिक्रिप्शन के लिए); खाली = सादे-पाठ पर डाउनग्रेड |
|
|
96
99
|
| `autoPullOnStart` | `false` | प्लगइन माउंट होने पर एक बार pull करें (कॉन्फ़िग ही अनुमति है; पुनः पुष्टि नहीं) |
|
|
97
100
|
| `autoPushOnTurnEnd` | `false` | हर बंद टर्न के बाद push करें |
|
|
98
101
|
| `pullIntervalMinutes` | `0` | हर N मिनट में आवधिक pull (`0` = बंद, अधिकतम `10080`) |
|
|
@@ -159,7 +162,7 @@ dsh --profile web --dump-config | grep -A2 'id: session-sync'
|
|
|
159
162
|
```sh
|
|
160
163
|
pnpm install # node ^22.19 || >=24
|
|
161
164
|
pnpm run typecheck && pnpm run typecheck:ci # प्रकाशित 0.1.1-rc.2 peers के विरुद्ध tsc --checkJs
|
|
162
|
-
pnpm test # node --test (
|
|
165
|
+
pnpm test # node --test (12 टेस्ट फ़ाइलें; git इंजन सुइट बिना git के छोड़ी जाती है)
|
|
163
166
|
pnpm run verify:self-contained # निर्भरता spec रजिस्ट्री से हल होती हैं
|
|
164
167
|
pnpm run verify:artifacts # प्रकाशित फ़ाइलें उपस्थित + index.mjs import योग्य
|
|
165
168
|
pnpm run check:readmes # पाँच-भाषा README संगतता
|
package/README.md
CHANGED
|
@@ -88,12 +88,15 @@ All tunables are Schemastery `Config` fields (changeable from cordis.yml). An id
|
|
|
88
88
|
| Key | Default | Meaning |
|
|
89
89
|
|---|---|---|
|
|
90
90
|
| `enabled` | `true` | Master switch; `false` unregisters the command, tools, listeners, and auto modes |
|
|
91
|
-
| `backend` | `git` | Sync backend
|
|
91
|
+
| `backend` | `git` | Sync backend: `git` (plaintext mirror) or `encrypted` (age-encrypted mirror content) |
|
|
92
92
|
| `sessionRoot` | `''` | Session store root; empty = `$DSH_HOME/sessions` (both missing fails load) |
|
|
93
93
|
| `repoDir` | `''` | Sync worktree root; empty = `$DSH_HOME/dsh-session-sync/repo` |
|
|
94
94
|
| `remote` | `''` | Remote address (required before pull/push; status/diff work without one) |
|
|
95
95
|
| `branch` | `main` | Remote branch name |
|
|
96
96
|
| `gitBin` | `git` | git executable path |
|
|
97
|
+
| `ageBin` | `age` | age executable path (probed for `backend: encrypted`; missing degrades to plaintext) |
|
|
98
|
+
| `ageRecipient` | `''` | age recipient (public key or identity string); empty = cannot encrypt, degrades to plaintext |
|
|
99
|
+
| `ageIdentity` | `''` | Path to a passphrase-less age secret key for decryption; empty = cannot decrypt, degrades to plaintext |
|
|
97
100
|
| `autoPullOnStart` | `false` | Pull once when the plugin mounts (config is the grant; no re-confirm) |
|
|
98
101
|
| `autoPushOnTurnEnd` | `false` | Push after every closed turn |
|
|
99
102
|
| `pullIntervalMinutes` | `0` | Periodic pull every N minutes (`0` = off, max `10080`) |
|
|
@@ -144,14 +147,33 @@ Example override in your profile patch:
|
|
|
144
147
|
- **Never silently overwrite.** The append-only three-way merge keeps both sides on any divergence; fork files are never deleted, and git never force-pushes, resets, rebases, or switches branches.
|
|
145
148
|
- **Path containment.** Files are mirrored as opaque bytes with symlinks refused and every joined path containment-checked (`PATH_UNSAFE` fails loud).
|
|
146
149
|
- **Sanitized output.** Remote-URL credentials, tokens, and `key=value` secrets are redacted before reaching the model or the log; path display refuses anything outside its root.
|
|
147
|
-
- **No credential storage.** The plugin stores no credentials; git credentials live in your normal git credential helper.
|
|
150
|
+
- **No credential storage.** The plugin stores no credentials; git credentials live in your normal git credential helper. age keys are read from paths you configure (`ageIdentity`); keys never enter the sync repository.
|
|
148
151
|
- **Git hardening.** Git runs with `GIT_TERMINAL_PROMPT=0` and `GIT_OPTIONAL_LOCKS=0`, deadline- and signal-bounded, with a per-stream output cap.
|
|
149
152
|
- **Fail closed.** A missing confirmation answerer, a missing remote, or an unsafe path refuses the operation loudly.
|
|
150
153
|
|
|
154
|
+
## Encryption & threat model
|
|
155
|
+
|
|
156
|
+
`backend: encrypted` adds an optional **age** layer above the mirror: session bytes are encrypted into `encrypted/**/*.age` files before they are committed and pushed, and decrypted back to the local plaintext mirror before merging. The three-way merge always runs on plaintext locally, so the append-only keep-both semantics are unchanged.
|
|
157
|
+
|
|
158
|
+
What the encryption **protects**:
|
|
159
|
+
|
|
160
|
+
- **Mirror content at rest in the remote.** The session files you push are age ciphertext; the remote host, its operators, and anyone who clones the repository do not see plaintext session bytes without the private key.
|
|
161
|
+
|
|
162
|
+
What it does **not** protect (the boundary):
|
|
163
|
+
|
|
164
|
+
- **Keys and age identities are yours to manage.** The recipient/identity files are never shipped, stored, or rotated by the plugin. If a key leaks, the mirror content it protects is exposed. Use a passphrase-less identity and keep it out of the repository.
|
|
165
|
+
- **The remote is still a private repository in practice.** git metadata — commit messages, the `.gitignore`, the `encrypted/` path structure, branch names, and push/fetch activity — remains visible to the remote host. Encryption hides the *content*, not the fact that you sync, nor the shape of your session tree.
|
|
166
|
+
- **Plaintext still exists locally.** The mirror at `<repoDir>/sessions/` is plaintext on disk; encryption protects the transmitted/remote copy, not local disk encryption or the live session store.
|
|
167
|
+
- **graceful degradation means plaintext.** With `backend: encrypted`, if `age` is missing, or `ageRecipient`/`ageIdentity` is empty, the plugin falls back to the plaintext git path **and warns explicitly** in the status/log — it never silently pretends to encrypt. Check `/sync status` for the warning before trusting the remote as encrypted.
|
|
168
|
+
|
|
169
|
+
Baseline: with `backend: git` (the default), session bytes are stored unencrypted in **your** git remote — use a private repository.
|
|
170
|
+
|
|
151
171
|
## Known limitations
|
|
152
172
|
|
|
153
|
-
- **
|
|
173
|
+
- **Object storage backend reserved.** `object-storage` is an interface placeholder and fails loudly at load; only `git` and `encrypted` are implemented.
|
|
154
174
|
- **git required.** The plugin needs the `git` executable and the `subprocess` service; without them, sync operations fail with a clear reason (profiles keep booting).
|
|
175
|
+
- **age is optional, external.** Encryption depends on the `age` binary on `PATH` (or `ageBin`). No `age` → plaintext fallback with a warning; a passphrase-protected identity cannot be used (decryption would block on a TTY prompt, so it fails closed).
|
|
176
|
+
- **One repoDir per backend.** Switching between `git` and `encrypted` on the same `repoDir` is not supported; use a fresh worktree per backend.
|
|
155
177
|
- **Session events on `0.1.0-rc.6`/`0.1.0-rc.8`/`0.1.1-rc.2`.** The harness does not record `sync/*` event types, so the session-log appends are skipped (sessions keep loading); the plugin enables them automatically once a host records the types or exposes the `ignorable` envelope on `Session.append`.
|
|
156
178
|
- **`approval` between turns.** `/sync` runs between turns, where the `approval` channel has no open turn to attach to; use `confirmVia: userQuestions` for command-driven sync, or drive sync through the tools inside a turn.
|
|
157
179
|
|
|
@@ -160,7 +182,7 @@ Example override in your profile patch:
|
|
|
160
182
|
```sh
|
|
161
183
|
pnpm install # node ^22.19 || >=24
|
|
162
184
|
pnpm run typecheck && pnpm run typecheck:ci # tsc --checkJs against the published 0.1.1-rc.2 peers
|
|
163
|
-
pnpm test # node --test (
|
|
185
|
+
pnpm test # node --test (12 test files; the engine git suite skips without git)
|
|
164
186
|
pnpm run verify:self-contained # dependency specs resolve from the registry
|
|
165
187
|
pnpm run verify:artifacts # shipped files present + index.mjs importable
|
|
166
188
|
pnpm run check:readmes # five-language README consistency
|
package/README.pt.md
CHANGED
|
@@ -87,12 +87,15 @@ Todos os ajustes são campos de `Config` do Schemastery (alteráveis pelo cordis
|
|
|
87
87
|
| Chave | Padrão | Significado |
|
|
88
88
|
|---|---|---|
|
|
89
89
|
| `enabled` | `true` | Interruptor mestre; `false` remove comando, ferramentas, ouvintes e modos automáticos |
|
|
90
|
-
| `backend` | `git` | Backend de sincronização
|
|
90
|
+
| `backend` | `git` | Backend de sincronização: `git` (espelho em texto simples) ou `encrypted` (conteúdo do espelho criptografado com age) |
|
|
91
91
|
| `sessionRoot` | `''` | Raiz do armazenamento de sessões; vazio = `$DSH_HOME/sessions` (ambos ausentes falha o carregamento) |
|
|
92
92
|
| `repoDir` | `''` | Raiz da árvore de trabalho; vazio = `$DSH_HOME/dsh-session-sync/repo` |
|
|
93
93
|
| `remote` | `''` | Endereço remoto (obrigatório antes de pull/push; status/diff funcionam sem ele) |
|
|
94
94
|
| `branch` | `main` | Nome da branch remota |
|
|
95
95
|
| `gitBin` | `git` | Caminho do executável git |
|
|
96
|
+
| `ageBin` | `age` | Caminho do executável age (sondado com `backend: encrypted`; se ausente, degrada para texto simples) |
|
|
97
|
+
| `ageRecipient` | `''` | Destinatário age (chave pública ou string de identidade); vazio = não é possível criptografar, degrada para texto simples |
|
|
98
|
+
| `ageIdentity` | `''` | Caminho para uma chave secreta age sem senha (para descriptografar); vazio = degrada para texto simples |
|
|
96
99
|
| `autoPullOnStart` | `false` | Faz pull uma vez quando o plugin monta (a configuração é a concessão; sem reconfirmar) |
|
|
97
100
|
| `autoPushOnTurnEnd` | `false` | Faz push após cada turno fechado |
|
|
98
101
|
| `pullIntervalMinutes` | `0` | Pull periódico a cada N minutos (`0` = desligado, máx. `10080`) |
|
|
@@ -159,7 +162,7 @@ Exemplo de sobrescrita no seu patch de perfil:
|
|
|
159
162
|
```sh
|
|
160
163
|
pnpm install # node ^22.19 || >=24
|
|
161
164
|
pnpm run typecheck && pnpm run typecheck:ci # tsc --checkJs contra os peers 0.1.1-rc.2 publicados
|
|
162
|
-
pnpm test # node --test (
|
|
165
|
+
pnpm test # node --test (12 arquivos de teste; a suíte git do motor é omitida sem git)
|
|
163
166
|
pnpm run verify:self-contained # as specs de dependência resolvem do registro
|
|
164
167
|
pnpm run verify:artifacts # arquivos publicados presentes + index.mjs importável
|
|
165
168
|
pnpm run check:readmes # consistência dos cinco README
|
package/README.zh.md
CHANGED
|
@@ -87,12 +87,15 @@ dsh --profile web --dump-config | grep -A2 'id: session-sync'
|
|
|
87
87
|
| 键 | 默认值 | 含义 |
|
|
88
88
|
|---|---|---|
|
|
89
89
|
| `enabled` | `true` | 总开关;`false` 卸载命令、工具、监听器与自动模式 |
|
|
90
|
-
| `backend` | `git` |
|
|
90
|
+
| `backend` | `git` | 同步后端:`git`(明文镜像)或 `encrypted`(age 加密镜像内容) |
|
|
91
91
|
| `sessionRoot` | `''` | 会话存储根;空 = `$DSH_HOME/sessions`(两者皆缺加载失败) |
|
|
92
92
|
| `repoDir` | `''` | 同步工作树根;空 = `$DSH_HOME/dsh-session-sync/repo` |
|
|
93
93
|
| `remote` | `''` | 远端地址(pull/push 前必须非空;status/diff 无需) |
|
|
94
94
|
| `branch` | `main` | 远端分支名 |
|
|
95
95
|
| `gitBin` | `git` | git 可执行路径 |
|
|
96
|
+
| `ageBin` | `age` | age 可执行路径(`backend: encrypted` 时探测;缺失降级明文) |
|
|
97
|
+
| `ageRecipient` | `''` | age 收件人(公钥/身份串);空 = 无法加密、降级明文 |
|
|
98
|
+
| `ageIdentity` | `''` | 无口令 age 私钥文件路径(用于解密);空 = 无法解密、降级明文 |
|
|
96
99
|
| `autoPullOnStart` | `false` | 插件挂载时拉取一次(配置即授权,不再确认) |
|
|
97
100
|
| `autoPushOnTurnEnd` | `false` | 每个关闭轮次后推送 |
|
|
98
101
|
| `pullIntervalMinutes` | `0` | 每 N 分钟周期拉取(`0` = 关闭,最大 `10080`) |
|
|
@@ -159,7 +162,7 @@ dsh --profile web --dump-config | grep -A2 'id: session-sync'
|
|
|
159
162
|
```sh
|
|
160
163
|
pnpm install # node ^22.19 || >=24
|
|
161
164
|
pnpm run typecheck && pnpm run typecheck:ci # tsc --checkJs,针对已发布的 0.1.1-rc.2 peers
|
|
162
|
-
pnpm test # node --test(
|
|
165
|
+
pnpm test # node --test(12 个测试文件;git 引擎套件在无 git 时跳过)
|
|
163
166
|
pnpm run verify:self-contained # 依赖 spec 可从 registry 解析
|
|
164
167
|
pnpm run verify:artifacts # 发布文件齐全 + index.mjs 可 import
|
|
165
168
|
pnpm run check:readmes # 五语 README 一致性
|
package/cordis.patch.yml
CHANGED
|
@@ -20,8 +20,9 @@
|
|
|
20
20
|
name: dsh-session-sync
|
|
21
21
|
config:
|
|
22
22
|
enabled: true
|
|
23
|
-
# backend: git
|
|
24
|
-
#
|
|
23
|
+
# backend: git = plaintext mirror transport; encrypted = age-encrypted
|
|
24
|
+
# mirror content (encrypt-then-push). 'object-storage' is reserved and
|
|
25
|
+
# fails loud at load.
|
|
25
26
|
backend: git
|
|
26
27
|
# Root of the DSH session store to mirror ('' = $DSH_HOME/sessions).
|
|
27
28
|
sessionRoot: ''
|
|
@@ -31,6 +32,12 @@
|
|
|
31
32
|
remote: ''
|
|
32
33
|
branch: main
|
|
33
34
|
gitBin: git
|
|
35
|
+
# age settings for backend: encrypted. ageBin is probed at first use;
|
|
36
|
+
# missing age / empty ageRecipient / empty ageIdentity degrades to
|
|
37
|
+
# plaintext git with an explicit warning (never hard-depends on age).
|
|
38
|
+
ageBin: age
|
|
39
|
+
ageRecipient: ''
|
|
40
|
+
ageIdentity: ''
|
|
34
41
|
# Auto modes: pull once when the plugin mounts; push after every
|
|
35
42
|
# closed turn; periodic pull every N minutes (0 = off). Auto runs are
|
|
36
43
|
# covered by the config grant and never re-confirm.
|
package/index.mjs
CHANGED
|
@@ -45,6 +45,9 @@ import {
|
|
|
45
45
|
import { assertNestingSafe, resolveRepoDir, resolveSessionRoot } from './lib/paths.mjs'
|
|
46
46
|
import { GitBackend } from './lib/git.mjs'
|
|
47
47
|
import { SyncEngine } from './lib/engine.mjs'
|
|
48
|
+
import { EncryptedBackend, encryptTree, decryptTree, mergeTrees } from './lib/encrypted.mjs'
|
|
49
|
+
import { selectEncryptionMode } from './lib/backend.mjs'
|
|
50
|
+
import { detectAge, ageEncrypt, ageDecrypt } from './lib/age.mjs'
|
|
48
51
|
import { collectStatus } from './lib/status.mjs'
|
|
49
52
|
import { renderDiff, renderPull, renderPush, renderStatus, errorValue } from './lib/render.mjs'
|
|
50
53
|
import { confirmSync, hasOpenTurn, makeEventGate, maybeAppendSessionEvent } from './lib/gate.mjs'
|
|
@@ -92,6 +95,9 @@ export function probeIgnorableAppend() {
|
|
|
92
95
|
* @property {string} [remote] 远端地址(自定义 remote;pull/push 前必须非空,status/diff 不需要)。
|
|
93
96
|
* @property {string} [branch] 远端分支名(默认 main)。
|
|
94
97
|
* @property {string} [gitBin] git 可执行路径(默认 'git')。
|
|
98
|
+
* @property {string} [ageBin] age 可执行路径(默认 'age';backend: encrypted 时探测,缺失降级明文)。
|
|
99
|
+
* @property {string} [ageRecipient] age 收件人(公钥/身份串;空 = 无法加密,降级明文)。
|
|
100
|
+
* @property {string} [ageIdentity] age 身份文件路径(无口令私钥;空 = 无法解密,降级明文)。
|
|
95
101
|
* @property {boolean} [autoPullOnStart] 挂载时自动拉取一次(配置即授权,不再确认)。
|
|
96
102
|
* @property {boolean} [autoPushOnTurnEnd] 每个 turn/end 后自动推送(配置即授权)。
|
|
97
103
|
* @property {number} [pullIntervalMinutes] 周期自动拉取间隔分钟(0 = 关闭)。
|
|
@@ -112,6 +118,9 @@ export const Config = Schema.object({
|
|
|
112
118
|
remote: Schema.string().default(DEFAULTS.REMOTE),
|
|
113
119
|
branch: Schema.string().default(DEFAULTS.BRANCH),
|
|
114
120
|
gitBin: Schema.string().default(DEFAULTS.GIT_BIN),
|
|
121
|
+
ageBin: Schema.string().default(DEFAULTS.AGE_BIN),
|
|
122
|
+
ageRecipient: Schema.string().default(DEFAULTS.AGE_RECIPIENT),
|
|
123
|
+
ageIdentity: Schema.string().default(DEFAULTS.AGE_IDENTITY),
|
|
115
124
|
autoPullOnStart: Schema.boolean().default(DEFAULTS.AUTO_PULL_ON_START),
|
|
116
125
|
autoPushOnTurnEnd: Schema.boolean().default(DEFAULTS.AUTO_PUSH_ON_TURN_END),
|
|
117
126
|
pullIntervalMinutes: Schema.number().default(DEFAULTS.PULL_INTERVAL_MINUTES),
|
|
@@ -139,6 +148,9 @@ export function resolveConfig(config = {}) {
|
|
|
139
148
|
remote: config.remote ?? DEFAULTS.REMOTE,
|
|
140
149
|
branch: config.branch ?? DEFAULTS.BRANCH,
|
|
141
150
|
gitBin: config.gitBin ?? DEFAULTS.GIT_BIN,
|
|
151
|
+
ageBin: config.ageBin ?? DEFAULTS.AGE_BIN,
|
|
152
|
+
ageRecipient: config.ageRecipient ?? DEFAULTS.AGE_RECIPIENT,
|
|
153
|
+
ageIdentity: config.ageIdentity ?? DEFAULTS.AGE_IDENTITY,
|
|
142
154
|
autoPullOnStart: config.autoPullOnStart ?? DEFAULTS.AUTO_PULL_ON_START,
|
|
143
155
|
autoPushOnTurnEnd: config.autoPushOnTurnEnd ?? DEFAULTS.AUTO_PUSH_ON_TURN_END,
|
|
144
156
|
pullIntervalMinutes: config.pullIntervalMinutes ?? DEFAULTS.PULL_INTERVAL_MINUTES,
|
|
@@ -161,6 +173,15 @@ export function resolveConfig(config = {}) {
|
|
|
161
173
|
if (typeof resolved.gitBin !== 'string' || resolved.gitBin.length === 0) {
|
|
162
174
|
throw badConfig('gitBin must be a non-empty string')
|
|
163
175
|
}
|
|
176
|
+
if (typeof resolved.ageBin !== 'string' || resolved.ageBin.length === 0) {
|
|
177
|
+
throw badConfig('ageBin must be a non-empty string')
|
|
178
|
+
}
|
|
179
|
+
if (typeof resolved.ageRecipient !== 'string') {
|
|
180
|
+
throw badConfig('ageRecipient must be a string')
|
|
181
|
+
}
|
|
182
|
+
if (typeof resolved.ageIdentity !== 'string') {
|
|
183
|
+
throw badConfig('ageIdentity must be a string')
|
|
184
|
+
}
|
|
164
185
|
if (typeof resolved.branch !== 'string' || resolved.branch.length === 0 || !/^[A-Za-z0-9._/-]+$/u.test(resolved.branch)) {
|
|
165
186
|
throw badConfig('branch must be a non-empty ref-safe string')
|
|
166
187
|
}
|
|
@@ -254,6 +275,60 @@ export function makeRunGit(subprocess, opts) {
|
|
|
254
275
|
}
|
|
255
276
|
}
|
|
256
277
|
|
|
278
|
+
/**
|
|
279
|
+
* age runner:ctx.subprocess 上的 collect 封装(与 makeRunGit 同构)。
|
|
280
|
+
* args 为「含可执行路径的完整 argv」(lib/age.mjs 的 runner 契约),只做文本
|
|
281
|
+
* 输出收集与退出码/超时/取消语义;age 加解密经文件入参(-o out in),无需 stdin。
|
|
282
|
+
* @param {import('@deepseek-ai/dsh-subprocess').SubprocessRuntime} subprocess - 宿主子进程服务。
|
|
283
|
+
* @param {object} opts - {graceMs, commandTimeoutMs, maxOutputBytes}。
|
|
284
|
+
* @returns {(args: string[], runOpts?: object) => Promise<{code: number, stdout: string, stderr: string}>}
|
|
285
|
+
*/
|
|
286
|
+
export function makeRunAge(subprocess, opts) {
|
|
287
|
+
return async (args, runOpts = {}) => {
|
|
288
|
+
const controller = new AbortController()
|
|
289
|
+
let timedOut = false
|
|
290
|
+
const timer = setTimeout(() => {
|
|
291
|
+
timedOut = true
|
|
292
|
+
controller.abort(new Error(`age ${args[0] ?? ''} timed out after ${opts.commandTimeoutMs}ms`))
|
|
293
|
+
}, opts.commandTimeoutMs)
|
|
294
|
+
const onAbort = () => {
|
|
295
|
+
controller.abort(runOpts.signal?.reason instanceof Error ? runOpts.signal.reason : new Error('sync operation aborted'))
|
|
296
|
+
}
|
|
297
|
+
if (runOpts.signal !== undefined) {
|
|
298
|
+
runOpts.signal.addEventListener('abort', onAbort, { once: true })
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
const executable = await subprocess.resolveExecutable(args[0], undefined, controller.signal)
|
|
302
|
+
const handle = subprocess.spawn({
|
|
303
|
+
argv: [executable, ...args.slice(1)],
|
|
304
|
+
cwd: runOpts.cwd,
|
|
305
|
+
stdio: {
|
|
306
|
+
stdin: 'ignore',
|
|
307
|
+
stdout: { maxBytes: opts.maxOutputBytes },
|
|
308
|
+
stderr: { maxBytes: opts.maxOutputBytes },
|
|
309
|
+
},
|
|
310
|
+
graceMs: opts.graceMs,
|
|
311
|
+
signal: controller.signal,
|
|
312
|
+
})
|
|
313
|
+
const outcome = await handle.done
|
|
314
|
+
if (timedOut) {
|
|
315
|
+
throw new Error(`age ${args[0] ?? ''} timed out after ${opts.commandTimeoutMs}ms`)
|
|
316
|
+
}
|
|
317
|
+
if (runOpts.signal?.aborted === true) {
|
|
318
|
+
throw runOpts.signal.reason instanceof Error ? runOpts.signal.reason : new Error('sync operation aborted')
|
|
319
|
+
}
|
|
320
|
+
const stdout = handle.collected.stdout.readFrom(0).text
|
|
321
|
+
const stderr = handle.collected.stderr.readFrom(0).text
|
|
322
|
+
return { code: outcome.exitCode ?? (outcome.signal !== null ? 128 : 0), stdout, stderr }
|
|
323
|
+
} finally {
|
|
324
|
+
clearTimeout(timer)
|
|
325
|
+
if (runOpts.signal !== undefined) {
|
|
326
|
+
runOpts.signal.removeEventListener('abort', onAbort)
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
257
332
|
/**
|
|
258
333
|
* 工具参数/输出描述(双语)。
|
|
259
334
|
*/
|
|
@@ -266,13 +341,13 @@ const TOOL_TEXT = {
|
|
|
266
341
|
}
|
|
267
342
|
|
|
268
343
|
/** sync_status 工具规范结果(与工具 schema 同构)。 */
|
|
269
|
-
/** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string}} StatusValue */
|
|
270
|
-
/** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string}} PullValue */
|
|
271
|
-
/** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string}} PushValue */
|
|
344
|
+
/** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string, warnings?: string[]}} StatusValue */
|
|
345
|
+
/** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string, warnings?: string[]}} PullValue */
|
|
346
|
+
/** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string, warnings?: string[]}} PushValue */
|
|
272
347
|
|
|
273
348
|
/**
|
|
274
349
|
* sync_status 工具定义(read-only:不确认、不触网)。
|
|
275
|
-
* @param {
|
|
350
|
+
* @param {{status: () => Promise<object>}} engine - 同步引擎(git 或 encrypted 后端同一 surface)。
|
|
276
351
|
* @param {() => Promise<object>} readMeta - 元数据读取。
|
|
277
352
|
* @returns {object} 工具定义。
|
|
278
353
|
*/
|
|
@@ -302,6 +377,7 @@ export function makeSyncStatusTool(engine, readMeta) {
|
|
|
302
377
|
lastPushAt: { type: 'integer' },
|
|
303
378
|
lastError: { type: 'string' },
|
|
304
379
|
error: { type: 'string' },
|
|
380
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
305
381
|
},
|
|
306
382
|
},
|
|
307
383
|
render(_args, value) {
|
|
@@ -345,6 +421,7 @@ export function makeSyncPullTool(deps) {
|
|
|
345
421
|
forks: { type: 'array', items: { type: 'string' } },
|
|
346
422
|
head: { type: 'string' },
|
|
347
423
|
error: { type: 'string' },
|
|
424
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
348
425
|
},
|
|
349
426
|
},
|
|
350
427
|
render(_args, value) {
|
|
@@ -403,6 +480,7 @@ export function makeSyncPushTool(deps) {
|
|
|
403
480
|
deleted: { type: 'integer' },
|
|
404
481
|
remote: { type: 'string' },
|
|
405
482
|
error: { type: 'string' },
|
|
483
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
406
484
|
},
|
|
407
485
|
},
|
|
408
486
|
render(_args, value) {
|
|
@@ -530,7 +608,7 @@ export function apply(ctx, config = {}) {
|
|
|
530
608
|
reportMeta({ lastError: message.slice(0, 500) })
|
|
531
609
|
}
|
|
532
610
|
|
|
533
|
-
// --- git 后端 +
|
|
611
|
+
// --- git 后端 + 引擎(backend seam:git = 明文,encrypted = age 加密的 git)。
|
|
534
612
|
const git = new GitBackend({
|
|
535
613
|
repoDir,
|
|
536
614
|
remote: resolved.remote,
|
|
@@ -546,7 +624,7 @@ export function apply(ctx, config = {}) {
|
|
|
546
624
|
timeoutMs: resolved.commandTimeoutMs,
|
|
547
625
|
})
|
|
548
626
|
|
|
549
|
-
const
|
|
627
|
+
const engineDeps = {
|
|
550
628
|
git,
|
|
551
629
|
sessionRoot,
|
|
552
630
|
repoDir,
|
|
@@ -557,7 +635,21 @@ export function apply(ctx, config = {}) {
|
|
|
557
635
|
reportError,
|
|
558
636
|
logger,
|
|
559
637
|
onForks: (forkPaths) => handleForks(forkPaths),
|
|
560
|
-
}
|
|
638
|
+
}
|
|
639
|
+
const engine = resolved.backend === BACKENDS.ENCRYPTED
|
|
640
|
+
? new EncryptedBackend({
|
|
641
|
+
...engineDeps,
|
|
642
|
+
run: makeRunAge(ctx.subprocess, {
|
|
643
|
+
graceMs: resolved.graceMs,
|
|
644
|
+
commandTimeoutMs: resolved.commandTimeoutMs,
|
|
645
|
+
maxOutputBytes: resolved.maxOutputBytes,
|
|
646
|
+
}),
|
|
647
|
+
ageBin: resolved.ageBin,
|
|
648
|
+
ageRecipient: resolved.ageRecipient,
|
|
649
|
+
ageIdentity: resolved.ageIdentity,
|
|
650
|
+
timeoutMs: resolved.commandTimeoutMs,
|
|
651
|
+
})
|
|
652
|
+
: new SyncEngine(engineDeps)
|
|
561
653
|
// 设备 id 来自元数据领域;在领域就绪后补齐(fork 命名/设备文件用)。
|
|
562
654
|
void ensureMeta().then((meta) => {
|
|
563
655
|
engine.deviceId = meta.deviceId
|
|
@@ -759,6 +851,14 @@ export {
|
|
|
759
851
|
// 复用/测试面:引擎、后端、纯函数与词汇。
|
|
760
852
|
GitBackend,
|
|
761
853
|
SyncEngine,
|
|
854
|
+
EncryptedBackend,
|
|
855
|
+
selectEncryptionMode,
|
|
856
|
+
detectAge,
|
|
857
|
+
ageEncrypt,
|
|
858
|
+
ageDecrypt,
|
|
859
|
+
encryptTree,
|
|
860
|
+
decryptTree,
|
|
861
|
+
mergeTrees,
|
|
762
862
|
collectStatus,
|
|
763
863
|
renderStatus,
|
|
764
864
|
renderDiff,
|
package/lib/age.mjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// lib/age.mjs — age 二进制探测与加解密(零 DSH 依赖)。
|
|
2
|
+
//
|
|
3
|
+
// age 是「探测 → 使用 → 优雅降级」的可选外部二进制:encrypted 后端在 resolve
|
|
4
|
+
// 期探测其是否存在,缺 age/缺 recipient/identity 时降级为明文 git 并显式警告,
|
|
5
|
+
// 绝不硬依赖 age。操作期(encrypted 模式下)加解密失败一律 fail closed
|
|
6
|
+
// (AGE_FAILED),绝不静默回退成明文传输。
|
|
7
|
+
//
|
|
8
|
+
// runner 契约(与 git 一致,但 args 为「含可执行路径的完整 argv」):
|
|
9
|
+
// run(args, { cwd, timeoutMs, signal, binary, maxBytes }) → { code, stdout, stderr }
|
|
10
|
+
// args[0] 为 age 可执行路径,其余为 age 参数。
|
|
11
|
+
|
|
12
|
+
import { redactText } from './sanitize.mjs'
|
|
13
|
+
import { ageFailed } from './errors.mjs'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 探测 age:`age --version` 退出 0 → 返回配置的二进制路径;否则(含 runner
|
|
17
|
+
* 抛错)返回 null。纯探测,不抛错——调用方据此降级。
|
|
18
|
+
* @param {(args: string[], opts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>} run - 子进程 runner。
|
|
19
|
+
* @param {string} [ageBin] - age 可执行路径(默认 'age')。
|
|
20
|
+
* @param {{timeoutMs?: number, cwd?: string}} [opts] - 探测参数。
|
|
21
|
+
* @returns {Promise<string|null>} 二进制路径或 null。
|
|
22
|
+
*/
|
|
23
|
+
export async function detectAge(run, ageBin = 'age', opts = {}) {
|
|
24
|
+
if (typeof ageBin !== 'string' || ageBin.length === 0) return null
|
|
25
|
+
try {
|
|
26
|
+
const result = await run([ageBin, '--version'], { timeoutMs: opts.timeoutMs, cwd: opts.cwd })
|
|
27
|
+
return result.code === 0 ? ageBin : null
|
|
28
|
+
} catch {
|
|
29
|
+
return null
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 执行一条 age 命令并把失败包成 AGE_FAILED(stderr 尾部脱敏嵌入)。
|
|
35
|
+
* @param {(args: string[], opts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>} run - 子进程 runner。
|
|
36
|
+
* @param {string[]} args - 完整 argv(含可执行路径)。
|
|
37
|
+
* @param {{cwd?: string, timeoutMs?: number}} [opts] - 命令参数。
|
|
38
|
+
* @returns {Promise<{code: number, stdout: string|Buffer, stderr: string}>}
|
|
39
|
+
*/
|
|
40
|
+
async function runAge(run, args, opts = {}) {
|
|
41
|
+
let result
|
|
42
|
+
try {
|
|
43
|
+
result = await run(args, { cwd: opts.cwd, timeoutMs: opts.timeoutMs })
|
|
44
|
+
} catch (error) {
|
|
45
|
+
throw ageFailed(args[0] ?? 'age', redactText(error instanceof Error ? error.message : String(error)))
|
|
46
|
+
}
|
|
47
|
+
if (result.code !== 0) {
|
|
48
|
+
const tail = redactText(String(result.stderr ?? '')).trim().split('\n').slice(-3).join(' | ') || `exit ${result.code}`
|
|
49
|
+
throw ageFailed(args[0] ?? 'age', tail)
|
|
50
|
+
}
|
|
51
|
+
return result
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* age 加密单个明文文件 → 密文文件:`age -r <recipient> -o <out> <in>`。
|
|
56
|
+
* 文件入参(非 stdin)避免写管道的宿主限制;身份文件无需、不触网。
|
|
57
|
+
* @param {(args: string[], opts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>} run - 子进程 runner。
|
|
58
|
+
* @param {object} deps - {ageBin, recipient, inPath, outPath, timeoutMs?, cwd?}。
|
|
59
|
+
* @returns {Promise<string>} 密文输出路径。
|
|
60
|
+
*/
|
|
61
|
+
export async function ageEncrypt(run, deps) {
|
|
62
|
+
await runAge(run, [deps.ageBin, '-r', deps.recipient, '-o', deps.outPath, deps.inPath], deps)
|
|
63
|
+
return deps.outPath
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* age 解密密文文件 → 明文文件:`age -d -i <identity> -o <out> <in>`。
|
|
68
|
+
* 身份文件必须是「无口令」的 age 私钥(有口令会走 TTY 提示;stdin 已 ignore,
|
|
69
|
+
* 将立即失败——这是 fail-closed 的预期行为,用户需用无口令身份文件)。
|
|
70
|
+
* @param {(args: string[], opts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>} run - 子进程 runner。
|
|
71
|
+
* @param {object} deps - {ageBin, identity, inPath, outPath, timeoutMs?, cwd?}。
|
|
72
|
+
* @returns {Promise<string>} 明文输出路径。
|
|
73
|
+
*/
|
|
74
|
+
export async function ageDecrypt(run, deps) {
|
|
75
|
+
await runAge(run, [deps.ageBin, '-d', '-i', deps.identity, '-o', deps.outPath, deps.inPath], deps)
|
|
76
|
+
return deps.outPath
|
|
77
|
+
}
|
package/lib/backend.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// lib/backend.mjs — 传输后端 seam(零依赖)。
|
|
2
|
+
//
|
|
3
|
+
// Backend 契约(三类传输后端共享同一 surface;本次落地 git 与 encrypted,
|
|
4
|
+
// 对象存储 object-storage 为接口占位,配置即 resolveConfig 响亮失败):
|
|
5
|
+
//
|
|
6
|
+
// kind : 'git' | 'encrypted' | 'object-storage' —— 语义后端
|
|
7
|
+
// mode : 'plaintext' | 'encrypted' —— 实际生效的传输模式
|
|
8
|
+
// warnings : string[] —— 降级/边界警告(进入
|
|
9
|
+
// status/push/pull 结果)
|
|
10
|
+
// status() -> StatusValue
|
|
11
|
+
// push(opts) -> PushValue
|
|
12
|
+
// pull(opts) -> PullValue
|
|
13
|
+
//
|
|
14
|
+
// git(GitBackend + SyncEngine)为明文内置实现;encrypted(lib/encrypted.mjs)
|
|
15
|
+
// 为 age 包装的 git 传输(镜像内容加密后再推、解密后再合并);object-storage
|
|
16
|
+
// 无实现——只有契约与常量占位。
|
|
17
|
+
|
|
18
|
+
import { BACKENDS } from './constants.mjs'
|
|
19
|
+
|
|
20
|
+
/** 传输模式词汇。 */
|
|
21
|
+
export const BACKEND_MODES = Object.freeze({
|
|
22
|
+
PLAINTEXT: 'plaintext',
|
|
23
|
+
ENCRYPTED: 'encrypted',
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 选择 encrypted 后端实际生效的传输模式(纯函数;探测结果经参数注入,便于测试)。
|
|
28
|
+
*
|
|
29
|
+
* 降级规则(任一不满足即回退明文 git 并给出显式警告,绝不静默降级):
|
|
30
|
+
* - backend !== 'encrypted' → 明文(无警告);
|
|
31
|
+
* - age 二进制不可用 → 明文 + 警告;
|
|
32
|
+
* - ageRecipient 为空 → 明文 + 警告(无法加密);
|
|
33
|
+
* - ageIdentity 为空 → 明文 + 警告(无法解密)。
|
|
34
|
+
*
|
|
35
|
+
* @param {object} deps - {backend, ageAvailable, ageRecipient, ageIdentity}。
|
|
36
|
+
* @param {string} deps.backend - BACKENDS 之一。
|
|
37
|
+
* @param {boolean} deps.ageAvailable - detectAge 是否探测到 age 二进制。
|
|
38
|
+
* @param {string} deps.ageRecipient - age 收件人(公钥/身份串)。
|
|
39
|
+
* @param {string} deps.ageIdentity - age 身份文件路径(解密私钥)。
|
|
40
|
+
* @returns {{mode: 'plaintext'|'encrypted', warnings: string[]}}
|
|
41
|
+
*/
|
|
42
|
+
export function selectEncryptionMode({ backend, ageAvailable, ageRecipient, ageIdentity }) {
|
|
43
|
+
if (backend !== BACKENDS.ENCRYPTED) return { mode: BACKEND_MODES.PLAINTEXT, warnings: [] }
|
|
44
|
+
const warnings = []
|
|
45
|
+
if (ageAvailable !== true) {
|
|
46
|
+
warnings.push('age binary not found (probed `age --version`); mirror content will be pushed unencrypted')
|
|
47
|
+
} else {
|
|
48
|
+
if (typeof ageRecipient !== 'string' || ageRecipient.trim() === '') {
|
|
49
|
+
warnings.push('ageRecipient is empty; mirror content will be pushed unencrypted')
|
|
50
|
+
}
|
|
51
|
+
if (typeof ageIdentity !== 'string' || ageIdentity.trim() === '') {
|
|
52
|
+
warnings.push('ageIdentity is empty; mirror content will be pushed unencrypted')
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const mode = warnings.length === 0 ? BACKEND_MODES.ENCRYPTED : BACKEND_MODES.PLAINTEXT
|
|
56
|
+
return { mode, warnings }
|
|
57
|
+
}
|