dsh-config-manager 0.4.1 → 0.4.2
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/lib/cli/actions.js +2 -3
- package/lib/cli/import-source.js +2 -6
- package/lib/cli/index.js +2 -3
- package/lib/client.d.ts +0 -5
- package/lib/client.js +26116 -25801
- package/lib/core/exporter.js +2 -4
- package/lib/core/host-schedulers/cache-cleanup.d.ts +41 -0
- package/lib/core/host-schedulers/cache-cleanup.js +45 -0
- package/lib/core/host-schedulers/lifecycle-hooks.d.ts +51 -0
- package/lib/core/host-schedulers/lifecycle-hooks.js +78 -0
- package/lib/core/host-schedulers/market-cache.d.ts +40 -0
- package/lib/core/host-schedulers/market-cache.js +92 -0
- package/lib/core/model-tools.js +2 -6
- package/lib/core/restore.d.ts +0 -2
- package/lib/core/restore.js +16 -18
- package/lib/core/verify-recovery.js +4 -7
- package/lib/index.d.ts +3 -22
- package/lib/index.js +69 -325
- package/lib/profiles/dsh-profile-manager.d.ts +23 -1
- package/lib/profiles/dsh-profile-manager.js +70 -2
- package/lib/routes/kit.d.ts +21 -0
- package/lib/routes/kit.js +29 -0
- package/lib/routes/prefs.js +6 -6
- package/lib/routes/recovery.js +25 -41
- package/lib/routes/route-support.d.ts +23 -1
- package/lib/routes/route-support.js +185 -0
- package/lib/routes/snapshots.js +4 -11
- package/lib/routes/sync.js +5 -7
- package/lib/security/redaction.d.ts +5 -1
- package/lib/security/redaction.js +26 -23
- package/lib/sync/backup-scheduler.js +2 -6
- package/lib/ui/backup-inspect.d.ts +1 -1
- package/lib/ui/dsh-profiles-view.d.ts +0 -10
- package/lib/ui/dsh-profiles-view.js +3 -7
- package/lib/ui/snapshots-view.d.ts +0 -14
- package/lib/ui/snapshots-view.js +16 -2
- package/lib/utils/paths.d.ts +20 -4
- package/lib/utils/paths.js +22 -6
- package/lib/utils/time.d.ts +31 -0
- package/lib/utils/time.js +54 -0
- package/package.json +1 -1
- package/src/cli/actions.ts +2 -3
- package/src/cli/import-source.ts +2 -7
- package/src/cli/index.ts +2 -3
- package/src/client/about/AboutPanel.tsx +1 -1
- package/src/client/about/ReleaseBody.tsx +22 -52
- package/src/client/about/ReleaseNotesDialog.tsx +15 -69
- package/src/client/about/release-notes-view.ts +4 -11
- package/src/client/common/info-hint-guard.test.ts +11 -5
- package/src/client/common/ui.tsx +23 -0
- package/src/client/config-manager.module.css +201 -32
- package/src/client/css-token-guard.test.ts +135 -1
- package/src/client/import/ConflictList.tsx +3 -3
- package/src/client/import/ImportWizardView.tsx +1 -1
- package/src/client/library/ArtifactRow.tsx +2 -2
- package/src/client/library/RestorePlanView.tsx +21 -9
- package/src/client/library/report-dismiss.test.ts +5 -3
- package/src/client/locales/about.ts +97 -0
- package/src/client/locales/backup.ts +141 -0
- package/src/client/locales/common.ts +113 -0
- package/src/client/locales/export.ts +184 -0
- package/src/client/locales/foreign.ts +184 -0
- package/src/client/locales/import-compat.ts +32 -0
- package/src/client/locales/import.ts +192 -0
- package/src/client/locales/next-steps.ts +25 -0
- package/src/client/locales/overview-control.ts +32 -0
- package/src/client/locales/overview.ts +145 -0
- package/src/client/locales/profiles.ts +263 -0
- package/src/client/locales/report.ts +17 -0
- package/src/client/locales/restore.ts +132 -0
- package/src/client/locales/sessions.ts +257 -0
- package/src/client/locales/shell.ts +149 -0
- package/src/client/locales.ts +49 -1783
- package/src/client/market/MarketImportReview.tsx +2 -2
- package/src/client/market/MarketPanel.tsx +1 -1
- package/src/client/market/market-view.ts +3 -5
- package/src/client/recovery/RecoveryPanel.tsx +62 -1054
- package/src/client/recovery/SessionHealthCard.tsx +134 -0
- package/src/client/recovery/SessionHealthDialog.tsx +665 -0
- package/src/client/recovery/SessionLayoutSection.tsx +284 -0
- package/src/client/recovery/recovery-api.ts +10 -1
- package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
- package/src/client/recovery/session-dialog-mount.test.ts +16 -9
- package/src/client/recovery/use-recovery-write.test.ts +90 -0
- package/src/client/recovery/use-recovery-write.ts +53 -0
- package/src/client/run-store.ts +57 -2
- package/src/client/sync/PushPreviewCard.tsx +2 -2
- package/src/client/sync/SyncConfirmView.tsx +5 -5
- package/src/client/sync/SyncLogList.tsx +2 -2
- package/src/client/sync/history-model.ts +4 -5
- package/src/client/sync/sync-view.ts +3 -4
- package/src/core/exporter.ts +2 -4
- package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
- package/src/core/host-schedulers/cache-cleanup.ts +74 -0
- package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
- package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
- package/src/core/host-schedulers/market-cache.test.ts +93 -0
- package/src/core/host-schedulers/market-cache.ts +116 -0
- package/src/core/model-tools.ts +2 -7
- package/src/core/restore-failure-state.test.ts +210 -0
- package/src/core/restore.ts +16 -18
- package/src/core/verify-recovery.ts +4 -7
- package/src/index.ts +76 -330
- package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
- package/src/profiles/dsh-profile-manager.ts +71 -3
- package/src/routes/kit.ts +37 -0
- package/src/routes/prefs.ts +6 -6
- package/src/routes/recovery.ts +25 -42
- package/src/routes/route-support.ts +208 -1
- package/src/routes/snapshots.ts +4 -9
- package/src/routes/sync.ts +4 -7
- package/src/security/redaction.ts +29 -23
- package/src/sync/backup-scheduler.ts +3 -6
- package/src/sync/sync-config.test.ts +24 -13
- package/src/ui/backup-inspect.ts +1 -1
- package/src/ui/dsh-profiles-view.ts +3 -5
- package/src/ui/i18n.test.ts +8 -3
- package/src/ui/snapshots-view.ts +2 -2
- package/src/utils/paths.test.ts +36 -1
- package/src/utils/paths.ts +30 -6
- package/src/utils/time.test.ts +46 -0
- package/src/utils/time.ts +55 -0
|
@@ -28,13 +28,15 @@ import { collectCredentialRefs } from '../security/credentials-yaml.ts'
|
|
|
28
28
|
import { decryptCredentials, SecurityError } from '../security/index.ts'
|
|
29
29
|
import type { Manifest, SectionId } from '../schema/types.ts'
|
|
30
30
|
import type { HostContext, ImportPlan, PlanItemKind } from '../core/types.ts'
|
|
31
|
+
import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
|
|
31
32
|
import { engineMsg } from '../core/engine-locale.ts'
|
|
32
33
|
import { createPreRestoreAttemptDir } from '../core/restore.ts'
|
|
33
34
|
import type { RestoreActionKind, RestorePlan, RestoreReport } from '../core/restore.ts'
|
|
34
35
|
import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
|
|
35
36
|
import type { RestoreResumeHint } from '../core/restore-resume.ts'
|
|
36
37
|
import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
|
|
37
|
-
import type { SyncTransportType } from '../sync/sync-config.ts'
|
|
38
|
+
import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts'
|
|
39
|
+
import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.ts'
|
|
38
40
|
import { DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, lastRunFailureMessage, readAllAutosyncConfigs, readAutosyncConfig } from '../sync/autosync-config.ts'
|
|
39
41
|
import type { AutosyncAutoApplyTier, AutosyncConflictPolicy, AutosyncInterval, AutosyncRunStatus } from '../sync/autosync-config.ts'
|
|
40
42
|
import { SYNC_CHANNELS } from '../sync/sync-config.ts'
|
|
@@ -733,3 +735,208 @@ export function makeRestoreExecutor(snapshotDir: string, host: HostContext, prof
|
|
|
733
735
|
},
|
|
734
736
|
}
|
|
735
737
|
}
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
/* ------------------------------------------- 同步通道请求体解析(tech-debt #23 下沉)
|
|
741
|
+
*
|
|
742
|
+
* 原在 src/index.ts 的宿主组合根里,但它们是**不依赖组合根状态**的纯解析:
|
|
743
|
+
* body → 归一化 SyncConfig(可辨识联合)+ 密钥只写 DSH credentials 槽位。
|
|
744
|
+
* 下沉后 `src/index.sync.test.ts` 仍经组合根的再导出取用(符号名不变)。
|
|
745
|
+
*/
|
|
746
|
+
|
|
747
|
+
/** parseSyncBody 的凭据写入依赖(只用到 set;测试可注入内存 mock)。 */
|
|
748
|
+
export interface ParseSyncBodyDeps {
|
|
749
|
+
credentials: Pick<CredentialProvider, 'set'>
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
|
|
754
|
+
* 请求体形状(flat,M4 契约):
|
|
755
|
+
* - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
|
|
756
|
+
* git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
|
|
757
|
+
* - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
|
|
758
|
+
* 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
|
|
759
|
+
*/
|
|
760
|
+
export async function parseSyncBody(
|
|
761
|
+
body: Record<string, unknown>,
|
|
762
|
+
deps: ParseSyncBodyDeps,
|
|
763
|
+
): Promise<SyncConfig> {
|
|
764
|
+
const rawTransport = body['transport']
|
|
765
|
+
// 通道值解析:接受通道名(s3/gist);也接受**具体兼容商**(oss/cos/minio/kodo)直接落到 s3 通道
|
|
766
|
+
const transport = parseSyncChannel(rawTransport) ?? (isS3CompatProvider(rawTransport) ? 's3' : 'git')
|
|
767
|
+
if (transport === 's3') return parseCloudS3Body(body, rawTransport, deps)
|
|
768
|
+
if (transport === 'gist') return parseCloudGistBody(body, deps)
|
|
769
|
+
if (transport === 'webdav') {
|
|
770
|
+
const url = typeof body['url'] === 'string' ? body['url'].trim() : ''
|
|
771
|
+
if (url === '') throw new SyncRouteError('url is required for webdav')
|
|
772
|
+
const urlError = validateWebDavUrl(url)
|
|
773
|
+
if (urlError !== null) throw new SyncRouteError(urlError)
|
|
774
|
+
const username = typeof body['username'] === 'string' && body['username'] !== '' ? body['username'] : undefined
|
|
775
|
+
const password = typeof body['password'] === 'string' && body['password'] !== '' ? body['password'] : undefined
|
|
776
|
+
if (password !== undefined) {
|
|
777
|
+
try {
|
|
778
|
+
await deps.credentials.set(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF), password)
|
|
779
|
+
} catch (error) {
|
|
780
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
781
|
+
throw new SyncRouteError(
|
|
782
|
+
engineMsg('host.syncWebdavPasswordWriteFailed', { reason, ref: SYNC_WEBDAV_CREDENTIAL_REF }),
|
|
783
|
+
)
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return {
|
|
787
|
+
schemaVersion: 2,
|
|
788
|
+
transport: 'webdav',
|
|
789
|
+
webdav: { url, ...(username !== undefined ? { username } : {}) },
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// git 通道(沿用现有逻辑)
|
|
793
|
+
const repoUrl = typeof body['repoUrl'] === 'string' ? body['repoUrl'].trim() : ''
|
|
794
|
+
if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
|
|
795
|
+
const urlError = validateRepoUrl(repoUrl)
|
|
796
|
+
if (urlError !== null) throw new SyncRouteError(urlError)
|
|
797
|
+
const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
|
|
798
|
+
if (token !== undefined) {
|
|
799
|
+
try {
|
|
800
|
+
await deps.credentials.set(credentialRef(SYNC_CREDENTIAL_REF), token)
|
|
801
|
+
} catch (error) {
|
|
802
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
803
|
+
throw new SyncRouteError(
|
|
804
|
+
engineMsg('host.syncTokenWriteFailed', { reason, ref: SYNC_CREDENTIAL_REF }),
|
|
805
|
+
)
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return {
|
|
809
|
+
schemaVersion: 2,
|
|
810
|
+
transport: 'git',
|
|
811
|
+
git: { repoUrl },
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** 请求体字段 → 去空白字符串(非字符串 = 空)。 */
|
|
816
|
+
function syncStr(value: unknown): string {
|
|
817
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** 云端点密钥写入失败 → 可操作错误(**含 ref 名、绝不含密钥值**)。 */
|
|
821
|
+
function cloudCredentialWriteError(ref: string, kind: string, error: unknown): SyncRouteError {
|
|
822
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
823
|
+
return new SyncRouteError(
|
|
824
|
+
engineMsg('host.syncCredentialWriteFailed', { kind, reason, ref }),
|
|
825
|
+
400,
|
|
826
|
+
'cloud.credentialsWriteFailed',
|
|
827
|
+
)
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* s3 通道请求体 → SyncConfig(provider 必填或由 transport 直接给出)。
|
|
832
|
+
* 非密字段按 validateCloudChannelInput 校验(错误码 = HTTP body.code,由 UI 映射字典);
|
|
833
|
+
* 密钥**只写**进 DSH credentials 的 cloudSecretRef(provider) 槽位,绝不进返回值 / 文件 / 日志。
|
|
834
|
+
*/
|
|
835
|
+
async function parseCloudS3Body(
|
|
836
|
+
body: Record<string, unknown>,
|
|
837
|
+
rawTransport: unknown,
|
|
838
|
+
deps: ParseSyncBodyDeps,
|
|
839
|
+
): Promise<SyncConfig> {
|
|
840
|
+
const provider = isS3CompatProvider(body['provider'])
|
|
841
|
+
? body['provider']
|
|
842
|
+
: (isS3CompatProvider(rawTransport) ? rawTransport : null)
|
|
843
|
+
if (provider === null) {
|
|
844
|
+
throw new SyncRouteError('provider is required for s3 (s3/oss/cos/minio/kodo)', 400, 'cloud.providerUnknown')
|
|
845
|
+
}
|
|
846
|
+
const endpoint = syncStr(body['endpoint']).replace(/\/+$/, '')
|
|
847
|
+
const region = syncStr(body['region'])
|
|
848
|
+
const bucket = syncStr(body['bucket'])
|
|
849
|
+
const accessKeyId = syncStr(body['accessKeyId'])
|
|
850
|
+
const prefix = syncStr(body['prefix'])
|
|
851
|
+
const pathStyle = typeof body['pathStyle'] === 'boolean' ? body['pathStyle'] : undefined
|
|
852
|
+
const dialectId = body['dialectId'] === 'aws4' || body['dialectId'] === 'oss4' ? body['dialectId'] : undefined
|
|
853
|
+
const issue = validateCloudChannelInput(provider, {
|
|
854
|
+
endpoint,
|
|
855
|
+
region,
|
|
856
|
+
bucket,
|
|
857
|
+
accessKeyId,
|
|
858
|
+
...(prefix === '' ? {} : { prefix }),
|
|
859
|
+
...(pathStyle === undefined ? {} : { pathStyle }),
|
|
860
|
+
...(dialectId === undefined ? {} : { dialectId }),
|
|
861
|
+
})
|
|
862
|
+
if (issue !== null) throw new SyncRouteError(issue, 400, issue)
|
|
863
|
+
const secret = typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined
|
|
864
|
+
if (secret !== undefined) {
|
|
865
|
+
const ref = cloudSecretRef(provider)
|
|
866
|
+
try {
|
|
867
|
+
await deps.credentials.set(credentialRef(ref), secret)
|
|
868
|
+
} catch (error) {
|
|
869
|
+
throw cloudCredentialWriteError(ref, engineMsg('host.syncKindS3Secret'), error)
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
return {
|
|
873
|
+
schemaVersion: 2,
|
|
874
|
+
transport: 's3',
|
|
875
|
+
s3: {
|
|
876
|
+
provider,
|
|
877
|
+
endpoint,
|
|
878
|
+
region,
|
|
879
|
+
bucket,
|
|
880
|
+
accessKeyId,
|
|
881
|
+
...(prefix === '' ? {} : { prefix }),
|
|
882
|
+
...(pathStyle === undefined ? {} : { pathStyle }),
|
|
883
|
+
...(dialectId === undefined ? {} : { dialectId }),
|
|
884
|
+
},
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/**
|
|
889
|
+
* gist 通道请求体 → SyncConfig。token 只写进 cloudSecretRef('gist') 槽位
|
|
890
|
+
* (请求体字段名 token 或 secret 都接受;值绝不进返回值 / 文件 / 日志)。
|
|
891
|
+
*/
|
|
892
|
+
async function parseCloudGistBody(body: Record<string, unknown>, deps: ParseSyncBodyDeps): Promise<SyncConfig> {
|
|
893
|
+
const gistId = syncStr(body['gistId'])
|
|
894
|
+
const apiBaseUrl = syncStr(body['apiBaseUrl'])
|
|
895
|
+
const filePrefix = syncStr(body['filePrefix'])
|
|
896
|
+
const issue = validateCloudChannelInput(GIST_PROVIDER, {
|
|
897
|
+
gistId,
|
|
898
|
+
...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
|
|
899
|
+
...(filePrefix === '' ? {} : { filePrefix }),
|
|
900
|
+
})
|
|
901
|
+
if (issue !== null) throw new SyncRouteError(issue, 400, issue)
|
|
902
|
+
const token = typeof body['token'] === 'string' && body['token'] !== ''
|
|
903
|
+
? body['token']
|
|
904
|
+
: (typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined)
|
|
905
|
+
if (token !== undefined) {
|
|
906
|
+
const ref = cloudSecretRef(GIST_PROVIDER)
|
|
907
|
+
try {
|
|
908
|
+
await deps.credentials.set(credentialRef(ref), token)
|
|
909
|
+
} catch (error) {
|
|
910
|
+
throw cloudCredentialWriteError(ref, 'Gist token', error)
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
return {
|
|
914
|
+
schemaVersion: 2,
|
|
915
|
+
transport: 'gist',
|
|
916
|
+
gist: {
|
|
917
|
+
gistId,
|
|
918
|
+
...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
|
|
919
|
+
...(filePrefix === '' ? {} : { filePrefix }),
|
|
920
|
+
},
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/** 由 SyncConfig 合成 WebDAV 通道 baseUrl(webdav.url,尾部规范化带 '/';git 通道返回 '')。 */
|
|
925
|
+
export function webdavBaseUrl(cfg: SyncConfig): string {
|
|
926
|
+
if (!isWebDavConfig(cfg)) return ''
|
|
927
|
+
return cfg.webdav.url.replace(/\/+$/, '') + '/'
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* 补全 webdav 配置缺失的 username(从持久化配置回填;纯函数,不修改入参)。
|
|
932
|
+
* 语义与 password 一致:请求未带 username(表单留空/挂载自动加载)→ 沿用已保存的值;
|
|
933
|
+
* 请求显式带 username → 原样保留(用户新输入优先)。非 webdav / 无持久化 → 原样返回。
|
|
934
|
+
*/
|
|
935
|
+
export function mergePersistedWebDavUsername(cfg: SyncConfig, persisted: SyncConfig | null): SyncConfig {
|
|
936
|
+
if (!isWebDavConfig(cfg) || (cfg.webdav.username !== undefined && cfg.webdav.username !== '')) return cfg
|
|
937
|
+
if (persisted !== null && isWebDavConfig(persisted)
|
|
938
|
+
&& typeof persisted.webdav.username === 'string' && persisted.webdav.username !== '') {
|
|
939
|
+
return { ...cfg, webdav: { ...cfg.webdav, username: persisted.webdav.username } }
|
|
940
|
+
}
|
|
941
|
+
return cfg
|
|
942
|
+
}
|
package/src/routes/snapshots.ts
CHANGED
|
@@ -5,10 +5,9 @@
|
|
|
5
5
|
* path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { endpoint, readJsonBody, writeJson } from './kit.ts'
|
|
8
|
+
import { endpoint, readJsonBody, writeJson, writeMutationError } from './kit.ts'
|
|
9
9
|
import type { WebRoute } from './kit.ts'
|
|
10
10
|
import type { RoutesEnv } from './context.ts'
|
|
11
|
-
import { TransactionRecoveryRequiredError } from '../core/phase3-host.ts'
|
|
12
11
|
import { deleteSnapshot, isValidSnapshotId, listSnapshots, planRestore, setSnapshotPinned } from '../core/restore.ts'
|
|
13
12
|
import type { RunState } from '../core/run-registry.ts'
|
|
14
13
|
import { snapshotFileDiff, summarizeRestoreChanges } from '../core/snapshot-diff.ts'
|
|
@@ -16,7 +15,7 @@ import { buildFileDiffBody, buildRestoreBody, executeRestorePlan, makeRestoreExe
|
|
|
16
15
|
import type { RestoreJournalPort } from '../core/restore-wal.ts'
|
|
17
16
|
import { probeRestoreResume, runRestoreWithResume } from '../core/restore-resume.ts'
|
|
18
17
|
import type { RestoreResumeHint } from '../core/restore-resume.ts'
|
|
19
|
-
import {
|
|
18
|
+
import { runWithMutationLock } from '../utils/env-lock.ts'
|
|
20
19
|
import { isENOENT } from '../utils/guards.ts'
|
|
21
20
|
import { join } from 'node:path'
|
|
22
21
|
import { createHash } from 'node:crypto'
|
|
@@ -205,12 +204,8 @@ export function snapshotRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
205
204
|
}
|
|
206
205
|
})
|
|
207
206
|
} catch (error) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
writeJson(res, 423, { error: error.message, code: 'mutation-locked' })
|
|
211
|
-
} else if (error instanceof TransactionRecoveryRequiredError) {
|
|
212
|
-
writeJson(res, 423, { error: error.message, code: 'transaction-recovery-required' })
|
|
213
|
-
} else {
|
|
207
|
+
// 423 家族(SAFE MODE / 环境锁 / 未收敛事务)的唯一映射在 kit;本路由其余错误沿用 400 口径。
|
|
208
|
+
if (!writeMutationError(res, host, error)) {
|
|
214
209
|
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
|
|
215
210
|
}
|
|
216
211
|
}
|
package/src/routes/sync.ts
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { endpoint, queryParam, requireJsonObject, readJsonBody, writeJson } from './kit.ts'
|
|
9
|
-
import {
|
|
8
|
+
import { endpoint, queryParam, requireJsonObject, readJsonBody, writeJson, writeMutationError } from './kit.ts'
|
|
9
|
+
import { runWithMutationLock } from '../utils/env-lock.ts'
|
|
10
10
|
import type { WebRoute } from './kit.ts'
|
|
11
11
|
import type { RoutesEnv } from './context.ts'
|
|
12
12
|
import { FileSnapshotStore } from '../core/index.ts'
|
|
@@ -426,11 +426,8 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
426
426
|
)
|
|
427
427
|
writeJson(res, 200, { ok: true, lastSyncChannel: channel })
|
|
428
428
|
} catch (error) {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
return
|
|
432
|
-
}
|
|
433
|
-
writeSyncRouteError(res, error)
|
|
429
|
+
// 423 家族(SAFE MODE / 环境锁)的唯一映射在 kit;其余沿用本组既有 SyncRouteError 口径。
|
|
430
|
+
if (!writeMutationError(res, host, error)) writeSyncRouteError(res, error)
|
|
434
431
|
}
|
|
435
432
|
}),
|
|
436
433
|
// ------------------------------------------------------ sync/push
|
|
@@ -116,23 +116,34 @@ function replaceSensitiveField(text: string, re: RegExp, blacklist: readonly str
|
|
|
116
116
|
}
|
|
117
117
|
|
|
118
118
|
/**
|
|
119
|
-
*
|
|
120
|
-
*
|
|
119
|
+
* 脱敏流水线(**唯一实现**,redact 与 createRedactor 共用一套顺序与语义)。
|
|
120
|
+
*
|
|
121
|
+
* 曾经这里与 createRedactor 各写一遍完全相同的 6 步(结构化 3 步 + 值形状 + URL query + userinfo),
|
|
122
|
+
* 两份代码只在「正则实例从哪来」上不同 —— 任何一步调整都要记得改两处,漏一次就是两条脱敏口径。
|
|
123
|
+
* 现在只由调用方决定正则实例的生命周期(模块级常量 / 每次预编译),流水线本身不再有副本。
|
|
121
124
|
*/
|
|
122
|
-
|
|
123
|
-
|
|
125
|
+
function redactPipeline(
|
|
126
|
+
text: string, blacklist: readonly string[], json: RegExp, kv: RegExp, colon: RegExp,
|
|
127
|
+
): string {
|
|
124
128
|
// 1. 结构化字段形态(顺序:JSON → kv → colon;JSON 键不会被后续形态二次命中)
|
|
125
|
-
out = replaceSensitiveField(
|
|
126
|
-
out = replaceSensitiveField(out,
|
|
127
|
-
out = replaceSensitiveField(out,
|
|
129
|
+
let out = replaceSensitiveField(text, json, blacklist);
|
|
130
|
+
out = replaceSensitiveField(out, kv, blacklist);
|
|
131
|
+
out = replaceSensitiveField(out, colon, blacklist);
|
|
128
132
|
// 2. 值形状模式(字段名无关,包含式)
|
|
129
133
|
for (const { re } of VALUE_PATTERNS) {
|
|
130
134
|
re.lastIndex = 0;
|
|
131
135
|
out = out.replace(re, REDACTED);
|
|
132
136
|
}
|
|
133
137
|
out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
|
|
134
|
-
|
|
135
|
-
|
|
138
|
+
return out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 文本脱敏(幂等)。blacklist 为**附加**规范化字段名(小写无分隔符,如 'clientsecret')。
|
|
143
|
+
* 输出仍保留结构化形态(JSON 行合法)。
|
|
144
|
+
*/
|
|
145
|
+
export function redact(text: string, blacklist: readonly string[] = []): string {
|
|
146
|
+
return redactPipeline(text, blacklist, JSON_FIELD_RE, KV_FIELD_RE, COLON_FIELD_RE);
|
|
136
147
|
}
|
|
137
148
|
|
|
138
149
|
/** 对象级掩码:字段名命中敏感名单 → 整值替换(返回新对象,不改原对象;结构与类型保留) */
|
|
@@ -147,21 +158,16 @@ export function redactValue(value: unknown, blacklist: readonly string[] = []):
|
|
|
147
158
|
return out;
|
|
148
159
|
}
|
|
149
160
|
|
|
150
|
-
/**
|
|
161
|
+
/**
|
|
162
|
+
* 预编译脱敏器(多次调用复用;blacklist 为附加规范化字段名)。
|
|
163
|
+
* 正则实例**在创建时**各复制一份:模块级常量若与本函数共享,多线程无害但会让「谁动了 lastIndex」
|
|
164
|
+
* 不可追溯;复制成本只有一次,换来每个脱敏器实例自持状态。
|
|
165
|
+
*/
|
|
151
166
|
export function createRedactor(blacklist: readonly string[] = []): (text: string) => string {
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
out = replaceSensitiveField(out, new RegExp(compiled.colon.source, 'g'), blacklist);
|
|
157
|
-
for (const { re } of VALUE_PATTERNS) {
|
|
158
|
-
re.lastIndex = 0;
|
|
159
|
-
out = out.replace(re, REDACTED);
|
|
160
|
-
}
|
|
161
|
-
out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
|
|
162
|
-
out = out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
|
|
163
|
-
return out;
|
|
164
|
-
};
|
|
167
|
+
const json = new RegExp(JSON_FIELD_RE.source, 'g');
|
|
168
|
+
const kv = new RegExp(KV_FIELD_RE.source, 'g');
|
|
169
|
+
const colon = new RegExp(COLON_FIELD_RE.source, 'g');
|
|
170
|
+
return (text: string): string => redactPipeline(text, blacklist, json, kv, colon);
|
|
165
171
|
}
|
|
166
172
|
|
|
167
173
|
/** 默认名单(文档用;redact 的默认附加名单为空,内置判定已含 DEFAULT_SECRET_FIELD_NAMES) */
|
|
@@ -40,6 +40,7 @@ import { shouldTriggerStartupRun } from './autosync-scheduler.ts';
|
|
|
40
40
|
import { AUTO_BACKUP_PREFIX, pruneAutoBackupsByPolicy } from './backup-files.ts';
|
|
41
41
|
import { DEFAULT_RETENTION_POLICY } from './retention-policy.ts';
|
|
42
42
|
import type { RetentionPolicy } from './retention-policy.ts';
|
|
43
|
+
import { formatDateStamp } from '../utils/time.ts';
|
|
43
44
|
|
|
44
45
|
export interface BackupRunResult {
|
|
45
46
|
status: BackupRunStatus;
|
|
@@ -280,7 +281,7 @@ export class BackupScheduler {
|
|
|
280
281
|
});
|
|
281
282
|
// 显式落 exportsDir(与 host 路由同构;Exporter 缺省 outPath 是相对文件名,不落目录)
|
|
282
283
|
// auto 前缀 = 定时备份产物标识:列表来源 Badge + cache-cleaner 豁免 + 保留策略清理依据
|
|
283
|
-
const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${
|
|
284
|
+
const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${formatDateStamp(this.now())}-${randomBytes(3).toString('hex')}.zip`);
|
|
284
285
|
const { report } = await exporter.export({
|
|
285
286
|
includeSecrets: false, // 恒不含 secret(与自动同步同语义)
|
|
286
287
|
outPath,
|
|
@@ -404,8 +405,4 @@ export class BackupScheduler {
|
|
|
404
405
|
}
|
|
405
406
|
}
|
|
406
407
|
|
|
407
|
-
|
|
408
|
-
function dateStamp(d: Date): string {
|
|
409
|
-
const p = (n: number): string => String(n).padStart(2, '0');
|
|
410
|
-
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
411
|
-
}
|
|
408
|
+
|
|
@@ -449,30 +449,41 @@ test('t32 源码守卫:地面代码里通道数组只有一处声明(其余
|
|
|
449
449
|
* 同一实验里 t32 的旧守卫(原文 includes)会误报 —— 正是本守卫存在的原因;
|
|
450
450
|
* - 把诱饵换成真实代码 → 本守卫变红并报出行号(当时为 5868 / 5869)。
|
|
451
451
|
*/
|
|
452
|
-
test('t33/B7
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
const
|
|
452
|
+
test('t33/B7 源码守卫:宿主侧两处源码不再手写通道数组/裸通道三元,全部消费单一来源', async () => {
|
|
453
|
+
// parseSyncBody 家族已下沉到 src/routes/route-support.ts(tech-debt #23)——宿主侧消费点因此分两处:
|
|
454
|
+
// 组合根源码与共享路由工具都必须在单一来源上取值,故一起扫、一起断言。
|
|
455
|
+
const sources: Array<[string, string]> = [
|
|
456
|
+
['src/index.ts', await fs.readFile(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8')],
|
|
457
|
+
['src/routes/route-support.ts', await fs.readFile(fileURLToPath(new URL('../routes/route-support.ts', import.meta.url)), 'utf8')],
|
|
458
|
+
]
|
|
459
|
+
const tplModes: string[] = []
|
|
460
|
+
const bad: string[] = []
|
|
461
|
+
for (const [sourceLabel, sourceText] of sources) {
|
|
462
|
+
const tplMode = stripJsComments(sourceText, true, false)
|
|
463
|
+
const opaqueMode = stripJsComments(sourceText, false, true)
|
|
464
|
+
tplModes.push(tplMode)
|
|
456
465
|
const tplLines = tplMode.split(String.fromCharCode(10))
|
|
457
466
|
const opaqueLines = opaqueMode.split(String.fromCharCode(10))
|
|
458
|
-
const bad: string[] = []
|
|
459
467
|
tplLines.forEach((line, i) => {
|
|
460
468
|
const t = line.trim()
|
|
461
469
|
// 只有两趟都认为这里是「真实代码」时才判定(注释在其中一趟必被清空)
|
|
462
470
|
if (t === '' || (opaqueLines[i] ?? '').trim() === '') return
|
|
463
|
-
if (t.includes("['git', 'webdav']") || t.includes("['git','webdav']")) bad.push(String(i + 1) + ': 通道数组字面量 ' + t)
|
|
464
|
-
if (t.includes("? 'webdav' : 'git'") || t.includes("?'webdav':'git'")) bad.push(String(i + 1) + ': 裸通道三元判定 ' + t)
|
|
471
|
+
if (t.includes("['git', 'webdav']") || t.includes("['git','webdav']")) bad.push(sourceLabel + ':' + String(i + 1) + ': 通道数组字面量 ' + t)
|
|
472
|
+
if (t.includes("? 'webdav' : 'git'") || t.includes("?'webdav':'git'")) bad.push(sourceLabel + ':' + String(i + 1) + ': 裸通道三元判定 ' + t)
|
|
465
473
|
})
|
|
466
|
-
|
|
474
|
+
}
|
|
475
|
+
const allTpl = tplModes.join(String.fromCharCode(10))
|
|
476
|
+
assert.deepEqual(bad, [], '宿主侧两处源码都不得再手写通道判定/枚举(应消费 channelOf / parseSyncChannel / SYNC_CHANNELS):' + String.fromCharCode(10) + bad.join(String.fromCharCode(10)))
|
|
467
477
|
// 正向断言:确实接上了单一来源(否则上面可能因「什么都没写」而假绿)
|
|
468
478
|
assert.ok(
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
479
|
+
allTpl.includes('channelOf')
|
|
480
|
+
&& allTpl.includes('parseSyncChannel')
|
|
481
|
+
&& allTpl.includes('SYNC_CHANNELS'),
|
|
482
|
+
'宿主侧必须从 ./sync/sync-config.ts 导入单一来源 API(channelOf / parseSyncChannel / SYNC_CHANNELS)',
|
|
472
483
|
)
|
|
473
484
|
assert.ok(
|
|
474
|
-
|
|
475
|
-
'
|
|
485
|
+
allTpl.includes('for (const channel of SYNC_CHANNELS)') || allTpl.includes('SYNC_CHANNELS.map('),
|
|
486
|
+
'宿主侧的通道集合必须由 SYNC_CHANNELS 派生(不得穷举字面量)',
|
|
476
487
|
)
|
|
477
488
|
})
|
|
478
489
|
|
package/src/ui/backup-inspect.ts
CHANGED
|
@@ -56,7 +56,7 @@ export function inspectSummary(analysis: ImportAnalysis, plan: ImportPlan): Back
|
|
|
56
56
|
/** 变更明细分组键(渲染顺序 = 冲突 → 变更 → 路径映射 → 一致跳过 → 其他)。 */
|
|
57
57
|
export type InspectGroupKey = 'conflicts' | 'changes' | 'paths' | 'skipped' | 'others';
|
|
58
58
|
|
|
59
|
-
/** 单分组:key(语义)+ kind(Badge
|
|
59
|
+
/** 单分组:key(语义)+ kind(Badge 四态颜色语义)+ 组内条目。 */
|
|
60
60
|
export interface InspectChangeGroup {
|
|
61
61
|
key: InspectGroupKey;
|
|
62
62
|
/** 颜色语义:error=冲突 / info=变更 / warn=路径映射与其它 / ok=一致跳过 */
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* 依赖方向:只从 `src/profiles/dsh-profile-shared.ts`(零依赖)取类型与纯函数——
|
|
9
9
|
* 绝不 import 用 node fs 的引擎(否则 client bundle 会带上 node 内置模块依赖而整插件不加载)。
|
|
10
10
|
*/
|
|
11
|
+
import { formatMinuteStamp, parseDateInput } from '../utils/time.ts'
|
|
11
12
|
import {
|
|
12
13
|
checkProfileName, isLaunchableShape, isManagedProfileName,
|
|
13
14
|
type DshProfileCopyWarning, type DshProfileIssue, type DshProfileLaunchResult, type DshProfileLaunchWarning,
|
|
@@ -361,11 +362,8 @@ export function issueLabelKey(issue: DshProfileIssue): 'profiles.issue.manifestI
|
|
|
361
362
|
|
|
362
363
|
/** 时间戳(毫秒)→ 本地 `YYYY-MM-DD HH:mm`;null / 非法 = 空串。 */
|
|
363
364
|
export function formatProfileTime(ms: number | null): string {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
if (Number.isNaN(d.getTime())) return ''
|
|
367
|
-
const p = (n: number): string => String(n).padStart(2, '0')
|
|
368
|
-
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
365
|
+
const d = parseDateInput(ms)
|
|
366
|
+
return d === null ? '' : formatMinuteStamp(d)
|
|
369
367
|
}
|
|
370
368
|
|
|
371
369
|
/** 字节数 → 人类可读(B / KB / MB,保留一位小数)。 */
|
package/src/ui/i18n.test.ts
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import test from 'node:test';
|
|
21
21
|
import assert from 'node:assert/strict';
|
|
22
|
-
import { readFileSync } from 'node:fs';
|
|
22
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
23
23
|
|
|
24
24
|
import { makeUiT, uiEn, uiZh, zhUiT } from './i18n.ts';
|
|
25
25
|
import {
|
|
@@ -183,8 +183,13 @@ test('i18n-08 英文字典不留 (s)/(ies) 括号式复数(今日起由 plural
|
|
|
183
183
|
}
|
|
184
184
|
};
|
|
185
185
|
collect(uiEn, 'uiEn');
|
|
186
|
-
//
|
|
187
|
-
|
|
186
|
+
// 客户端字典同查:改的是源码文本,不 import(client 侧不保证可被 node 直接加载)
|
|
187
|
+
// tech-debt #22:主字典按域拆成 src/client/locales/*.ts(聚合器只剩展开语句)⇒ 逐个分域文件扫,覆盖率不降
|
|
188
|
+
const splitDicts = readdirSync(new URL('../client/locales/', import.meta.url))
|
|
189
|
+
.filter((name) => name.endsWith('.ts'))
|
|
190
|
+
.sort()
|
|
191
|
+
.map((name) => '../client/locales/' + name);
|
|
192
|
+
for (const rel of [...splitDicts, '../client/sync/sync-locales.ts', '../client/market/market-locales.ts', '../client/recovery/recovery-locales.ts']) {
|
|
188
193
|
const text = readFileSync(new URL(rel, import.meta.url), 'utf8');
|
|
189
194
|
for (const line of text.split('\n')) {
|
|
190
195
|
if (/\((s|ies)\)/.test(line) && !/http\(s\)/.test(line) && /:\s*'/.test(line)) offenders.push(rel + ' :: ' + line.trim());
|
package/src/ui/snapshots-view.ts
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* 约束:不 import node 模块、不 import `../client/*`(架构边界 tests/architecture-boundaries.test.ts)、
|
|
13
13
|
* 无 React 依赖;类型仅从 `../core/*` / `../sync/*` 以 type-only 方式取(运行时不加载)。
|
|
14
14
|
*/
|
|
15
|
+
import { formatMinuteStamp } from '../utils/time.ts'
|
|
15
16
|
import type { RestorePlan, RestoreReport, SnapshotMeta } from '../core/restore.ts'
|
|
16
17
|
import type { RestoreChangeSummary } from '../core/snapshot-diff.ts'
|
|
17
18
|
import type { BackupFileMeta } from '../sync/backup-files.ts'
|
|
@@ -210,8 +211,7 @@ export function filterBackupFiles(files: readonly BackupFileMeta[], query: strin
|
|
|
210
211
|
export function formatBackupFileTime(ms: number): string {
|
|
211
212
|
const d = new Date(ms)
|
|
212
213
|
if (Number.isNaN(d.getTime())) return ''
|
|
213
|
-
|
|
214
|
-
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
214
|
+
return formatMinuteStamp(d)
|
|
215
215
|
}
|
|
216
216
|
|
|
217
217
|
/**
|
package/src/utils/paths.test.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import test from 'node:test';
|
|
9
9
|
import assert from 'node:assert/strict';
|
|
10
|
-
import
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { applyPrefixMappings, isPathInside, isSameOrChild } from './paths.ts';
|
|
11
12
|
import type { PathMapping } from '../core/types.ts';
|
|
12
13
|
|
|
13
14
|
/** 测试用映射(appliesTo 与语义无关,任选一个合法分区) */
|
|
@@ -61,3 +62,37 @@ test('core-F4:POSIX 路径**不得**折叠大小写(不同目录不许误匹
|
|
|
61
62
|
// 空映射 = 恒等
|
|
62
63
|
assert.equal(pathOf(applyPrefixMappings({ workspace: { path: '/home/Alice/proj/x' } }, [])), '/home/Alice/proj/x');
|
|
63
64
|
});
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* #8 越界判定收敛:四份同义守卫(paths / restore 的 isWithinHome / restore 的 isRealInside /
|
|
68
|
+
* verify-recovery 的副本)合并为 isPathInside。三份旧实现用 `rel.startsWith('..')` 判越界,
|
|
69
|
+
* 会把名字真叫 `..foo` 的兄弟目录误判成逃逸(path.relative('/a/b', '/a/b/..foo') === '..foo')。
|
|
70
|
+
*/
|
|
71
|
+
test('core-E1:越界判定只有一份实现,且 `..foo` 这种合法兄弟目录不得被误判成逃逸', () => {
|
|
72
|
+
const parent = path.resolve('sandbox', 'home');
|
|
73
|
+
const inside = (...segs: string[]): string => path.resolve(parent, ...segs);
|
|
74
|
+
const outside = path.resolve('sandbox', 'other');
|
|
75
|
+
|
|
76
|
+
// ① 名字真叫 ..foo 的兄弟目录在 parent 之内 —— 旧实现(rel.startsWith('..'))在此误杀
|
|
77
|
+
assert.equal(isPathInside(inside('..foo'), parent), true, '..foo 是子目录,不是 ..');
|
|
78
|
+
assert.equal(isPathInside(inside('..foo', 'settings.yaml'), parent), true);
|
|
79
|
+
|
|
80
|
+
// ② 等于父目录 / .. 折叠后仍在父目录内
|
|
81
|
+
assert.equal(isPathInside(parent, parent), true);
|
|
82
|
+
assert.equal(isPathInside(inside('a', '..', 'b'), parent), true);
|
|
83
|
+
|
|
84
|
+
// ③ 真越界:.. 段本身、以 .. + 分隔符开头、完全在外
|
|
85
|
+
assert.equal(isPathInside(inside('..'), parent), false);
|
|
86
|
+
assert.equal(isPathInside(inside('..', 'other'), parent), false);
|
|
87
|
+
assert.equal(isPathInside(outside, parent), false);
|
|
88
|
+
|
|
89
|
+
// ④ 别名与正典同口径(既有调用点不必改语义)
|
|
90
|
+
assert.equal(isSameOrChild(inside('..foo'), parent), true);
|
|
91
|
+
assert.equal(isSameOrChild(inside('..', 'x'), parent), false);
|
|
92
|
+
|
|
93
|
+
// ⑤ 大小写:缺省按平台(Windows 折叠、POSIX 不折叠),显式开关可覆盖
|
|
94
|
+
assert.equal(isPathInside(parent.toUpperCase(), parent), process.platform === 'win32');
|
|
95
|
+
assert.equal(isPathInside('/a/B', '/a/b', { foldCase: true }), true);
|
|
96
|
+
// foldCase:false 只在 POSIX 生效:win32 的 path.relative 自己就折大小写(故此处结果仍 true)
|
|
97
|
+
assert.equal(isPathInside('/a/B', '/a/b', { foldCase: false }), process.platform === 'win32');
|
|
98
|
+
});
|
package/src/utils/paths.ts
CHANGED
|
@@ -41,14 +41,38 @@ export function isPathSafe(entryName: string): boolean {
|
|
|
41
41
|
return true;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
/**
|
|
44
|
+
/** 越界判定选项。 */
|
|
45
|
+
export interface PathInsideOptions {
|
|
46
|
+
/**
|
|
47
|
+
* 比较前折叠大小写(Windows 文件系统大小写不敏感)。缺省按当前平台。
|
|
48
|
+
* 显式传 false 的场景:拿另一台机器的路径做形状判定(跨平台导入)。
|
|
49
|
+
*/
|
|
50
|
+
foldCase?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 候选路径是否位于父目录之内(含等于父目录)。
|
|
54
|
+
*
|
|
55
|
+
* 全仓**唯一**的越界判定(restore / verify-recovery / zip / recursive-walk / 路由都走这里):
|
|
56
|
+
* 早期四处各写一份,其中三份用 `rel.startsWith('..')` 判越界 —— 名字真的叫 `..foo` 的
|
|
57
|
+
* 兄弟目录会被误判为逃逸(`path.relative('/a/b','/a/b/..foo') === '..foo'`)。
|
|
58
|
+
* 越界只有两种形态:相对结果是 `..` 段本身,或以 `..` + 分隔符开头;绝对结果(跨盘符)同样越界。
|
|
45
59
|
*
|
|
46
|
-
*
|
|
47
|
-
* realpath 结果与原路径(Windows 8.3 短名、macOS `/var`→`/private/var
|
|
48
|
-
* `path.
|
|
60
|
+
* 纯字符串语义(**不碰文件系统**):两侧各自 `path.resolve` 后比较。调用方若混用
|
|
61
|
+
* realpath 结果与原路径(Windows 8.3 短名、macOS `/var`→`/private/var`)仍会误判为越界 ——
|
|
62
|
+
* `path.resolve` 不折叠短名,真实路径那一层必须两侧都先 realpath 再调用。
|
|
63
|
+
*/
|
|
64
|
+
export function isPathInside(child: string, parent: string, options: PathInsideOptions = {}): boolean {
|
|
65
|
+
const foldCase = options.foldCase ?? process.platform === 'win32';
|
|
66
|
+
const fold = (v: string): string => (foldCase ? v.toLowerCase() : v);
|
|
67
|
+
const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
|
|
68
|
+
if (rel === '') return true;
|
|
69
|
+
if (path.isAbsolute(rel)) return false; // 跨盘符(win32 relative 直接回绝对路径)
|
|
70
|
+
return rel !== '..' && !rel.startsWith(`..${path.sep}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 候选目录是否位于父目录之内(含等于父目录)—— `isPathInside` 的读法友好别名。 */
|
|
49
74
|
export function isSameOrChild(p: string, parent: string): boolean {
|
|
50
|
-
|
|
51
|
-
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
75
|
+
return isPathInside(p, parent);
|
|
52
76
|
}
|
|
53
77
|
|
|
54
78
|
/**
|