dsh-memu-memory 1.4.2 → 1.4.4
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/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
|
@@ -1,963 +1,963 @@
|
|
|
1
|
-
import test from 'node:test'
|
|
2
|
-
import assert from 'node:assert/strict'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
import fs from 'node:fs'
|
|
5
|
-
import os from 'node:os'
|
|
6
|
-
import path from 'node:path'
|
|
7
|
-
import sharp from 'sharp'
|
|
8
|
-
import { zipSync, unzipSync } from 'fflate'
|
|
9
|
-
|
|
10
|
-
// W4: every browser-facing entry of this plugin goes through one handler mounted
|
|
11
|
-
// twice (current and legacy prefix). The tests below drive each registered route
|
|
12
|
-
// separately and prove that a 401/403 is decided before body parsing, index or
|
|
13
|
-
// attachment reads, state writes, and imports.
|
|
14
|
-
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-webui-auth-'))
|
|
15
|
-
process.env.DSH_MEMU_HOME = home
|
|
16
|
-
|
|
17
|
-
const state = await import('../lib/state.js')
|
|
18
|
-
const { registerRpc } = await import('../lib/rpc.js')
|
|
19
|
-
const { standaloneHtml, standaloneAsset } = await import('../lib/webui.js')
|
|
20
|
-
|
|
21
|
-
test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
|
|
22
|
-
|
|
23
|
-
const html = standaloneHtml()
|
|
24
|
-
const clientJs = standaloneAsset('/dsh-memu-memory/ui-assets/client.js')
|
|
25
|
-
const iconPng = standaloneAsset('/dsh-memu-memory/ui-assets/icon.png')
|
|
26
|
-
|
|
27
|
-
const routeSpecs = []
|
|
28
|
-
// callbackMode: 'present' | 'throw' | 'absent' — 'absent' models a host that
|
|
29
|
-
// does not implement authorizeLibrary at all (typeof check must fail).
|
|
30
|
-
const auth = { decision: undefined, calls: 0, libraryDecision: true, libraryCalls: 0, libraryRequests: [], callbackMode: 'present' }
|
|
31
|
-
registerRpc({
|
|
32
|
-
inject: (_deps, build) => build({
|
|
33
|
-
effect: (fn) => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
|
|
34
|
-
webServer: { register: (spec) => { routeSpecs.push(spec); return () => {} } },
|
|
35
|
-
connection: {
|
|
36
|
-
requestRejection: () => { auth.calls += 1; return auth.decision },
|
|
37
|
-
get authorizeLibrary() {
|
|
38
|
-
if (auth.callbackMode === 'absent') return undefined
|
|
39
|
-
return async (req, details) => {
|
|
40
|
-
auth.libraryCalls += 1
|
|
41
|
-
auth.libraryRequests.push({ req, ...details })
|
|
42
|
-
if (auth.callbackMode === 'throw') throw new Error('host authorization unavailable')
|
|
43
|
-
return auth.libraryDecision
|
|
44
|
-
}
|
|
45
|
-
},
|
|
46
|
-
},
|
|
47
|
-
logger: {},
|
|
48
|
-
}),
|
|
49
|
-
})
|
|
50
|
-
assert.deepEqual(routeSpecs.map((spec) => spec.path), ['/dsh-memu-memory', '/dsh-memu'])
|
|
51
|
-
assert.equal(typeof routeSpecs[0].handler, 'function')
|
|
52
|
-
assert.equal(typeof routeSpecs[1].handler, 'function')
|
|
53
|
-
const prefixes = [
|
|
54
|
-
{ name: 'formal', route: routeSpecs[0], base: '/dsh-memu-memory' },
|
|
55
|
-
{ name: 'legacy', route: routeSpecs[1], base: '/dsh-memu' },
|
|
56
|
-
]
|
|
57
|
-
|
|
58
|
-
const homeRoot = path.resolve(home)
|
|
59
|
-
const probe = { active: false, reads: [], writes: [] }
|
|
60
|
-
const originals = new Map()
|
|
61
|
-
function inHome(file) {
|
|
62
|
-
if (typeof file !== 'string') return false
|
|
63
|
-
const resolved = path.resolve(file)
|
|
64
|
-
return resolved === homeRoot || resolved.startsWith(homeRoot + path.sep)
|
|
65
|
-
}
|
|
66
|
-
function relative(file) { return path.relative(homeRoot, path.resolve(file)).replace(/\\/g, '/') }
|
|
67
|
-
function wrap(name, mode) {
|
|
68
|
-
const original = fs[name]
|
|
69
|
-
originals.set(name, original)
|
|
70
|
-
fs[name] = function (file, ...args) {
|
|
71
|
-
if (probe.active && inHome(file)) (mode === 'write' ? probe.writes : probe.reads).push(relative(file))
|
|
72
|
-
return original.call(this, file, ...args)
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
for (const name of ['readFileSync', 'readdirSync', 'existsSync', 'statSync', 'lstatSync', 'createReadStream']) wrap(name, 'read')
|
|
76
|
-
for (const name of ['writeFileSync', 'appendFileSync', 'renameSync', 'mkdirSync', 'rmSync', 'unlinkSync', 'copyFileSync']) wrap(name, 'write')
|
|
77
|
-
{
|
|
78
|
-
const openSync = fs.openSync
|
|
79
|
-
originals.set('openSync', openSync)
|
|
80
|
-
fs.openSync = function (file, flags, ...args) {
|
|
81
|
-
if (probe.active && inHome(file)) {
|
|
82
|
-
const text = typeof flags === 'string' ? flags : 'r'
|
|
83
|
-
const write = /[wa+]/.test(text)
|
|
84
|
-
;(write ? probe.writes : probe.reads).push(relative(file))
|
|
85
|
-
}
|
|
86
|
-
return openSync.call(this, file, flags, ...args)
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
function resetProbe() { probe.reads.length = 0; probe.writes.length = 0 }
|
|
90
|
-
|
|
91
|
-
function makeResponse() {
|
|
92
|
-
const chunks = []
|
|
93
|
-
let finish
|
|
94
|
-
const done = new Promise((resolve, reject) => {
|
|
95
|
-
finish = resolve
|
|
96
|
-
const timer = setTimeout(() => reject(new Error('response did not end')), 3000)
|
|
97
|
-
timer.unref?.()
|
|
98
|
-
})
|
|
99
|
-
return {
|
|
100
|
-
status: 0,
|
|
101
|
-
headers: {},
|
|
102
|
-
destroyed: false,
|
|
103
|
-
done,
|
|
104
|
-
writeHead(code, headers) { this.status = code; this.headers = headers || {}; return this },
|
|
105
|
-
write(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); return true },
|
|
106
|
-
end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); finish() },
|
|
107
|
-
destroy(error) { this.destroyed = true; this.error = error; finish() },
|
|
108
|
-
get buffer() { return Buffer.concat(chunks) },
|
|
109
|
-
get text() { return Buffer.concat(chunks).toString('utf8') },
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
async function send(route, url, { method = 'GET', body, rejection, poison = false } = {}) {
|
|
114
|
-
auth.decision = rejection
|
|
115
|
-
auth.calls = 0
|
|
116
|
-
resetProbe()
|
|
117
|
-
probe.active = true
|
|
118
|
-
const pulls = []
|
|
119
|
-
const req = {
|
|
120
|
-
method,
|
|
121
|
-
url,
|
|
122
|
-
headers: {},
|
|
123
|
-
async *[Symbol.asyncIterator]() {
|
|
124
|
-
pulls.push(auth.calls)
|
|
125
|
-
if (poison) throw new Error('the body was read before authentication')
|
|
126
|
-
if (body !== undefined) yield Buffer.isBuffer(body) ? body : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body))
|
|
127
|
-
},
|
|
128
|
-
}
|
|
129
|
-
const res = makeResponse()
|
|
130
|
-
try {
|
|
131
|
-
await route.handler(req, res)
|
|
132
|
-
await res.done
|
|
133
|
-
} finally {
|
|
134
|
-
probe.active = false
|
|
135
|
-
}
|
|
136
|
-
return { res, pulls, authCalls: auth.calls, reads: [...probe.reads], writes: [...probe.writes] }
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function envelope(method, payload = {}, rpcId = 'auth-test') {
|
|
140
|
-
return { type: 'client-request', rpcId, method, payload }
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function assertRejected(result, code) {
|
|
144
|
-
assert.equal(result.res.status, code)
|
|
145
|
-
assert.equal(result.res.text, code === 401 ? 'unauthorized' : 'forbidden')
|
|
146
|
-
assert.equal(result.pulls.length, 0, 'request body must not be iterated before requestRejection')
|
|
147
|
-
assert.equal(result.authCalls, 1, 'requestRejection must run exactly once')
|
|
148
|
-
assert.deepEqual(result.reads, [], 'rejected request must not read anything under DSH_MEMU_HOME')
|
|
149
|
-
assert.deepEqual(result.writes, [], 'rejected request must not write anything under DSH_MEMU_HOME')
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function snapshotTree(root) {
|
|
153
|
-
const files = {}
|
|
154
|
-
const walk = (dir) => {
|
|
155
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
156
|
-
const full = path.join(dir, entry.name)
|
|
157
|
-
const rel = path.relative(root, full).replace(/\\/g, '/')
|
|
158
|
-
if (entry.isDirectory()) { files[rel + '/'] = true; walk(full) }
|
|
159
|
-
else { const data = fs.readFileSync(full); files[rel] = data.length + ':' + crypto.createHash('sha256').update(data).digest('hex') }
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
walk(root)
|
|
163
|
-
return files
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const SENTINEL = 'AUTH-SENTINEL-7f3c2a'
|
|
167
|
-
const IMPORT_SENTINEL = 'IMPORT-SENTINEL-91b0d4'
|
|
168
|
-
const RPC_IMPORT_SENTINEL = 'RPC-IMPORT-SENTINEL-4c8e11'
|
|
169
|
-
|
|
170
|
-
const library = state.createLibrary({ name: 'auth-matrix', cwd: path.join(home, 'auth-matrix') })
|
|
171
|
-
const sessionId = 'auth-session'
|
|
172
|
-
state.setSessionBinding(sessionId, { libraryId: library.id, useLibrary: true, scopeKey: library.scopeKey })
|
|
173
|
-
state.updatePrivateIndex(library.id, (index) => {
|
|
174
|
-
index.entries['mem-auth-sentinel'] = {
|
|
175
|
-
title: 'auth sentinel', content: SENTINEL, status: 'active', layer: 'long_term',
|
|
176
|
-
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
177
|
-
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
178
|
-
}
|
|
179
|
-
})
|
|
180
|
-
state.flushState()
|
|
181
|
-
|
|
182
|
-
test('UI and assets: both registered prefixes authorize, and 401/403 never serve or read', async () => {
|
|
183
|
-
const cases = [
|
|
184
|
-
{ route: '/ui', expected: html, type: /text\/html/ },
|
|
185
|
-
{ route: '/settings', expected: html, type: /text\/html/ },
|
|
186
|
-
{ route: '/ui-assets/client.js', expected: clientJs, type: /javascript/ },
|
|
187
|
-
{ route: '/ui-assets/icon.png', expected: iconPng, type: /image\/png/ },
|
|
188
|
-
]
|
|
189
|
-
for (const prefix of prefixes) {
|
|
190
|
-
for (const item of cases) {
|
|
191
|
-
const url = prefix.base + item.route
|
|
192
|
-
const allowed = await send(prefix.route, url)
|
|
193
|
-
assert.equal(allowed.res.status, 200, prefix.name + ' ' + item.route)
|
|
194
|
-
assert.match(allowed.res.headers['Content-Type'], item.type)
|
|
195
|
-
assert.deepEqual(allowed.res.buffer, Buffer.from(item.expected))
|
|
196
|
-
for (const code of [401, 403]) {
|
|
197
|
-
assertRejected(await send(prefix.route, url, { rejection: code }), code)
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
})
|
|
202
|
-
|
|
203
|
-
test('POST RPC: requestRejection runs before body parsing and before any write', async () => {
|
|
204
|
-
for (const prefix of prefixes) {
|
|
205
|
-
for (const code of [401, 403]) {
|
|
206
|
-
state.flushState()
|
|
207
|
-
const baseline = snapshotTree(home)
|
|
208
|
-
const name = 'denied-' + prefix.name + '-' + code
|
|
209
|
-
const result = await send(prefix.route, prefix.base + '/createLibrary', {
|
|
210
|
-
method: 'POST', poison: true, rejection: code,
|
|
211
|
-
body: envelope('createLibrary', { name, cwd: path.join(home, name) }),
|
|
212
|
-
})
|
|
213
|
-
assertRejected(result, code)
|
|
214
|
-
assert.equal(state.listLibraries().some((item) => item.name === name), false)
|
|
215
|
-
assert.deepEqual(snapshotTree(home), baseline, 'a rejected createLibrary must not touch state.json')
|
|
216
|
-
}
|
|
217
|
-
const name = 'allowed-' + prefix.name
|
|
218
|
-
const result = await send(prefix.route, prefix.base + '/createLibrary', {
|
|
219
|
-
method: 'POST', body: envelope('createLibrary', { name, cwd: path.join(home, name) }),
|
|
220
|
-
})
|
|
221
|
-
assert.equal(result.res.status, 200)
|
|
222
|
-
const json = JSON.parse(result.res.text)
|
|
223
|
-
assert.equal(json.result.ok, true)
|
|
224
|
-
assert.equal(json.result.value.name, name)
|
|
225
|
-
assert.equal(result.authCalls, 1)
|
|
226
|
-
assert.equal(result.pulls.length, 1)
|
|
227
|
-
assert.equal(result.pulls[0], 1, 'authorized body iteration must happen after requestRejection')
|
|
228
|
-
assert.ok(result.writes.length > 0, 'authorized createLibrary must write the library')
|
|
229
|
-
}
|
|
230
|
-
})
|
|
231
|
-
|
|
232
|
-
test('GET-side RPC reads: 401/403 return before the private index is read', async () => {
|
|
233
|
-
const urlFor = (prefix) => prefix.base + '/getMemory'
|
|
234
|
-
for (const prefix of prefixes) {
|
|
235
|
-
for (const code of [401, 403]) {
|
|
236
|
-
state.flushState()
|
|
237
|
-
state.clearCaches()
|
|
238
|
-
const baseline = snapshotTree(home)
|
|
239
|
-
const denied = await send(prefix.route, urlFor(prefix), {
|
|
240
|
-
method: 'POST', poison: true, rejection: code,
|
|
241
|
-
body: envelope('getMemory', { libraryId: library.id, id: 'mem-auth-sentinel' }),
|
|
242
|
-
})
|
|
243
|
-
assertRejected(denied, code)
|
|
244
|
-
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
245
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
246
|
-
}
|
|
247
|
-
state.flushState()
|
|
248
|
-
state.clearCaches()
|
|
249
|
-
const allowed = await send(prefix.route, urlFor(prefix), {
|
|
250
|
-
method: 'POST', body: envelope('getMemory', { libraryId: library.id, id: 'mem-auth-sentinel' }),
|
|
251
|
-
})
|
|
252
|
-
assert.equal(allowed.res.status, 200)
|
|
253
|
-
assert.match(allowed.res.text, new RegExp(SENTINEL))
|
|
254
|
-
assert.ok(allowed.reads.length > 0, 'authorized getMemory must read the private index from disk')
|
|
255
|
-
assert.equal(allowed.pulls[0], 1)
|
|
256
|
-
}
|
|
257
|
-
})
|
|
258
|
-
|
|
259
|
-
test('library authorization: session A cannot address library B, and standalone callback fails closed', async () => {
|
|
260
|
-
const other = state.createLibrary({ name: 'auth-other', cwd: path.join(home, 'auth-other') })
|
|
261
|
-
state.setSessionBinding('auth-session-other', { libraryId: other.id, useLibrary: true, scopeKey: other.scopeKey })
|
|
262
|
-
for (const prefix of prefixes) {
|
|
263
|
-
auth.callbackMode = 'present'
|
|
264
|
-
auth.libraryDecision = true
|
|
265
|
-
auth.libraryCalls = 0
|
|
266
|
-
auth.libraryRequests.length = 0
|
|
267
|
-
const cross = await send(prefix.route, prefix.base + '/getMemory', {
|
|
268
|
-
method: 'POST',
|
|
269
|
-
body: envelope('getMemory', { libraryId: other.id, sessionId, id: 'mem-auth-sentinel' }),
|
|
270
|
-
})
|
|
271
|
-
assert.equal(cross.res.status, 403)
|
|
272
|
-
assert.equal(cross.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
273
|
-
assert.equal(cross.pulls.length, 1, 'JSON body may be parsed before route authorization')
|
|
274
|
-
assert.equal(auth.libraryCalls, 0, 'bound sessions must not fall back to host callback')
|
|
275
|
-
assert.deepEqual(cross.reads, [])
|
|
276
|
-
assert.deepEqual(cross.writes, [])
|
|
277
|
-
|
|
278
|
-
auth.libraryDecision = false
|
|
279
|
-
auth.libraryCalls = 0
|
|
280
|
-
const denied = await send(prefix.route, prefix.base + '/getMemory', {
|
|
281
|
-
method: 'POST',
|
|
282
|
-
body: envelope('getMemory', { libraryId: other.id }),
|
|
283
|
-
})
|
|
284
|
-
assert.equal(denied.res.status, 403)
|
|
285
|
-
assert.equal(auth.libraryCalls, 1)
|
|
286
|
-
assert.equal(denied.reads.length, 0)
|
|
287
|
-
assert.equal(denied.writes.length, 0)
|
|
288
|
-
|
|
289
|
-
auth.libraryDecision = true
|
|
290
|
-
auth.callbackMode = 'throw'
|
|
291
|
-
auth.libraryCalls = 0
|
|
292
|
-
const thrown = await send(prefix.route, prefix.base + '/getMemory', {
|
|
293
|
-
method: 'POST', poison: false,
|
|
294
|
-
body: envelope('getMemory', { libraryId: other.id }),
|
|
295
|
-
})
|
|
296
|
-
assert.equal(thrown.res.status, 403)
|
|
297
|
-
assert.equal(auth.libraryCalls, 1)
|
|
298
|
-
assert.equal(thrown.reads.length, 0)
|
|
299
|
-
assert.equal(thrown.writes.length, 0)
|
|
300
|
-
|
|
301
|
-
auth.callbackMode = 'present'
|
|
302
|
-
auth.libraryDecision = true
|
|
303
|
-
}
|
|
304
|
-
})
|
|
305
|
-
|
|
306
|
-
test('attachment thumbnails: 401/403 precede authorization and attachment-pool reads', async () => {
|
|
307
|
-
const attachmentLibrary = state.createLibrary({ name: 'auth-attachment', cwd: path.join(home, 'auth-attachment') })
|
|
308
|
-
const attachmentSession = 'auth-attachment-session'
|
|
309
|
-
state.setSessionBinding(attachmentSession, { libraryId: attachmentLibrary.id, useLibrary: true, scopeKey: attachmentLibrary.scopeKey })
|
|
310
|
-
const png = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#336699' } }).png().toBuffer()
|
|
311
|
-
const sha = crypto.createHash('sha256').update(png).digest('hex')
|
|
312
|
-
const blobPath = path.join(home, 'attachments', attachmentLibrary.id, sha + '.png')
|
|
313
|
-
fs.mkdirSync(path.dirname(blobPath), { recursive: true })
|
|
314
|
-
fs.writeFileSync(blobPath, png)
|
|
315
|
-
const poolPath = path.join(home, 'index', attachmentLibrary.id + '.media.json')
|
|
316
|
-
const pool = {
|
|
317
|
-
version: 1,
|
|
318
|
-
blobs: { [sha]: { sha256: sha, bytes: png.length, ext: 'png', mime: 'image/png', w: 8, h: 8, useCount: 1, refs: [], missing: false, captionBy: 'none' } },
|
|
319
|
-
totals: { bytes: png.length, count: 1 },
|
|
320
|
-
}
|
|
321
|
-
fs.writeFileSync(poolPath, JSON.stringify(pool))
|
|
322
|
-
state.updatePrivateIndex(attachmentLibrary.id, (index) => {
|
|
323
|
-
index.entries['mem-auth-image'] = {
|
|
324
|
-
title: 'auth image', content: 'attachment sentinel ' + SENTINEL, status: 'active', layer: 'long_term',
|
|
325
|
-
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
326
|
-
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
327
|
-
attachments: [{ sha256: sha, name: 'auth.png', mediaType: 'image/png', bytes: png.length }],
|
|
328
|
-
}
|
|
329
|
-
})
|
|
330
|
-
state.flushState()
|
|
331
|
-
const url = (prefix) => prefix.base + '/attachment/' + encodeURIComponent(attachmentLibrary.id) + '/' + sha + '?sessionId=' + encodeURIComponent(attachmentSession)
|
|
332
|
-
for (const prefix of prefixes) {
|
|
333
|
-
state.flushState()
|
|
334
|
-
state.clearCaches()
|
|
335
|
-
const allowed = await send(prefix.route, url(prefix))
|
|
336
|
-
assert.equal(allowed.res.status, 200)
|
|
337
|
-
assert.match(allowed.res.headers['Content-Type'], /image\/webp/)
|
|
338
|
-
assert.ok(allowed.res.buffer.length > 0)
|
|
339
|
-
assert.ok(allowed.reads.some((item) => item.endsWith('.media.json')), 'authorized thumbnail reads the media pool')
|
|
340
|
-
}
|
|
341
|
-
for (const prefix of prefixes) {
|
|
342
|
-
for (const code of [401, 403]) {
|
|
343
|
-
state.flushState()
|
|
344
|
-
state.clearCaches()
|
|
345
|
-
const baseline = snapshotTree(home)
|
|
346
|
-
const denied = await send(prefix.route, url(prefix), { rejection: code })
|
|
347
|
-
assertRejected(denied, code)
|
|
348
|
-
assert.equal(denied.res.text.includes('attachment unavailable'), false)
|
|
349
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
for (const prefix of prefixes) {
|
|
353
|
-
const rpcPayload = { libraryId: attachmentLibrary.id, sha256: sha, sessionId: attachmentSession }
|
|
354
|
-
for (const code of [401, 403]) {
|
|
355
|
-
state.flushState()
|
|
356
|
-
state.clearCaches()
|
|
357
|
-
const baseline = snapshotTree(home)
|
|
358
|
-
const denied = await send(prefix.route, prefix.base + '/getAttachment', {
|
|
359
|
-
method: 'POST', poison: true, rejection: code, body: envelope('getAttachment', rpcPayload),
|
|
360
|
-
})
|
|
361
|
-
assertRejected(denied, code)
|
|
362
|
-
assert.equal(denied.res.text.includes(sha), false)
|
|
363
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
364
|
-
}
|
|
365
|
-
state.flushState()
|
|
366
|
-
state.clearCaches()
|
|
367
|
-
const allowed = await send(prefix.route, prefix.base + '/getAttachment', {
|
|
368
|
-
method: 'POST', body: envelope('getAttachment', rpcPayload),
|
|
369
|
-
})
|
|
370
|
-
assert.equal(allowed.res.status, 200)
|
|
371
|
-
const json = JSON.parse(allowed.res.text)
|
|
372
|
-
assert.equal(json.result.ok, true)
|
|
373
|
-
assert.equal(json.result.value.sha256, sha)
|
|
374
|
-
assert.equal(allowed.pulls[0], 1)
|
|
375
|
-
}
|
|
376
|
-
// Tripwire: a corrupt pool makes an authorized thumbnail fail inside the media
|
|
377
|
-
// path, so a 401/403 instead of that failure proves rejection happened first.
|
|
378
|
-
fs.writeFileSync(poolPath, '{not valid json')
|
|
379
|
-
for (const prefix of prefixes) {
|
|
380
|
-
state.flushState()
|
|
381
|
-
state.clearCaches()
|
|
382
|
-
const tripwire = await send(prefix.route, url(prefix))
|
|
383
|
-
assert.equal(tripwire.res.status, 503)
|
|
384
|
-
assert.equal(tripwire.res.text, 'attachment unavailable')
|
|
385
|
-
for (const code of [401, 403]) {
|
|
386
|
-
const denied = await send(prefix.route, url(prefix), { rejection: code })
|
|
387
|
-
assertRejected(denied, code)
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
fs.writeFileSync(poolPath, JSON.stringify(pool))
|
|
391
|
-
})
|
|
392
|
-
|
|
393
|
-
test('export ZIP: 401/403 precede export dispatch, index reads and ZIP construction', async () => {
|
|
394
|
-
for (const prefix of prefixes) {
|
|
395
|
-
for (const code of [401, 403]) {
|
|
396
|
-
state.flushState()
|
|
397
|
-
state.clearCaches()
|
|
398
|
-
const baseline = snapshotTree(home)
|
|
399
|
-
const denied = await send(prefix.route, prefix.base + '/export/' + library.id + '.zip', { rejection: code })
|
|
400
|
-
assertRejected(denied, code)
|
|
401
|
-
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
402
|
-
assert.equal(denied.res.text.startsWith('PK'), false)
|
|
403
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
404
|
-
}
|
|
405
|
-
state.flushState()
|
|
406
|
-
state.clearCaches()
|
|
407
|
-
const allowed = await send(prefix.route, prefix.base + '/export/' + library.id + '.zip')
|
|
408
|
-
assert.equal(allowed.res.status, 200)
|
|
409
|
-
assert.match(allowed.res.headers['Content-Type'], /application\/zip/)
|
|
410
|
-
assert.equal(allowed.res.buffer.subarray(0, 2).toString('utf8'), 'PK')
|
|
411
|
-
const files = unzipSync(new Uint8Array(allowed.res.buffer))
|
|
412
|
-
assert.ok(files['memories.json'])
|
|
413
|
-
const exported = JSON.parse(Buffer.from(files['memories.json']).toString('utf8'))
|
|
414
|
-
assert.ok(exported.memories.some((item) => String(item.content).includes(SENTINEL)))
|
|
415
|
-
assert.ok(allowed.reads.length > 0, 'authorized export reads the private index')
|
|
416
|
-
const rpcUrl = prefix.base + '/exportLibrary'
|
|
417
|
-
const rpcPayload = { libraryId: library.id, includeAttachments: true }
|
|
418
|
-
for (const code of [401, 403]) {
|
|
419
|
-
state.flushState()
|
|
420
|
-
state.clearCaches()
|
|
421
|
-
const baseline = snapshotTree(home)
|
|
422
|
-
const denied = await send(prefix.route, rpcUrl, {
|
|
423
|
-
method: 'POST', poison: true, rejection: code, body: envelope('exportLibrary', rpcPayload),
|
|
424
|
-
})
|
|
425
|
-
assertRejected(denied, code)
|
|
426
|
-
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
427
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
428
|
-
}
|
|
429
|
-
state.flushState()
|
|
430
|
-
state.clearCaches()
|
|
431
|
-
const rpcAllowed = await send(prefix.route, rpcUrl, {
|
|
432
|
-
method: 'POST', body: envelope('exportLibrary', rpcPayload),
|
|
433
|
-
})
|
|
434
|
-
assert.equal(rpcAllowed.res.status, 200)
|
|
435
|
-
const rpcJson = JSON.parse(rpcAllowed.res.text)
|
|
436
|
-
assert.equal(rpcJson.result.ok, true)
|
|
437
|
-
const rpcZip = unzipSync(new Uint8Array(Buffer.from(rpcJson.result.value.base64, 'base64')))
|
|
438
|
-
const rpcExported = JSON.parse(Buffer.from(rpcZip['memories.json']).toString('utf8'))
|
|
439
|
-
assert.ok(rpcExported.memories.some((item) => String(item.content).includes(SENTINEL)))
|
|
440
|
-
assert.equal(rpcAllowed.pulls[0], 1)
|
|
441
|
-
}
|
|
442
|
-
})
|
|
443
|
-
|
|
444
|
-
test('import ZIP: 401/403 precede body reads, staging and library writes', async () => {
|
|
445
|
-
const destinations = {}
|
|
446
|
-
for (const prefix of prefixes) destinations[prefix.name] = state.createLibrary({ name: 'auth-import-' + prefix.name, cwd: path.join(home, 'auth-import-' + prefix.name) })
|
|
447
|
-
const archive = Buffer.from(zipSync({
|
|
448
|
-
'memories.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-memory-library@1', memories: [{ id: 'mem-imported', title: 'imported', content: IMPORT_SENTINEL, layer: 'long_term', status: 'active' }] })),
|
|
449
|
-
'manifest.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-memory-media@1', blobs: {} })),
|
|
450
|
-
}))
|
|
451
|
-
for (const prefix of prefixes) {
|
|
452
|
-
const destination = destinations[prefix.name]
|
|
453
|
-
const importUrl = prefix.base + '/import/' + destination.id + '.zip'
|
|
454
|
-
for (const code of [401, 403]) {
|
|
455
|
-
state.flushState()
|
|
456
|
-
state.clearCaches()
|
|
457
|
-
const baseline = snapshotTree(home)
|
|
458
|
-
const denied = await send(prefix.route, importUrl, { method: 'POST', body: archive, poison: true, rejection: code })
|
|
459
|
-
assertRejected(denied, code)
|
|
460
|
-
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(IMPORT_SENTINEL), false)
|
|
461
|
-
assert.deepEqual(snapshotTree(home), baseline, 'a rejected import must not create staging files or touch the library')
|
|
462
|
-
}
|
|
463
|
-
state.flushState()
|
|
464
|
-
state.clearCaches()
|
|
465
|
-
const allowed = await send(prefix.route, importUrl, { method: 'POST', body: archive })
|
|
466
|
-
assert.equal(allowed.res.status, 200)
|
|
467
|
-
assert.equal(JSON.parse(allowed.res.text).ok, true)
|
|
468
|
-
assert.equal(allowed.pulls[0], 1, 'authorized ZIP body is consumed after requestRejection')
|
|
469
|
-
assert.ok(allowed.writes.length > 0, 'authorized import writes the library')
|
|
470
|
-
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(IMPORT_SENTINEL), true)
|
|
471
|
-
}
|
|
472
|
-
})
|
|
473
|
-
|
|
474
|
-
test('importMemories RPC: 401/403 precede JSON parsing and import writes', async () => {
|
|
475
|
-
const destinations = {}
|
|
476
|
-
for (const prefix of prefixes) destinations[prefix.name] = state.createLibrary({ name: 'auth-rpc-import-' + prefix.name, cwd: path.join(home, 'auth-rpc-import-' + prefix.name) })
|
|
477
|
-
for (const prefix of prefixes) {
|
|
478
|
-
const destination = destinations[prefix.name]
|
|
479
|
-
const payload = { libraryId: destination.id, memories: [{ content: RPC_IMPORT_SENTINEL, title: 'rpc imported' }] }
|
|
480
|
-
for (const code of [401, 403]) {
|
|
481
|
-
state.flushState()
|
|
482
|
-
state.clearCaches()
|
|
483
|
-
const baseline = snapshotTree(home)
|
|
484
|
-
const denied = await send(prefix.route, prefix.base + '/importMemories', {
|
|
485
|
-
method: 'POST', poison: true, rejection: code, body: envelope('importMemories', payload),
|
|
486
|
-
})
|
|
487
|
-
assertRejected(denied, code)
|
|
488
|
-
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(RPC_IMPORT_SENTINEL), false)
|
|
489
|
-
assert.deepEqual(snapshotTree(home), baseline)
|
|
490
|
-
}
|
|
491
|
-
state.flushState()
|
|
492
|
-
state.clearCaches()
|
|
493
|
-
const allowed = await send(prefix.route, prefix.base + '/importMemories', {
|
|
494
|
-
method: 'POST', body: envelope('importMemories', payload),
|
|
495
|
-
})
|
|
496
|
-
assert.equal(allowed.res.status, 200)
|
|
497
|
-
const json = JSON.parse(allowed.res.text)
|
|
498
|
-
assert.equal(json.result.ok, true)
|
|
499
|
-
assert.equal(json.result.value.imported, 1)
|
|
500
|
-
assert.equal(allowed.pulls[0], 1)
|
|
501
|
-
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(RPC_IMPORT_SENTINEL), true)
|
|
502
|
-
}
|
|
503
|
-
})
|
|
504
|
-
|
|
505
|
-
test('unsupported methods still authenticate first: 401/403 before 405', async () => {
|
|
506
|
-
for (const prefix of prefixes) {
|
|
507
|
-
for (const code of [401, 403]) {
|
|
508
|
-
assertRejected(await send(prefix.route, prefix.base + '/ui', { method: 'DELETE', rejection: code }), code)
|
|
509
|
-
assertRejected(await send(prefix.route, prefix.base + '/listLibraries', { method: 'GET', rejection: code }), code)
|
|
510
|
-
}
|
|
511
|
-
assert.equal((await send(prefix.route, prefix.base + '/ui', { method: 'DELETE' })).res.status, 405)
|
|
512
|
-
assert.equal((await send(prefix.route, prefix.base + '/listLibraries', { method: 'GET' })).res.status, 405)
|
|
513
|
-
}
|
|
514
|
-
})
|
|
515
|
-
|
|
516
|
-
// §10 P0: one representative per audited operation category. The table drives
|
|
517
|
-
// every variant, so a new endpoint added to LIBRARY_ROUTE_OPERATIONS with the
|
|
518
|
-
// wrong operation (or none) fails here instead of shipping unverified.
|
|
519
|
-
const MATRIX_SHA = 'a'.repeat(64)
|
|
520
|
-
const matrixRows = [
|
|
521
|
-
{ endpoint: 'getMemory', operation: 'read', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
522
|
-
{ endpoint: 'browseWall', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
523
|
-
{ endpoint: 'getGraph', operation: 'read', payload: (lib) => ({ libraryId: lib.id, offset: 0, domain: 'coding' }) },
|
|
524
|
-
{ endpoint: 'getStats', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
525
|
-
// 工单 F:实体合并的读写面。合并矩阵只验证路由授权:不存在的实体在 200
|
|
526
|
-
// 业务信封里报 unknown entity,403 必须在 dispatch 之前发生。
|
|
527
|
-
{ endpoint: 'suggestEntityMerges', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
528
|
-
{ endpoint: 'mergeEntities', operation: 'write', payload: (lib) => ({ libraryId: lib.id, targetId: 'ent-matrix-target', sourceIds: ['ent-matrix-source'] }) },
|
|
529
|
-
{ endpoint: 'addMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, content: 'matrix write body' }) },
|
|
530
|
-
{ endpoint: 'updateMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch', patch: { title: 'matrix retitled' } }) },
|
|
531
|
-
{ endpoint: 'archiveMemory', operation: 'archive', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
532
|
-
{ endpoint: 'deleteMemory', operation: 'delete', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
533
|
-
{ endpoint: 'renameLibrary', operation: 'rename', payload: (lib) => ({ libraryId: lib.id, name: 'matrix rename' }) },
|
|
534
|
-
{ endpoint: 'restoreLibrary', operation: 'restore', payload: (lib) => ({ libraryId: lib.id }) },
|
|
535
|
-
{ endpoint: 'importMemories', operation: 'import', payload: (lib) => ({ libraryId: lib.id, memories: [] }) },
|
|
536
|
-
{ endpoint: 'exportLibrary', operation: 'export', payload: (lib) => ({ libraryId: lib.id }) },
|
|
537
|
-
{ endpoint: 'getAttachment', operation: 'attachment.read', payload: (lib) => ({ libraryId: lib.id, sha256: MATRIX_SHA }) },
|
|
538
|
-
{ endpoint: 'listReviews', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
539
|
-
{ endpoint: 'resolveReview', operation: 'write', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch', action: 'reject' }) },
|
|
540
|
-
{ endpoint: 'lexiconList', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
541
|
-
{ endpoint: 'lexiconAdd', operation: 'write', payload: (lib) => ({ libraryId: lib.id, term: 'matrix term', kind: 'term', meaning: 'matrix meaning' }) },
|
|
542
|
-
// §2.3:lexiconReview 删除,lifecycle 变成 archive / restore 两个普通 write;
|
|
543
|
-
// 授权模型不动(会话绑定优先、standalone 走 host callback)。
|
|
544
|
-
{ endpoint: 'lexiconArchive', operation: 'write', payload: (lib) => ({ libraryId: lib.id, termId: 'lex-matrix-scratch' }) },
|
|
545
|
-
{ endpoint: 'lexiconRestore', operation: 'write', payload: (lib) => ({ libraryId: lib.id, termId: 'lex-matrix-scratch' }) },
|
|
546
|
-
]
|
|
547
|
-
|
|
548
|
-
function seedMatrixScratch() {
|
|
549
|
-
state.updatePrivateIndex(library.id, (index) => {
|
|
550
|
-
index.entries['mem-matrix-scratch'] = {
|
|
551
|
-
title: 'matrix scratch', content: 'matrix scratch body', status: 'active', layer: 'long_term',
|
|
552
|
-
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
553
|
-
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
554
|
-
}
|
|
555
|
-
})
|
|
556
|
-
state.flushState()
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
test('operation matrix: every library route denies A→B, allows A→A, and gates standalone on the host callback', async () => {
|
|
560
|
-
const libB = state.createLibrary({ name: 'auth-matrix-b', cwd: path.join(home, 'auth-matrix-b') })
|
|
561
|
-
for (const prefix of prefixes) {
|
|
562
|
-
seedMatrixScratch()
|
|
563
|
-
for (const row of matrixRows) {
|
|
564
|
-
const post = (payload) => send(prefix.route, prefix.base + '/' + row.endpoint, { method: 'POST', body: envelope(row.endpoint, payload) })
|
|
565
|
-
|
|
566
|
-
// Session A → library B: 403, the host callback is never consulted, and
|
|
567
|
-
// the body (already parsed) is the only thing touched before the denial.
|
|
568
|
-
auth.callbackMode = 'present'
|
|
569
|
-
auth.libraryDecision = true
|
|
570
|
-
auth.libraryCalls = 0
|
|
571
|
-
const cross = await post({ ...row.payload(libB), sessionId })
|
|
572
|
-
assert.equal(cross.res.status, 403, `${prefix.name} ${row.endpoint}: session A must not address library B`)
|
|
573
|
-
assert.equal(cross.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
574
|
-
assert.equal(cross.pulls.length, 1, 'route authorization happens after the envelope parse')
|
|
575
|
-
assert.equal(auth.libraryCalls, 0, `${row.endpoint}: a bound session must not fall back to the host callback`)
|
|
576
|
-
|
|
577
|
-
// Session A → library A: past the route gate. Business errors, when the
|
|
578
|
-
// payload is not worth making valid, still come back inside a 200.
|
|
579
|
-
const own = await post({ ...row.payload(library), sessionId })
|
|
580
|
-
assert.equal(own.res.status, 200, `${prefix.name} ${row.endpoint}: session A on its own library must pass the route gate`)
|
|
581
|
-
assert.equal(auth.libraryCalls, 0)
|
|
582
|
-
|
|
583
|
-
// Standalone (no session): exactly one authorizeLibrary call that carries
|
|
584
|
-
// the audited operation and the target library; only strict true passes.
|
|
585
|
-
auth.libraryRequests.length = 0
|
|
586
|
-
auth.libraryDecision = true
|
|
587
|
-
auth.libraryCalls = 0
|
|
588
|
-
const granted = await post(row.payload(libB))
|
|
589
|
-
assert.equal(granted.res.status, 200, `${prefix.name} ${row.endpoint}: host callback true must grant the standalone request`)
|
|
590
|
-
assert.equal(auth.libraryCalls, 1)
|
|
591
|
-
const request = auth.libraryRequests.at(-1)
|
|
592
|
-
assert.equal(request.libraryId, libB.id, `${row.endpoint}: callback must see the target library`)
|
|
593
|
-
assert.equal(request.operation, row.operation, `${row.endpoint}: callback must see the audited operation`)
|
|
594
|
-
|
|
595
|
-
auth.libraryDecision = false
|
|
596
|
-
auth.libraryCalls = 0
|
|
597
|
-
const denied = await post(row.payload(libB))
|
|
598
|
-
assert.equal(denied.res.status, 403, `${prefix.name} ${row.endpoint}: callback false must deny`)
|
|
599
|
-
assert.equal(auth.libraryCalls, 1)
|
|
600
|
-
|
|
601
|
-
auth.callbackMode = 'throw'
|
|
602
|
-
auth.libraryDecision = true
|
|
603
|
-
auth.libraryCalls = 0
|
|
604
|
-
const thrown = await post(row.payload(libB))
|
|
605
|
-
assert.equal(thrown.res.status, 403, `${prefix.name} ${row.endpoint}: a thrown callback must deny`)
|
|
606
|
-
|
|
607
|
-
auth.callbackMode = 'absent'
|
|
608
|
-
auth.libraryCalls = 0
|
|
609
|
-
const absent = await post(row.payload(libB))
|
|
610
|
-
assert.equal(absent.res.status, 200, `${prefix.name} ${row.endpoint}: a host without the callback falls back to the HTTP boundary (2026-11-01 flip)`)
|
|
611
|
-
assert.equal(auth.libraryCalls, 0)
|
|
612
|
-
auth.callbackMode = 'present'
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
})
|
|
616
|
-
|
|
617
|
-
// 全局词典(lib/lexicon.js 的 GLOBAL_LEXICON_ID)不是私有库:宿主不该被叫去授权一本
|
|
618
|
-
// 根本不存在的库,绑定中的会话也不该因为点名「全局」而不是自己的库就被判成越权。
|
|
619
|
-
// 会话侧仍要认凭证(会话存在 + 全局层没被天花板关掉);standalone 与 listGlobal 一样
|
|
620
|
-
// 只由 HTTP 边界把关。
|
|
621
|
-
test('the global lexicon is a shared store, not a library route', async () => {
|
|
622
|
-
const { GLOBAL_LEXICON_ID } = await import('../lib/lexicon.js')
|
|
623
|
-
for (const prefix of prefixes) {
|
|
624
|
-
const post = (payload) => send(prefix.route, prefix.base + '/lexiconList', { method: 'POST', body: envelope('lexiconList', payload) })
|
|
625
|
-
auth.callbackMode = 'present'
|
|
626
|
-
auth.libraryDecision = false
|
|
627
|
-
auth.libraryCalls = 0
|
|
628
|
-
const bound = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId })
|
|
629
|
-
assert.equal(bound.res.status, 200, `${prefix.name}: a bound session may address the global lexicon`)
|
|
630
|
-
assert.equal(auth.libraryCalls, 0, `${prefix.name}: the host must not be asked about a library that does not exist`)
|
|
631
|
-
const ghost = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId: 'auth-session-ghost' })
|
|
632
|
-
assert.equal(ghost.res.status, 403, `${prefix.name}: a dangling session id is never a credential`)
|
|
633
|
-
state.setSessionBinding(sessionId, { useGlobal: false })
|
|
634
|
-
const blocked = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId })
|
|
635
|
-
state.setSessionBinding(sessionId, { useGlobal: true })
|
|
636
|
-
assert.equal(blocked.res.status, 403, `${prefix.name}: useGlobal=false means there is no global lexicon for that conversation`)
|
|
637
|
-
auth.libraryDecision = false
|
|
638
|
-
auth.libraryCalls = 0
|
|
639
|
-
const solo = await post({ libraryId: GLOBAL_LEXICON_ID })
|
|
640
|
-
assert.equal(solo.res.status, 200, `${prefix.name}: the management plane is governed by the HTTP boundary`)
|
|
641
|
-
assert.equal(auth.libraryCalls, 0)
|
|
642
|
-
}
|
|
643
|
-
})
|
|
644
|
-
|
|
645
|
-
test('removed lexiconReview is no longer a library route and does not dispatch', async () => {
|
|
646
|
-
for (const prefix of prefixes) {
|
|
647
|
-
auth.callbackMode = 'present'
|
|
648
|
-
auth.libraryDecision = true
|
|
649
|
-
auth.libraryCalls = 0
|
|
650
|
-
const res = await send(prefix.route, prefix.base + '/lexiconReview', {
|
|
651
|
-
method: 'POST',
|
|
652
|
-
body: envelope('lexiconReview', { libraryId: library.id, termId: 'lex-matrix-scratch', action: 'approve' }),
|
|
653
|
-
})
|
|
654
|
-
assert.equal(res.res.status, 200, 'an unknown method is answered as a business error, not routed')
|
|
655
|
-
assert.equal(auth.libraryCalls, 0, 'lexiconReview must not be authorized as a library route anymore')
|
|
656
|
-
const json = JSON.parse(res.res.text)
|
|
657
|
-
assert.equal(json.result.ok, false)
|
|
658
|
-
assert.match(json.result.error.message, /unknown endpoint/)
|
|
659
|
-
}
|
|
660
|
-
// 401/403 仍然先于方法存在性:被拒的 review 请求连 dispatch 都到不了。
|
|
661
|
-
for (const prefix of prefixes) {
|
|
662
|
-
for (const code of [401, 403]) {
|
|
663
|
-
assertRejected(await send(prefix.route, prefix.base + '/lexiconReview', {
|
|
664
|
-
method: 'POST', poison: true, rejection: code,
|
|
665
|
-
body: envelope('lexiconReview', { libraryId: library.id, termId: 'lex-matrix-scratch', action: 'approve' }),
|
|
666
|
-
}), code)
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
})
|
|
670
|
-
|
|
671
|
-
test('session-bound resolution: write/archive without an explicit libraryId resolve from the persisted binding', async () => {
|
|
672
|
-
const rows = [
|
|
673
|
-
{ endpoint: 'updateMemory', payload: (session) => ({ sessionId: session, id: 'mem-matrix-scratch', patch: { title: 'fallback retitled' } }) },
|
|
674
|
-
{ endpoint: 'archiveMemory', payload: (session) => ({ sessionId: session, id: 'mem-matrix-scratch' }) },
|
|
675
|
-
]
|
|
676
|
-
for (const prefix of prefixes) {
|
|
677
|
-
seedMatrixScratch()
|
|
678
|
-
for (const row of rows) {
|
|
679
|
-
const post = (payload) => send(prefix.route, prefix.base + '/' + row.endpoint, { method: 'POST', body: envelope(row.endpoint, payload) })
|
|
680
|
-
auth.callbackMode = 'present'
|
|
681
|
-
auth.libraryDecision = true
|
|
682
|
-
auth.libraryCalls = 0
|
|
683
|
-
const own = await post(row.payload(sessionId))
|
|
684
|
-
assert.equal(own.res.status, 200, `${prefix.name} ${row.endpoint}: the bound session resolves its own library`)
|
|
685
|
-
assert.equal(auth.libraryCalls, 0)
|
|
686
|
-
for (const bad of ['', 'ghost-session', 42]) {
|
|
687
|
-
const denied = await post(row.payload(bad))
|
|
688
|
-
assert.equal(denied.res.status, 403, `${prefix.name} ${row.endpoint}: sessionId=${JSON.stringify(bad)} must not resolve to a target`)
|
|
689
|
-
assert.equal(denied.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
})
|
|
694
|
-
|
|
695
|
-
test('global review queue: embedded sessions may read, writes need a live binding, standalone needs review.manage', async () => {
|
|
696
|
-
const seedGlobalReview = () => {
|
|
697
|
-
state.updateGlobalIndex((index) => {
|
|
698
|
-
index.entries['mem-global-review'] = {
|
|
699
|
-
title: 'global review', content: 'global pending body', status: 'pending_review', layer: 'long_term',
|
|
700
|
-
domain: 'general', visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
|
|
701
|
-
reviewReason: 'matrix conflict', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
702
|
-
}
|
|
703
|
-
})
|
|
704
|
-
state.flushState()
|
|
705
|
-
}
|
|
706
|
-
const post = (prefix, endpoint, payload) => send(prefix.route, prefix.base + '/' + endpoint, { method: 'POST', body: envelope(endpoint, payload) })
|
|
707
|
-
|
|
708
|
-
for (const prefix of prefixes) {
|
|
709
|
-
seedGlobalReview()
|
|
710
|
-
auth.callbackMode = 'present'
|
|
711
|
-
auth.libraryDecision = true
|
|
712
|
-
auth.libraryCalls = 0
|
|
713
|
-
|
|
714
|
-
// Embedded read: a well-formed session reads the global queue without any
|
|
715
|
-
// host callback — the queue is conversation-visible by design.
|
|
716
|
-
const read = await post(prefix, 'listReviews', { sessionId })
|
|
717
|
-
assert.equal(read.res.status, 200)
|
|
718
|
-
const readJson = JSON.parse(read.res.text)
|
|
719
|
-
assert.equal(readJson.result.ok, true)
|
|
720
|
-
assert.equal(readJson.result.value.scope, 'global')
|
|
721
|
-
assert.ok(readJson.result.value.items.some((item) => item.id === 'mem-global-review'))
|
|
722
|
-
assert.equal(auth.libraryCalls, 0, 'embedded reads never consult the host callback')
|
|
723
|
-
|
|
724
|
-
// Embedded write: only a session whose binding still exists may resolve.
|
|
725
|
-
const resolved = await post(prefix, 'resolveReview', { sessionId, id: 'mem-global-review', action: 'reject', resolution: 'replace' })
|
|
726
|
-
assert.equal(resolved.res.status, 200)
|
|
727
|
-
assert.equal(JSON.parse(resolved.res.text).result.ok, true)
|
|
728
|
-
assert.equal(state.loadGlobalIndex().entries['mem-global-review'].status, 'archived')
|
|
729
|
-
|
|
730
|
-
for (const bad of ['', 'ghost-session']) {
|
|
731
|
-
seedGlobalReview()
|
|
732
|
-
auth.libraryCalls = 0
|
|
733
|
-
const denied = await post(prefix, 'resolveReview', { sessionId: bad, id: 'mem-global-review', action: 'reject' })
|
|
734
|
-
assert.equal(denied.res.status, 403, `${prefix.name} resolveReview with sessionId=${JSON.stringify(bad)} must fail closed`)
|
|
735
|
-
assert.equal(state.loadGlobalIndex().entries['mem-global-review'].status, 'pending_review', 'a denied review write must not touch the queue')
|
|
736
|
-
const readDenied = await post(prefix, 'listReviews', { sessionId: bad })
|
|
737
|
-
assert.equal(readDenied.res.status, 403, `${prefix.name} listReviews with sessionId=${JSON.stringify(bad)} must fail closed`)
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
// Standalone management plane: the global queue authorizes with
|
|
741
|
-
// libraryId null and the dedicated review.manage operation, and a host
|
|
742
|
-
// that does not implement it fails closed.
|
|
743
|
-
const standalone = async (endpoint, payload) => {
|
|
744
|
-
seedGlobalReview()
|
|
745
|
-
auth.callbackMode = 'present'
|
|
746
|
-
auth.libraryDecision = true
|
|
747
|
-
auth.libraryCalls = 0
|
|
748
|
-
auth.libraryRequests.length = 0
|
|
749
|
-
const granted = await post(prefix, endpoint, payload)
|
|
750
|
-
assert.equal(granted.res.status, 200, `${prefix.name} ${endpoint}: review.manage true must grant the standalone request`)
|
|
751
|
-
assert.equal(auth.libraryCalls, 1)
|
|
752
|
-
const request = auth.libraryRequests.at(-1)
|
|
753
|
-
assert.equal(request.libraryId, null, 'the global queue authorizes with libraryId null')
|
|
754
|
-
assert.equal(request.operation, 'review.manage')
|
|
755
|
-
|
|
756
|
-
auth.libraryDecision = false
|
|
757
|
-
auth.libraryCalls = 0
|
|
758
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: review.manage false must deny`)
|
|
759
|
-
assert.equal(auth.libraryCalls, 1)
|
|
760
|
-
|
|
761
|
-
auth.callbackMode = 'throw'
|
|
762
|
-
auth.libraryDecision = true
|
|
763
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: a thrown callback must deny`)
|
|
764
|
-
|
|
765
|
-
auth.callbackMode = 'absent'
|
|
766
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 200, `${prefix.name} ${endpoint}: a host without the callback falls back to the HTTP boundary (2026-11-01 flip)`)
|
|
767
|
-
auth.callbackMode = 'present'
|
|
768
|
-
}
|
|
769
|
-
await standalone('listReviews', {})
|
|
770
|
-
await standalone('resolveReview', { id: 'mem-global-review', action: 'reject' })
|
|
771
|
-
|
|
772
|
-
// The private branch keeps its library checks: a bound session cannot
|
|
773
|
-
// address another library's queue, and a granted standalone private read is
|
|
774
|
-
// a plain library read, not review.manage.
|
|
775
|
-
const privateLib = state.createLibrary({ name: 'auth-review-private', cwd: path.join(home, 'auth-review-private') })
|
|
776
|
-
auth.libraryDecision = true
|
|
777
|
-
assert.equal((await post(prefix, 'listReviews', { libraryId: privateLib.id, sessionId })).res.status, 403)
|
|
778
|
-
assert.equal((await post(prefix, 'resolveReview', { libraryId: privateLib.id, sessionId, id: 'mem-global-review', action: 'reject' })).res.status, 403)
|
|
779
|
-
auth.libraryRequests.length = 0
|
|
780
|
-
auth.libraryCalls = 0
|
|
781
|
-
const standalonePrivate = await post(prefix, 'listReviews', { libraryId: privateLib.id })
|
|
782
|
-
assert.equal(standalonePrivate.res.status, 200)
|
|
783
|
-
assert.equal(auth.libraryRequests.at(-1).operation, 'read', 'a private-queue read is a plain library read')
|
|
784
|
-
}
|
|
785
|
-
})
|
|
786
|
-
|
|
787
|
-
// 全局生命周期(1.3.12):scope:'global' 的 archiveMemory/updateMemory/deleteMemory
|
|
788
|
-
// 与全局复核队列同一管理面凭据模型——embedded 要活绑定、standalone 走 libraryId=null
|
|
789
|
-
// 的 review.manage;scope 与 libraryId 同时出现是作用域冲突,先于 dispatch 拒绝。
|
|
790
|
-
test('global lifecycle: scope global follows the global management credential model', async () => {
|
|
791
|
-
const seedGlobalActive = () => {
|
|
792
|
-
state.updateGlobalIndex((index) => {
|
|
793
|
-
index.entries['mem-global-lifecycle'] = {
|
|
794
|
-
title: 'global lifecycle', content: 'global lifecycle body', status: 'active', layer: 'long_term',
|
|
795
|
-
domain: 'general', visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
|
|
796
|
-
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
797
|
-
}
|
|
798
|
-
})
|
|
799
|
-
state.flushState()
|
|
800
|
-
}
|
|
801
|
-
const post = (prefix, endpoint, payload) => send(prefix.route, prefix.base + '/' + endpoint, { method: 'POST', body: envelope(endpoint, payload) })
|
|
802
|
-
for (const prefix of prefixes) {
|
|
803
|
-
seedGlobalActive()
|
|
804
|
-
auth.callbackMode = 'present'
|
|
805
|
-
auth.libraryDecision = true
|
|
806
|
-
auth.libraryCalls = 0
|
|
807
|
-
const embedded = await post(prefix, 'archiveMemory', { scope: 'global', sessionId, id: 'mem-global-lifecycle' })
|
|
808
|
-
assert.equal(embedded.res.status, 200, `${prefix.name}: a live binding may archive global memory without the host callback`)
|
|
809
|
-
assert.equal(JSON.parse(embedded.res.text).result.ok, true)
|
|
810
|
-
assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'archived')
|
|
811
|
-
assert.equal(auth.libraryCalls, 0)
|
|
812
|
-
|
|
813
|
-
seedGlobalActive()
|
|
814
|
-
const ghost = await post(prefix, 'archiveMemory', { scope: 'global', sessionId: 'ghost-session', id: 'mem-global-lifecycle' })
|
|
815
|
-
assert.equal(ghost.res.status, 403, `${prefix.name}: a dangling session is never a credential`)
|
|
816
|
-
assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'active', 'a denied write must not touch the store')
|
|
817
|
-
|
|
818
|
-
const conflict = await post(prefix, 'archiveMemory', { scope: 'global', libraryId: 'lib-whatever', id: 'mem-global-lifecycle' })
|
|
819
|
-
assert.equal(conflict.res.status, 403, `${prefix.name}: scope global alongside a libraryId is a scope conflict`)
|
|
820
|
-
|
|
821
|
-
const rows = [
|
|
822
|
-
['archiveMemory', { scope: 'global', id: 'mem-global-lifecycle' }],
|
|
823
|
-
['updateMemory', { scope: 'global', id: 'mem-global-lifecycle', patch: { status: 'active' } }],
|
|
824
|
-
['deleteMemory', { scope: 'global', id: 'mem-global-lifecycle', confirmed: true }],
|
|
825
|
-
]
|
|
826
|
-
for (const [endpoint, payload] of rows) {
|
|
827
|
-
seedGlobalActive()
|
|
828
|
-
if (endpoint !== 'archiveMemory') {
|
|
829
|
-
state.updateGlobalIndex((index) => { index.entries['mem-global-lifecycle'].status = 'archived' })
|
|
830
|
-
}
|
|
831
|
-
auth.callbackMode = 'present'
|
|
832
|
-
auth.libraryDecision = true
|
|
833
|
-
auth.libraryCalls = 0
|
|
834
|
-
auth.libraryRequests.length = 0
|
|
835
|
-
const granted = await post(prefix, endpoint, payload)
|
|
836
|
-
assert.equal(granted.res.status, 200, `${prefix.name} ${endpoint}: review.manage true must grant`)
|
|
837
|
-
assert.equal(JSON.parse(granted.res.text).result.ok, true)
|
|
838
|
-
assert.equal(auth.libraryCalls, 1)
|
|
839
|
-
assert.equal(auth.libraryRequests.at(-1).libraryId, null, 'global lifecycle authorizes with libraryId null')
|
|
840
|
-
assert.equal(auth.libraryRequests.at(-1).operation, 'review.manage')
|
|
841
|
-
|
|
842
|
-
seedGlobalActive()
|
|
843
|
-
auth.libraryDecision = false
|
|
844
|
-
auth.libraryCalls = 0
|
|
845
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: review.manage false must deny`)
|
|
846
|
-
assert.equal(auth.libraryCalls, 1)
|
|
847
|
-
|
|
848
|
-
auth.callbackMode = 'throw'
|
|
849
|
-
auth.libraryDecision = true
|
|
850
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: a thrown callback must deny`)
|
|
851
|
-
|
|
852
|
-
auth.callbackMode = 'absent'
|
|
853
|
-
assert.equal((await post(prefix, endpoint, payload)).res.status, 200, `${prefix.name} ${endpoint}: absent callback falls back to the HTTP boundary`)
|
|
854
|
-
auth.callbackMode = 'present'
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
})
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
// ----
|
|
861
|
-
// 无 libraryId 的 browseWall("全部记忆库"视图)曾被硬拒 403:capability 缺席的宿主
|
|
862
|
-
// 上整个记忆墙挂掉。契约:无 libraryId 走同一 capability 模型——缺席回退放行、实现
|
|
863
|
-
// 了回调的宿主由 callback 决定;403 响应必须是 JSON 信封(standalone fetch 会
|
|
864
|
-
// response.json(),裸文本抛 SyntaxError)。
|
|
865
|
-
|
|
866
|
-
test('browseWall all-libraries view: absent capability allows, present callback decides, envelope on 403', async () => {
|
|
867
|
-
state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
|
|
868
|
-
const lib = state.createLibrary({ name: 'auth-wall-all', cwd: path.join(home, 'auth-wall-all') })
|
|
869
|
-
state.updatePrivateIndex(lib.id, (index) => {
|
|
870
|
-
index.entries['mem-wall-all'] = { title: 'wall all body', content: 'wall all body', status: 'active', layer: 'long_term', visibility: 'shared', disclosure: 'can_tell', source: 'user_said', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
|
871
|
-
})
|
|
872
|
-
state.flushState()
|
|
873
|
-
|
|
874
|
-
for (const prefix of prefixes) {
|
|
875
|
-
// capability 缺席(当前版本宿主):跨库视图放行——记忆墙的核心视图不能 403。
|
|
876
|
-
auth.libraryCalls = 0
|
|
877
|
-
const allowed = await send(prefix.route, prefix.base + '/browseWall', { method: 'POST', body: envelope('browseWall', { libraryId: '' }) })
|
|
878
|
-
assert.equal(allowed.res.status, 200, `${prefix.name} browseWall(''): absent capability falls back to the HTTP boundary`)
|
|
879
|
-
const payload = JSON.parse(allowed.res.text)
|
|
880
|
-
assert.ok(payload.result.value.items.length >= 1, 'the wall returns entries across libraries')
|
|
881
|
-
|
|
882
|
-
// 实现了 capability 的宿主:多库枚举由回调决定(deny → 403 JSON 信封)。
|
|
883
|
-
auth.libraryDecision = false
|
|
884
|
-
auth.libraryCalls = 0
|
|
885
|
-
const denied = await send(prefix.route, prefix.base + '/browseWall', { method: 'POST', body: envelope('browseWall', { libraryId: '' }) })
|
|
886
|
-
assert.equal(denied.res.status, 403, 'a host that implements the capability may deny the multi-library read')
|
|
887
|
-
assert.equal(auth.libraryCalls, 1, 'present capability is consulted for the multi-library read')
|
|
888
|
-
|
|
889
|
-
// 403 响应体必须是 JSON 信封:standalone fetch 客户端 response.json() 之后再读
|
|
890
|
-
// error.message
|
|
891
|
-
assert.equal(denied.res.headers['content-type'] || denied.res.headers['Content-Type'], 'application/json')
|
|
892
|
-
const parsed = JSON.parse(denied.res.text)
|
|
893
|
-
assert.equal(parsed.ok, false)
|
|
894
|
-
assert.equal(parsed.error.code, 'dsh-memu-memory/forbidden')
|
|
895
|
-
assert.equal(typeof parsed.error.message, 'string')
|
|
896
|
-
auth.libraryDecision = true
|
|
897
|
-
}
|
|
898
|
-
})
|
|
899
|
-
|
|
900
|
-
// standalone fetch 包装器:403 信封透传 error.message,而不是只报状态码
|
|
901
|
-
//
|
|
902
|
-
test('standalone rpc wrapper surfaces the server error message instead of the status code', () => {
|
|
903
|
-
const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
|
|
904
|
-
assert.match(client, /envelope\.error\?\.message \|\| \('Invalid RPC response: ' \+ response\.status\)/)
|
|
905
|
-
})
|
|
906
|
-
|
|
907
|
-
// 0.2.3-alpha.1 起宿主把 connection.requestRejection 换成 connection.admit。
|
|
908
|
-
// 只探测前者(或只探测挂在模块而非服务上的 isTrustedApiRequest)的守卫在新宿主上会静默放行。
|
|
909
|
-
test('a host that only exposes connection.admit stays guarded', async () => {
|
|
910
|
-
const routes = []
|
|
911
|
-
const admit = { calls: 0, decision: undefined }
|
|
912
|
-
registerRpc({
|
|
913
|
-
inject: (_deps, build) => build({
|
|
914
|
-
effect: (fn) => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
|
|
915
|
-
webServer: { register: (spec) => { routes.push(spec); return () => {} } },
|
|
916
|
-
connection: { admit: () => { admit.calls += 1; return admit.decision } },
|
|
917
|
-
logger: {},
|
|
918
|
-
}),
|
|
919
|
-
})
|
|
920
|
-
const route = routes.find(spec => spec.path === '/dsh-memu-memory')
|
|
921
|
-
assert.ok(route, 'the admit-only host registered its RPC route')
|
|
922
|
-
const fire = async (decision) => {
|
|
923
|
-
admit.decision = decision
|
|
924
|
-
admit.calls = 0
|
|
925
|
-
resetProbe()
|
|
926
|
-
const chunks = []
|
|
927
|
-
let resolveDone
|
|
928
|
-
const done = new Promise((resolve) => { resolveDone = resolve })
|
|
929
|
-
const timer = setTimeout(() => resolveDone(new Error('response did not end')), 3000)
|
|
930
|
-
timer.unref?.()
|
|
931
|
-
const res = {
|
|
932
|
-
status: 0,
|
|
933
|
-
writeHead(code) { this.status = code; return this },
|
|
934
|
-
write() { return true },
|
|
935
|
-
end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); resolveDone() },
|
|
936
|
-
get text() { return Buffer.concat(chunks).toString('utf8') },
|
|
937
|
-
}
|
|
938
|
-
const req = {
|
|
939
|
-
method: 'POST', url: '/dsh-memu-memory', headers: {},
|
|
940
|
-
async *[Symbol.asyncIterator]() { chunks.push(Buffer.from('body read')) },
|
|
941
|
-
}
|
|
942
|
-
probe.active = true
|
|
943
|
-
try {
|
|
944
|
-
await route.handler(req, res)
|
|
945
|
-
await done
|
|
946
|
-
} finally { probe.active = false }
|
|
947
|
-
return { status: res.status, text: res.text, admitCalls: admit.calls, reads: [...probe.reads], writes: [...probe.writes] }
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
const refused = await fire({ rejection: 403 })
|
|
951
|
-
assert.equal(refused.status, 403, 'admit rejection becomes the HTTP status')
|
|
952
|
-
assert.equal(refused.admitCalls, 1, 'admit runs exactly once')
|
|
953
|
-
assert.equal(refused.text.includes('body read'), false, 'the body is not read before admission')
|
|
954
|
-
assert.deepEqual(refused.reads, [])
|
|
955
|
-
assert.deepEqual(refused.writes, [])
|
|
956
|
-
|
|
957
|
-
const admitted = await fire({ peer: {} })
|
|
958
|
-
assert.ok(admitted.status !== 403 && admitted.status !== 401, 'an admitted peer passes the guard')
|
|
959
|
-
assert.equal(admitted.admitCalls, 1)
|
|
960
|
-
// §13.6:这台宿主实际走了哪一级探测,要能在指纹里读到(台账核对用的就是这一行)。
|
|
961
|
-
const surface = await import('../lib/host-surface.js')
|
|
962
|
-
assert.equal(surface.hostSurface().rpcGuard, 'admit', 'the probe records which guard shape this host exposes')
|
|
963
|
-
})
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import sharp from 'sharp'
|
|
8
|
+
import { zipSync, unzipSync } from 'fflate'
|
|
9
|
+
|
|
10
|
+
// W4: every browser-facing entry of this plugin goes through one handler mounted
|
|
11
|
+
// twice (current and legacy prefix). The tests below drive each registered route
|
|
12
|
+
// separately and prove that a 401/403 is decided before body parsing, index or
|
|
13
|
+
// attachment reads, state writes, and imports.
|
|
14
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-webui-auth-'))
|
|
15
|
+
process.env.DSH_MEMU_HOME = home
|
|
16
|
+
|
|
17
|
+
const state = await import('../lib/state.js')
|
|
18
|
+
const { registerRpc } = await import('../lib/rpc.js')
|
|
19
|
+
const { standaloneHtml, standaloneAsset } = await import('../lib/webui.js')
|
|
20
|
+
|
|
21
|
+
test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
|
|
22
|
+
|
|
23
|
+
const html = standaloneHtml()
|
|
24
|
+
const clientJs = standaloneAsset('/dsh-memu-memory/ui-assets/client.js')
|
|
25
|
+
const iconPng = standaloneAsset('/dsh-memu-memory/ui-assets/icon.png')
|
|
26
|
+
|
|
27
|
+
const routeSpecs = []
|
|
28
|
+
// callbackMode: 'present' | 'throw' | 'absent' — 'absent' models a host that
|
|
29
|
+
// does not implement authorizeLibrary at all (typeof check must fail).
|
|
30
|
+
const auth = { decision: undefined, calls: 0, libraryDecision: true, libraryCalls: 0, libraryRequests: [], callbackMode: 'present' }
|
|
31
|
+
registerRpc({
|
|
32
|
+
inject: (_deps, build) => build({
|
|
33
|
+
effect: (fn) => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
|
|
34
|
+
webServer: { register: (spec) => { routeSpecs.push(spec); return () => {} } },
|
|
35
|
+
connection: {
|
|
36
|
+
requestRejection: () => { auth.calls += 1; return auth.decision },
|
|
37
|
+
get authorizeLibrary() {
|
|
38
|
+
if (auth.callbackMode === 'absent') return undefined
|
|
39
|
+
return async (req, details) => {
|
|
40
|
+
auth.libraryCalls += 1
|
|
41
|
+
auth.libraryRequests.push({ req, ...details })
|
|
42
|
+
if (auth.callbackMode === 'throw') throw new Error('host authorization unavailable')
|
|
43
|
+
return auth.libraryDecision
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
logger: {},
|
|
48
|
+
}),
|
|
49
|
+
})
|
|
50
|
+
assert.deepEqual(routeSpecs.map((spec) => spec.path), ['/dsh-memu-memory', '/dsh-memu'])
|
|
51
|
+
assert.equal(typeof routeSpecs[0].handler, 'function')
|
|
52
|
+
assert.equal(typeof routeSpecs[1].handler, 'function')
|
|
53
|
+
const prefixes = [
|
|
54
|
+
{ name: 'formal', route: routeSpecs[0], base: '/dsh-memu-memory' },
|
|
55
|
+
{ name: 'legacy', route: routeSpecs[1], base: '/dsh-memu' },
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
const homeRoot = path.resolve(home)
|
|
59
|
+
const probe = { active: false, reads: [], writes: [] }
|
|
60
|
+
const originals = new Map()
|
|
61
|
+
function inHome(file) {
|
|
62
|
+
if (typeof file !== 'string') return false
|
|
63
|
+
const resolved = path.resolve(file)
|
|
64
|
+
return resolved === homeRoot || resolved.startsWith(homeRoot + path.sep)
|
|
65
|
+
}
|
|
66
|
+
function relative(file) { return path.relative(homeRoot, path.resolve(file)).replace(/\\/g, '/') }
|
|
67
|
+
function wrap(name, mode) {
|
|
68
|
+
const original = fs[name]
|
|
69
|
+
originals.set(name, original)
|
|
70
|
+
fs[name] = function (file, ...args) {
|
|
71
|
+
if (probe.active && inHome(file)) (mode === 'write' ? probe.writes : probe.reads).push(relative(file))
|
|
72
|
+
return original.call(this, file, ...args)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const name of ['readFileSync', 'readdirSync', 'existsSync', 'statSync', 'lstatSync', 'createReadStream']) wrap(name, 'read')
|
|
76
|
+
for (const name of ['writeFileSync', 'appendFileSync', 'renameSync', 'mkdirSync', 'rmSync', 'unlinkSync', 'copyFileSync']) wrap(name, 'write')
|
|
77
|
+
{
|
|
78
|
+
const openSync = fs.openSync
|
|
79
|
+
originals.set('openSync', openSync)
|
|
80
|
+
fs.openSync = function (file, flags, ...args) {
|
|
81
|
+
if (probe.active && inHome(file)) {
|
|
82
|
+
const text = typeof flags === 'string' ? flags : 'r'
|
|
83
|
+
const write = /[wa+]/.test(text)
|
|
84
|
+
;(write ? probe.writes : probe.reads).push(relative(file))
|
|
85
|
+
}
|
|
86
|
+
return openSync.call(this, file, flags, ...args)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function resetProbe() { probe.reads.length = 0; probe.writes.length = 0 }
|
|
90
|
+
|
|
91
|
+
function makeResponse() {
|
|
92
|
+
const chunks = []
|
|
93
|
+
let finish
|
|
94
|
+
const done = new Promise((resolve, reject) => {
|
|
95
|
+
finish = resolve
|
|
96
|
+
const timer = setTimeout(() => reject(new Error('response did not end')), 3000)
|
|
97
|
+
timer.unref?.()
|
|
98
|
+
})
|
|
99
|
+
return {
|
|
100
|
+
status: 0,
|
|
101
|
+
headers: {},
|
|
102
|
+
destroyed: false,
|
|
103
|
+
done,
|
|
104
|
+
writeHead(code, headers) { this.status = code; this.headers = headers || {}; return this },
|
|
105
|
+
write(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); return true },
|
|
106
|
+
end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); finish() },
|
|
107
|
+
destroy(error) { this.destroyed = true; this.error = error; finish() },
|
|
108
|
+
get buffer() { return Buffer.concat(chunks) },
|
|
109
|
+
get text() { return Buffer.concat(chunks).toString('utf8') },
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function send(route, url, { method = 'GET', body, rejection, poison = false } = {}) {
|
|
114
|
+
auth.decision = rejection
|
|
115
|
+
auth.calls = 0
|
|
116
|
+
resetProbe()
|
|
117
|
+
probe.active = true
|
|
118
|
+
const pulls = []
|
|
119
|
+
const req = {
|
|
120
|
+
method,
|
|
121
|
+
url,
|
|
122
|
+
headers: {},
|
|
123
|
+
async *[Symbol.asyncIterator]() {
|
|
124
|
+
pulls.push(auth.calls)
|
|
125
|
+
if (poison) throw new Error('the body was read before authentication')
|
|
126
|
+
if (body !== undefined) yield Buffer.isBuffer(body) ? body : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body))
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
const res = makeResponse()
|
|
130
|
+
try {
|
|
131
|
+
await route.handler(req, res)
|
|
132
|
+
await res.done
|
|
133
|
+
} finally {
|
|
134
|
+
probe.active = false
|
|
135
|
+
}
|
|
136
|
+
return { res, pulls, authCalls: auth.calls, reads: [...probe.reads], writes: [...probe.writes] }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function envelope(method, payload = {}, rpcId = 'auth-test') {
|
|
140
|
+
return { type: 'client-request', rpcId, method, payload }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function assertRejected(result, code) {
|
|
144
|
+
assert.equal(result.res.status, code)
|
|
145
|
+
assert.equal(result.res.text, code === 401 ? 'unauthorized' : 'forbidden')
|
|
146
|
+
assert.equal(result.pulls.length, 0, 'request body must not be iterated before requestRejection')
|
|
147
|
+
assert.equal(result.authCalls, 1, 'requestRejection must run exactly once')
|
|
148
|
+
assert.deepEqual(result.reads, [], 'rejected request must not read anything under DSH_MEMU_HOME')
|
|
149
|
+
assert.deepEqual(result.writes, [], 'rejected request must not write anything under DSH_MEMU_HOME')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function snapshotTree(root) {
|
|
153
|
+
const files = {}
|
|
154
|
+
const walk = (dir) => {
|
|
155
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
156
|
+
const full = path.join(dir, entry.name)
|
|
157
|
+
const rel = path.relative(root, full).replace(/\\/g, '/')
|
|
158
|
+
if (entry.isDirectory()) { files[rel + '/'] = true; walk(full) }
|
|
159
|
+
else { const data = fs.readFileSync(full); files[rel] = data.length + ':' + crypto.createHash('sha256').update(data).digest('hex') }
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
walk(root)
|
|
163
|
+
return files
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const SENTINEL = 'AUTH-SENTINEL-7f3c2a'
|
|
167
|
+
const IMPORT_SENTINEL = 'IMPORT-SENTINEL-91b0d4'
|
|
168
|
+
const RPC_IMPORT_SENTINEL = 'RPC-IMPORT-SENTINEL-4c8e11'
|
|
169
|
+
|
|
170
|
+
const library = state.createLibrary({ name: 'auth-matrix', cwd: path.join(home, 'auth-matrix') })
|
|
171
|
+
const sessionId = 'auth-session'
|
|
172
|
+
state.setSessionBinding(sessionId, { libraryId: library.id, useLibrary: true, scopeKey: library.scopeKey })
|
|
173
|
+
state.updatePrivateIndex(library.id, (index) => {
|
|
174
|
+
index.entries['mem-auth-sentinel'] = {
|
|
175
|
+
title: 'auth sentinel', content: SENTINEL, status: 'active', layer: 'long_term',
|
|
176
|
+
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
177
|
+
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
state.flushState()
|
|
181
|
+
|
|
182
|
+
test('UI and assets: both registered prefixes authorize, and 401/403 never serve or read', async () => {
|
|
183
|
+
const cases = [
|
|
184
|
+
{ route: '/ui', expected: html, type: /text\/html/ },
|
|
185
|
+
{ route: '/settings', expected: html, type: /text\/html/ },
|
|
186
|
+
{ route: '/ui-assets/client.js', expected: clientJs, type: /javascript/ },
|
|
187
|
+
{ route: '/ui-assets/icon.png', expected: iconPng, type: /image\/png/ },
|
|
188
|
+
]
|
|
189
|
+
for (const prefix of prefixes) {
|
|
190
|
+
for (const item of cases) {
|
|
191
|
+
const url = prefix.base + item.route
|
|
192
|
+
const allowed = await send(prefix.route, url)
|
|
193
|
+
assert.equal(allowed.res.status, 200, prefix.name + ' ' + item.route)
|
|
194
|
+
assert.match(allowed.res.headers['Content-Type'], item.type)
|
|
195
|
+
assert.deepEqual(allowed.res.buffer, Buffer.from(item.expected))
|
|
196
|
+
for (const code of [401, 403]) {
|
|
197
|
+
assertRejected(await send(prefix.route, url, { rejection: code }), code)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
test('POST RPC: requestRejection runs before body parsing and before any write', async () => {
|
|
204
|
+
for (const prefix of prefixes) {
|
|
205
|
+
for (const code of [401, 403]) {
|
|
206
|
+
state.flushState()
|
|
207
|
+
const baseline = snapshotTree(home)
|
|
208
|
+
const name = 'denied-' + prefix.name + '-' + code
|
|
209
|
+
const result = await send(prefix.route, prefix.base + '/createLibrary', {
|
|
210
|
+
method: 'POST', poison: true, rejection: code,
|
|
211
|
+
body: envelope('createLibrary', { name, cwd: path.join(home, name) }),
|
|
212
|
+
})
|
|
213
|
+
assertRejected(result, code)
|
|
214
|
+
assert.equal(state.listLibraries().some((item) => item.name === name), false)
|
|
215
|
+
assert.deepEqual(snapshotTree(home), baseline, 'a rejected createLibrary must not touch state.json')
|
|
216
|
+
}
|
|
217
|
+
const name = 'allowed-' + prefix.name
|
|
218
|
+
const result = await send(prefix.route, prefix.base + '/createLibrary', {
|
|
219
|
+
method: 'POST', body: envelope('createLibrary', { name, cwd: path.join(home, name) }),
|
|
220
|
+
})
|
|
221
|
+
assert.equal(result.res.status, 200)
|
|
222
|
+
const json = JSON.parse(result.res.text)
|
|
223
|
+
assert.equal(json.result.ok, true)
|
|
224
|
+
assert.equal(json.result.value.name, name)
|
|
225
|
+
assert.equal(result.authCalls, 1)
|
|
226
|
+
assert.equal(result.pulls.length, 1)
|
|
227
|
+
assert.equal(result.pulls[0], 1, 'authorized body iteration must happen after requestRejection')
|
|
228
|
+
assert.ok(result.writes.length > 0, 'authorized createLibrary must write the library')
|
|
229
|
+
}
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
test('GET-side RPC reads: 401/403 return before the private index is read', async () => {
|
|
233
|
+
const urlFor = (prefix) => prefix.base + '/getMemory'
|
|
234
|
+
for (const prefix of prefixes) {
|
|
235
|
+
for (const code of [401, 403]) {
|
|
236
|
+
state.flushState()
|
|
237
|
+
state.clearCaches()
|
|
238
|
+
const baseline = snapshotTree(home)
|
|
239
|
+
const denied = await send(prefix.route, urlFor(prefix), {
|
|
240
|
+
method: 'POST', poison: true, rejection: code,
|
|
241
|
+
body: envelope('getMemory', { libraryId: library.id, id: 'mem-auth-sentinel' }),
|
|
242
|
+
})
|
|
243
|
+
assertRejected(denied, code)
|
|
244
|
+
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
245
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
246
|
+
}
|
|
247
|
+
state.flushState()
|
|
248
|
+
state.clearCaches()
|
|
249
|
+
const allowed = await send(prefix.route, urlFor(prefix), {
|
|
250
|
+
method: 'POST', body: envelope('getMemory', { libraryId: library.id, id: 'mem-auth-sentinel' }),
|
|
251
|
+
})
|
|
252
|
+
assert.equal(allowed.res.status, 200)
|
|
253
|
+
assert.match(allowed.res.text, new RegExp(SENTINEL))
|
|
254
|
+
assert.ok(allowed.reads.length > 0, 'authorized getMemory must read the private index from disk')
|
|
255
|
+
assert.equal(allowed.pulls[0], 1)
|
|
256
|
+
}
|
|
257
|
+
})
|
|
258
|
+
|
|
259
|
+
test('library authorization: session A cannot address library B, and standalone callback fails closed', async () => {
|
|
260
|
+
const other = state.createLibrary({ name: 'auth-other', cwd: path.join(home, 'auth-other') })
|
|
261
|
+
state.setSessionBinding('auth-session-other', { libraryId: other.id, useLibrary: true, scopeKey: other.scopeKey })
|
|
262
|
+
for (const prefix of prefixes) {
|
|
263
|
+
auth.callbackMode = 'present'
|
|
264
|
+
auth.libraryDecision = true
|
|
265
|
+
auth.libraryCalls = 0
|
|
266
|
+
auth.libraryRequests.length = 0
|
|
267
|
+
const cross = await send(prefix.route, prefix.base + '/getMemory', {
|
|
268
|
+
method: 'POST',
|
|
269
|
+
body: envelope('getMemory', { libraryId: other.id, sessionId, id: 'mem-auth-sentinel' }),
|
|
270
|
+
})
|
|
271
|
+
assert.equal(cross.res.status, 403)
|
|
272
|
+
assert.equal(cross.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
273
|
+
assert.equal(cross.pulls.length, 1, 'JSON body may be parsed before route authorization')
|
|
274
|
+
assert.equal(auth.libraryCalls, 0, 'bound sessions must not fall back to host callback')
|
|
275
|
+
assert.deepEqual(cross.reads, [])
|
|
276
|
+
assert.deepEqual(cross.writes, [])
|
|
277
|
+
|
|
278
|
+
auth.libraryDecision = false
|
|
279
|
+
auth.libraryCalls = 0
|
|
280
|
+
const denied = await send(prefix.route, prefix.base + '/getMemory', {
|
|
281
|
+
method: 'POST',
|
|
282
|
+
body: envelope('getMemory', { libraryId: other.id }),
|
|
283
|
+
})
|
|
284
|
+
assert.equal(denied.res.status, 403)
|
|
285
|
+
assert.equal(auth.libraryCalls, 1)
|
|
286
|
+
assert.equal(denied.reads.length, 0)
|
|
287
|
+
assert.equal(denied.writes.length, 0)
|
|
288
|
+
|
|
289
|
+
auth.libraryDecision = true
|
|
290
|
+
auth.callbackMode = 'throw'
|
|
291
|
+
auth.libraryCalls = 0
|
|
292
|
+
const thrown = await send(prefix.route, prefix.base + '/getMemory', {
|
|
293
|
+
method: 'POST', poison: false,
|
|
294
|
+
body: envelope('getMemory', { libraryId: other.id }),
|
|
295
|
+
})
|
|
296
|
+
assert.equal(thrown.res.status, 403)
|
|
297
|
+
assert.equal(auth.libraryCalls, 1)
|
|
298
|
+
assert.equal(thrown.reads.length, 0)
|
|
299
|
+
assert.equal(thrown.writes.length, 0)
|
|
300
|
+
|
|
301
|
+
auth.callbackMode = 'present'
|
|
302
|
+
auth.libraryDecision = true
|
|
303
|
+
}
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
test('attachment thumbnails: 401/403 precede authorization and attachment-pool reads', async () => {
|
|
307
|
+
const attachmentLibrary = state.createLibrary({ name: 'auth-attachment', cwd: path.join(home, 'auth-attachment') })
|
|
308
|
+
const attachmentSession = 'auth-attachment-session'
|
|
309
|
+
state.setSessionBinding(attachmentSession, { libraryId: attachmentLibrary.id, useLibrary: true, scopeKey: attachmentLibrary.scopeKey })
|
|
310
|
+
const png = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#336699' } }).png().toBuffer()
|
|
311
|
+
const sha = crypto.createHash('sha256').update(png).digest('hex')
|
|
312
|
+
const blobPath = path.join(home, 'attachments', attachmentLibrary.id, sha + '.png')
|
|
313
|
+
fs.mkdirSync(path.dirname(blobPath), { recursive: true })
|
|
314
|
+
fs.writeFileSync(blobPath, png)
|
|
315
|
+
const poolPath = path.join(home, 'index', attachmentLibrary.id + '.media.json')
|
|
316
|
+
const pool = {
|
|
317
|
+
version: 1,
|
|
318
|
+
blobs: { [sha]: { sha256: sha, bytes: png.length, ext: 'png', mime: 'image/png', w: 8, h: 8, useCount: 1, refs: [], missing: false, captionBy: 'none' } },
|
|
319
|
+
totals: { bytes: png.length, count: 1 },
|
|
320
|
+
}
|
|
321
|
+
fs.writeFileSync(poolPath, JSON.stringify(pool))
|
|
322
|
+
state.updatePrivateIndex(attachmentLibrary.id, (index) => {
|
|
323
|
+
index.entries['mem-auth-image'] = {
|
|
324
|
+
title: 'auth image', content: 'attachment sentinel ' + SENTINEL, status: 'active', layer: 'long_term',
|
|
325
|
+
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
326
|
+
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
327
|
+
attachments: [{ sha256: sha, name: 'auth.png', mediaType: 'image/png', bytes: png.length }],
|
|
328
|
+
}
|
|
329
|
+
})
|
|
330
|
+
state.flushState()
|
|
331
|
+
const url = (prefix) => prefix.base + '/attachment/' + encodeURIComponent(attachmentLibrary.id) + '/' + sha + '?sessionId=' + encodeURIComponent(attachmentSession)
|
|
332
|
+
for (const prefix of prefixes) {
|
|
333
|
+
state.flushState()
|
|
334
|
+
state.clearCaches()
|
|
335
|
+
const allowed = await send(prefix.route, url(prefix))
|
|
336
|
+
assert.equal(allowed.res.status, 200)
|
|
337
|
+
assert.match(allowed.res.headers['Content-Type'], /image\/webp/)
|
|
338
|
+
assert.ok(allowed.res.buffer.length > 0)
|
|
339
|
+
assert.ok(allowed.reads.some((item) => item.endsWith('.media.json')), 'authorized thumbnail reads the media pool')
|
|
340
|
+
}
|
|
341
|
+
for (const prefix of prefixes) {
|
|
342
|
+
for (const code of [401, 403]) {
|
|
343
|
+
state.flushState()
|
|
344
|
+
state.clearCaches()
|
|
345
|
+
const baseline = snapshotTree(home)
|
|
346
|
+
const denied = await send(prefix.route, url(prefix), { rejection: code })
|
|
347
|
+
assertRejected(denied, code)
|
|
348
|
+
assert.equal(denied.res.text.includes('attachment unavailable'), false)
|
|
349
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
for (const prefix of prefixes) {
|
|
353
|
+
const rpcPayload = { libraryId: attachmentLibrary.id, sha256: sha, sessionId: attachmentSession }
|
|
354
|
+
for (const code of [401, 403]) {
|
|
355
|
+
state.flushState()
|
|
356
|
+
state.clearCaches()
|
|
357
|
+
const baseline = snapshotTree(home)
|
|
358
|
+
const denied = await send(prefix.route, prefix.base + '/getAttachment', {
|
|
359
|
+
method: 'POST', poison: true, rejection: code, body: envelope('getAttachment', rpcPayload),
|
|
360
|
+
})
|
|
361
|
+
assertRejected(denied, code)
|
|
362
|
+
assert.equal(denied.res.text.includes(sha), false)
|
|
363
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
364
|
+
}
|
|
365
|
+
state.flushState()
|
|
366
|
+
state.clearCaches()
|
|
367
|
+
const allowed = await send(prefix.route, prefix.base + '/getAttachment', {
|
|
368
|
+
method: 'POST', body: envelope('getAttachment', rpcPayload),
|
|
369
|
+
})
|
|
370
|
+
assert.equal(allowed.res.status, 200)
|
|
371
|
+
const json = JSON.parse(allowed.res.text)
|
|
372
|
+
assert.equal(json.result.ok, true)
|
|
373
|
+
assert.equal(json.result.value.sha256, sha)
|
|
374
|
+
assert.equal(allowed.pulls[0], 1)
|
|
375
|
+
}
|
|
376
|
+
// Tripwire: a corrupt pool makes an authorized thumbnail fail inside the media
|
|
377
|
+
// path, so a 401/403 instead of that failure proves rejection happened first.
|
|
378
|
+
fs.writeFileSync(poolPath, '{not valid json')
|
|
379
|
+
for (const prefix of prefixes) {
|
|
380
|
+
state.flushState()
|
|
381
|
+
state.clearCaches()
|
|
382
|
+
const tripwire = await send(prefix.route, url(prefix))
|
|
383
|
+
assert.equal(tripwire.res.status, 503)
|
|
384
|
+
assert.equal(tripwire.res.text, 'attachment unavailable')
|
|
385
|
+
for (const code of [401, 403]) {
|
|
386
|
+
const denied = await send(prefix.route, url(prefix), { rejection: code })
|
|
387
|
+
assertRejected(denied, code)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
fs.writeFileSync(poolPath, JSON.stringify(pool))
|
|
391
|
+
})
|
|
392
|
+
|
|
393
|
+
test('export ZIP: 401/403 precede export dispatch, index reads and ZIP construction', async () => {
|
|
394
|
+
for (const prefix of prefixes) {
|
|
395
|
+
for (const code of [401, 403]) {
|
|
396
|
+
state.flushState()
|
|
397
|
+
state.clearCaches()
|
|
398
|
+
const baseline = snapshotTree(home)
|
|
399
|
+
const denied = await send(prefix.route, prefix.base + '/export/' + library.id + '.zip', { rejection: code })
|
|
400
|
+
assertRejected(denied, code)
|
|
401
|
+
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
402
|
+
assert.equal(denied.res.text.startsWith('PK'), false)
|
|
403
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
404
|
+
}
|
|
405
|
+
state.flushState()
|
|
406
|
+
state.clearCaches()
|
|
407
|
+
const allowed = await send(prefix.route, prefix.base + '/export/' + library.id + '.zip')
|
|
408
|
+
assert.equal(allowed.res.status, 200)
|
|
409
|
+
assert.match(allowed.res.headers['Content-Type'], /application\/zip/)
|
|
410
|
+
assert.equal(allowed.res.buffer.subarray(0, 2).toString('utf8'), 'PK')
|
|
411
|
+
const files = unzipSync(new Uint8Array(allowed.res.buffer))
|
|
412
|
+
assert.ok(files['memories.json'])
|
|
413
|
+
const exported = JSON.parse(Buffer.from(files['memories.json']).toString('utf8'))
|
|
414
|
+
assert.ok(exported.memories.some((item) => String(item.content).includes(SENTINEL)))
|
|
415
|
+
assert.ok(allowed.reads.length > 0, 'authorized export reads the private index')
|
|
416
|
+
const rpcUrl = prefix.base + '/exportLibrary'
|
|
417
|
+
const rpcPayload = { libraryId: library.id, includeAttachments: true }
|
|
418
|
+
for (const code of [401, 403]) {
|
|
419
|
+
state.flushState()
|
|
420
|
+
state.clearCaches()
|
|
421
|
+
const baseline = snapshotTree(home)
|
|
422
|
+
const denied = await send(prefix.route, rpcUrl, {
|
|
423
|
+
method: 'POST', poison: true, rejection: code, body: envelope('exportLibrary', rpcPayload),
|
|
424
|
+
})
|
|
425
|
+
assertRejected(denied, code)
|
|
426
|
+
assert.equal(denied.res.text.includes(SENTINEL), false)
|
|
427
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
428
|
+
}
|
|
429
|
+
state.flushState()
|
|
430
|
+
state.clearCaches()
|
|
431
|
+
const rpcAllowed = await send(prefix.route, rpcUrl, {
|
|
432
|
+
method: 'POST', body: envelope('exportLibrary', rpcPayload),
|
|
433
|
+
})
|
|
434
|
+
assert.equal(rpcAllowed.res.status, 200)
|
|
435
|
+
const rpcJson = JSON.parse(rpcAllowed.res.text)
|
|
436
|
+
assert.equal(rpcJson.result.ok, true)
|
|
437
|
+
const rpcZip = unzipSync(new Uint8Array(Buffer.from(rpcJson.result.value.base64, 'base64')))
|
|
438
|
+
const rpcExported = JSON.parse(Buffer.from(rpcZip['memories.json']).toString('utf8'))
|
|
439
|
+
assert.ok(rpcExported.memories.some((item) => String(item.content).includes(SENTINEL)))
|
|
440
|
+
assert.equal(rpcAllowed.pulls[0], 1)
|
|
441
|
+
}
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
test('import ZIP: 401/403 precede body reads, staging and library writes', async () => {
|
|
445
|
+
const destinations = {}
|
|
446
|
+
for (const prefix of prefixes) destinations[prefix.name] = state.createLibrary({ name: 'auth-import-' + prefix.name, cwd: path.join(home, 'auth-import-' + prefix.name) })
|
|
447
|
+
const archive = Buffer.from(zipSync({
|
|
448
|
+
'memories.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-memory-library@1', memories: [{ id: 'mem-imported', title: 'imported', content: IMPORT_SENTINEL, layer: 'long_term', status: 'active' }] })),
|
|
449
|
+
'manifest.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-memory-media@1', blobs: {} })),
|
|
450
|
+
}))
|
|
451
|
+
for (const prefix of prefixes) {
|
|
452
|
+
const destination = destinations[prefix.name]
|
|
453
|
+
const importUrl = prefix.base + '/import/' + destination.id + '.zip'
|
|
454
|
+
for (const code of [401, 403]) {
|
|
455
|
+
state.flushState()
|
|
456
|
+
state.clearCaches()
|
|
457
|
+
const baseline = snapshotTree(home)
|
|
458
|
+
const denied = await send(prefix.route, importUrl, { method: 'POST', body: archive, poison: true, rejection: code })
|
|
459
|
+
assertRejected(denied, code)
|
|
460
|
+
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(IMPORT_SENTINEL), false)
|
|
461
|
+
assert.deepEqual(snapshotTree(home), baseline, 'a rejected import must not create staging files or touch the library')
|
|
462
|
+
}
|
|
463
|
+
state.flushState()
|
|
464
|
+
state.clearCaches()
|
|
465
|
+
const allowed = await send(prefix.route, importUrl, { method: 'POST', body: archive })
|
|
466
|
+
assert.equal(allowed.res.status, 200)
|
|
467
|
+
assert.equal(JSON.parse(allowed.res.text).ok, true)
|
|
468
|
+
assert.equal(allowed.pulls[0], 1, 'authorized ZIP body is consumed after requestRejection')
|
|
469
|
+
assert.ok(allowed.writes.length > 0, 'authorized import writes the library')
|
|
470
|
+
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(IMPORT_SENTINEL), true)
|
|
471
|
+
}
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
test('importMemories RPC: 401/403 precede JSON parsing and import writes', async () => {
|
|
475
|
+
const destinations = {}
|
|
476
|
+
for (const prefix of prefixes) destinations[prefix.name] = state.createLibrary({ name: 'auth-rpc-import-' + prefix.name, cwd: path.join(home, 'auth-rpc-import-' + prefix.name) })
|
|
477
|
+
for (const prefix of prefixes) {
|
|
478
|
+
const destination = destinations[prefix.name]
|
|
479
|
+
const payload = { libraryId: destination.id, memories: [{ content: RPC_IMPORT_SENTINEL, title: 'rpc imported' }] }
|
|
480
|
+
for (const code of [401, 403]) {
|
|
481
|
+
state.flushState()
|
|
482
|
+
state.clearCaches()
|
|
483
|
+
const baseline = snapshotTree(home)
|
|
484
|
+
const denied = await send(prefix.route, prefix.base + '/importMemories', {
|
|
485
|
+
method: 'POST', poison: true, rejection: code, body: envelope('importMemories', payload),
|
|
486
|
+
})
|
|
487
|
+
assertRejected(denied, code)
|
|
488
|
+
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(RPC_IMPORT_SENTINEL), false)
|
|
489
|
+
assert.deepEqual(snapshotTree(home), baseline)
|
|
490
|
+
}
|
|
491
|
+
state.flushState()
|
|
492
|
+
state.clearCaches()
|
|
493
|
+
const allowed = await send(prefix.route, prefix.base + '/importMemories', {
|
|
494
|
+
method: 'POST', body: envelope('importMemories', payload),
|
|
495
|
+
})
|
|
496
|
+
assert.equal(allowed.res.status, 200)
|
|
497
|
+
const json = JSON.parse(allowed.res.text)
|
|
498
|
+
assert.equal(json.result.ok, true)
|
|
499
|
+
assert.equal(json.result.value.imported, 1)
|
|
500
|
+
assert.equal(allowed.pulls[0], 1)
|
|
501
|
+
assert.equal(JSON.stringify(state.loadPrivateIndex(destination.id)).includes(RPC_IMPORT_SENTINEL), true)
|
|
502
|
+
}
|
|
503
|
+
})
|
|
504
|
+
|
|
505
|
+
test('unsupported methods still authenticate first: 401/403 before 405', async () => {
|
|
506
|
+
for (const prefix of prefixes) {
|
|
507
|
+
for (const code of [401, 403]) {
|
|
508
|
+
assertRejected(await send(prefix.route, prefix.base + '/ui', { method: 'DELETE', rejection: code }), code)
|
|
509
|
+
assertRejected(await send(prefix.route, prefix.base + '/listLibraries', { method: 'GET', rejection: code }), code)
|
|
510
|
+
}
|
|
511
|
+
assert.equal((await send(prefix.route, prefix.base + '/ui', { method: 'DELETE' })).res.status, 405)
|
|
512
|
+
assert.equal((await send(prefix.route, prefix.base + '/listLibraries', { method: 'GET' })).res.status, 405)
|
|
513
|
+
}
|
|
514
|
+
})
|
|
515
|
+
|
|
516
|
+
// §10 P0: one representative per audited operation category. The table drives
|
|
517
|
+
// every variant, so a new endpoint added to LIBRARY_ROUTE_OPERATIONS with the
|
|
518
|
+
// wrong operation (or none) fails here instead of shipping unverified.
|
|
519
|
+
const MATRIX_SHA = 'a'.repeat(64)
|
|
520
|
+
const matrixRows = [
|
|
521
|
+
{ endpoint: 'getMemory', operation: 'read', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
522
|
+
{ endpoint: 'browseWall', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
523
|
+
{ endpoint: 'getGraph', operation: 'read', payload: (lib) => ({ libraryId: lib.id, offset: 0, domain: 'coding' }) },
|
|
524
|
+
{ endpoint: 'getStats', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
525
|
+
// 工单 F:实体合并的读写面。合并矩阵只验证路由授权:不存在的实体在 200
|
|
526
|
+
// 业务信封里报 unknown entity,403 必须在 dispatch 之前发生。
|
|
527
|
+
{ endpoint: 'suggestEntityMerges', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
528
|
+
{ endpoint: 'mergeEntities', operation: 'write', payload: (lib) => ({ libraryId: lib.id, targetId: 'ent-matrix-target', sourceIds: ['ent-matrix-source'] }) },
|
|
529
|
+
{ endpoint: 'addMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, content: 'matrix write body' }) },
|
|
530
|
+
{ endpoint: 'updateMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch', patch: { title: 'matrix retitled' } }) },
|
|
531
|
+
{ endpoint: 'archiveMemory', operation: 'archive', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
532
|
+
{ endpoint: 'deleteMemory', operation: 'delete', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
|
|
533
|
+
{ endpoint: 'renameLibrary', operation: 'rename', payload: (lib) => ({ libraryId: lib.id, name: 'matrix rename' }) },
|
|
534
|
+
{ endpoint: 'restoreLibrary', operation: 'restore', payload: (lib) => ({ libraryId: lib.id }) },
|
|
535
|
+
{ endpoint: 'importMemories', operation: 'import', payload: (lib) => ({ libraryId: lib.id, memories: [] }) },
|
|
536
|
+
{ endpoint: 'exportLibrary', operation: 'export', payload: (lib) => ({ libraryId: lib.id }) },
|
|
537
|
+
{ endpoint: 'getAttachment', operation: 'attachment.read', payload: (lib) => ({ libraryId: lib.id, sha256: MATRIX_SHA }) },
|
|
538
|
+
{ endpoint: 'listReviews', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
539
|
+
{ endpoint: 'resolveReview', operation: 'write', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch', action: 'reject' }) },
|
|
540
|
+
{ endpoint: 'lexiconList', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
|
|
541
|
+
{ endpoint: 'lexiconAdd', operation: 'write', payload: (lib) => ({ libraryId: lib.id, term: 'matrix term', kind: 'term', meaning: 'matrix meaning' }) },
|
|
542
|
+
// §2.3:lexiconReview 删除,lifecycle 变成 archive / restore 两个普通 write;
|
|
543
|
+
// 授权模型不动(会话绑定优先、standalone 走 host callback)。
|
|
544
|
+
{ endpoint: 'lexiconArchive', operation: 'write', payload: (lib) => ({ libraryId: lib.id, termId: 'lex-matrix-scratch' }) },
|
|
545
|
+
{ endpoint: 'lexiconRestore', operation: 'write', payload: (lib) => ({ libraryId: lib.id, termId: 'lex-matrix-scratch' }) },
|
|
546
|
+
]
|
|
547
|
+
|
|
548
|
+
function seedMatrixScratch() {
|
|
549
|
+
state.updatePrivateIndex(library.id, (index) => {
|
|
550
|
+
index.entries['mem-matrix-scratch'] = {
|
|
551
|
+
title: 'matrix scratch', content: 'matrix scratch body', status: 'active', layer: 'long_term',
|
|
552
|
+
visibility: 'shared', disclosure: 'can_tell', source: 'user_said',
|
|
553
|
+
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
554
|
+
}
|
|
555
|
+
})
|
|
556
|
+
state.flushState()
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
test('operation matrix: every library route denies A→B, allows A→A, and gates standalone on the host callback', async () => {
|
|
560
|
+
const libB = state.createLibrary({ name: 'auth-matrix-b', cwd: path.join(home, 'auth-matrix-b') })
|
|
561
|
+
for (const prefix of prefixes) {
|
|
562
|
+
seedMatrixScratch()
|
|
563
|
+
for (const row of matrixRows) {
|
|
564
|
+
const post = (payload) => send(prefix.route, prefix.base + '/' + row.endpoint, { method: 'POST', body: envelope(row.endpoint, payload) })
|
|
565
|
+
|
|
566
|
+
// Session A → library B: 403, the host callback is never consulted, and
|
|
567
|
+
// the body (already parsed) is the only thing touched before the denial.
|
|
568
|
+
auth.callbackMode = 'present'
|
|
569
|
+
auth.libraryDecision = true
|
|
570
|
+
auth.libraryCalls = 0
|
|
571
|
+
const cross = await post({ ...row.payload(libB), sessionId })
|
|
572
|
+
assert.equal(cross.res.status, 403, `${prefix.name} ${row.endpoint}: session A must not address library B`)
|
|
573
|
+
assert.equal(cross.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
574
|
+
assert.equal(cross.pulls.length, 1, 'route authorization happens after the envelope parse')
|
|
575
|
+
assert.equal(auth.libraryCalls, 0, `${row.endpoint}: a bound session must not fall back to the host callback`)
|
|
576
|
+
|
|
577
|
+
// Session A → library A: past the route gate. Business errors, when the
|
|
578
|
+
// payload is not worth making valid, still come back inside a 200.
|
|
579
|
+
const own = await post({ ...row.payload(library), sessionId })
|
|
580
|
+
assert.equal(own.res.status, 200, `${prefix.name} ${row.endpoint}: session A on its own library must pass the route gate`)
|
|
581
|
+
assert.equal(auth.libraryCalls, 0)
|
|
582
|
+
|
|
583
|
+
// Standalone (no session): exactly one authorizeLibrary call that carries
|
|
584
|
+
// the audited operation and the target library; only strict true passes.
|
|
585
|
+
auth.libraryRequests.length = 0
|
|
586
|
+
auth.libraryDecision = true
|
|
587
|
+
auth.libraryCalls = 0
|
|
588
|
+
const granted = await post(row.payload(libB))
|
|
589
|
+
assert.equal(granted.res.status, 200, `${prefix.name} ${row.endpoint}: host callback true must grant the standalone request`)
|
|
590
|
+
assert.equal(auth.libraryCalls, 1)
|
|
591
|
+
const request = auth.libraryRequests.at(-1)
|
|
592
|
+
assert.equal(request.libraryId, libB.id, `${row.endpoint}: callback must see the target library`)
|
|
593
|
+
assert.equal(request.operation, row.operation, `${row.endpoint}: callback must see the audited operation`)
|
|
594
|
+
|
|
595
|
+
auth.libraryDecision = false
|
|
596
|
+
auth.libraryCalls = 0
|
|
597
|
+
const denied = await post(row.payload(libB))
|
|
598
|
+
assert.equal(denied.res.status, 403, `${prefix.name} ${row.endpoint}: callback false must deny`)
|
|
599
|
+
assert.equal(auth.libraryCalls, 1)
|
|
600
|
+
|
|
601
|
+
auth.callbackMode = 'throw'
|
|
602
|
+
auth.libraryDecision = true
|
|
603
|
+
auth.libraryCalls = 0
|
|
604
|
+
const thrown = await post(row.payload(libB))
|
|
605
|
+
assert.equal(thrown.res.status, 403, `${prefix.name} ${row.endpoint}: a thrown callback must deny`)
|
|
606
|
+
|
|
607
|
+
auth.callbackMode = 'absent'
|
|
608
|
+
auth.libraryCalls = 0
|
|
609
|
+
const absent = await post(row.payload(libB))
|
|
610
|
+
assert.equal(absent.res.status, 200, `${prefix.name} ${row.endpoint}: a host without the callback falls back to the HTTP boundary (2026-11-01 flip)`)
|
|
611
|
+
assert.equal(auth.libraryCalls, 0)
|
|
612
|
+
auth.callbackMode = 'present'
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
})
|
|
616
|
+
|
|
617
|
+
// 全局词典(lib/lexicon.js 的 GLOBAL_LEXICON_ID)不是私有库:宿主不该被叫去授权一本
|
|
618
|
+
// 根本不存在的库,绑定中的会话也不该因为点名「全局」而不是自己的库就被判成越权。
|
|
619
|
+
// 会话侧仍要认凭证(会话存在 + 全局层没被天花板关掉);standalone 与 listGlobal 一样
|
|
620
|
+
// 只由 HTTP 边界把关。
|
|
621
|
+
test('the global lexicon is a shared store, not a library route', async () => {
|
|
622
|
+
const { GLOBAL_LEXICON_ID } = await import('../lib/lexicon.js')
|
|
623
|
+
for (const prefix of prefixes) {
|
|
624
|
+
const post = (payload) => send(prefix.route, prefix.base + '/lexiconList', { method: 'POST', body: envelope('lexiconList', payload) })
|
|
625
|
+
auth.callbackMode = 'present'
|
|
626
|
+
auth.libraryDecision = false
|
|
627
|
+
auth.libraryCalls = 0
|
|
628
|
+
const bound = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId })
|
|
629
|
+
assert.equal(bound.res.status, 200, `${prefix.name}: a bound session may address the global lexicon`)
|
|
630
|
+
assert.equal(auth.libraryCalls, 0, `${prefix.name}: the host must not be asked about a library that does not exist`)
|
|
631
|
+
const ghost = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId: 'auth-session-ghost' })
|
|
632
|
+
assert.equal(ghost.res.status, 403, `${prefix.name}: a dangling session id is never a credential`)
|
|
633
|
+
state.setSessionBinding(sessionId, { useGlobal: false })
|
|
634
|
+
const blocked = await post({ libraryId: GLOBAL_LEXICON_ID, sessionId })
|
|
635
|
+
state.setSessionBinding(sessionId, { useGlobal: true })
|
|
636
|
+
assert.equal(blocked.res.status, 403, `${prefix.name}: useGlobal=false means there is no global lexicon for that conversation`)
|
|
637
|
+
auth.libraryDecision = false
|
|
638
|
+
auth.libraryCalls = 0
|
|
639
|
+
const solo = await post({ libraryId: GLOBAL_LEXICON_ID })
|
|
640
|
+
assert.equal(solo.res.status, 200, `${prefix.name}: the management plane is governed by the HTTP boundary`)
|
|
641
|
+
assert.equal(auth.libraryCalls, 0)
|
|
642
|
+
}
|
|
643
|
+
})
|
|
644
|
+
|
|
645
|
+
test('removed lexiconReview is no longer a library route and does not dispatch', async () => {
|
|
646
|
+
for (const prefix of prefixes) {
|
|
647
|
+
auth.callbackMode = 'present'
|
|
648
|
+
auth.libraryDecision = true
|
|
649
|
+
auth.libraryCalls = 0
|
|
650
|
+
const res = await send(prefix.route, prefix.base + '/lexiconReview', {
|
|
651
|
+
method: 'POST',
|
|
652
|
+
body: envelope('lexiconReview', { libraryId: library.id, termId: 'lex-matrix-scratch', action: 'approve' }),
|
|
653
|
+
})
|
|
654
|
+
assert.equal(res.res.status, 200, 'an unknown method is answered as a business error, not routed')
|
|
655
|
+
assert.equal(auth.libraryCalls, 0, 'lexiconReview must not be authorized as a library route anymore')
|
|
656
|
+
const json = JSON.parse(res.res.text)
|
|
657
|
+
assert.equal(json.result.ok, false)
|
|
658
|
+
assert.match(json.result.error.message, /unknown endpoint/)
|
|
659
|
+
}
|
|
660
|
+
// 401/403 仍然先于方法存在性:被拒的 review 请求连 dispatch 都到不了。
|
|
661
|
+
for (const prefix of prefixes) {
|
|
662
|
+
for (const code of [401, 403]) {
|
|
663
|
+
assertRejected(await send(prefix.route, prefix.base + '/lexiconReview', {
|
|
664
|
+
method: 'POST', poison: true, rejection: code,
|
|
665
|
+
body: envelope('lexiconReview', { libraryId: library.id, termId: 'lex-matrix-scratch', action: 'approve' }),
|
|
666
|
+
}), code)
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
})
|
|
670
|
+
|
|
671
|
+
test('session-bound resolution: write/archive without an explicit libraryId resolve from the persisted binding', async () => {
|
|
672
|
+
const rows = [
|
|
673
|
+
{ endpoint: 'updateMemory', payload: (session) => ({ sessionId: session, id: 'mem-matrix-scratch', patch: { title: 'fallback retitled' } }) },
|
|
674
|
+
{ endpoint: 'archiveMemory', payload: (session) => ({ sessionId: session, id: 'mem-matrix-scratch' }) },
|
|
675
|
+
]
|
|
676
|
+
for (const prefix of prefixes) {
|
|
677
|
+
seedMatrixScratch()
|
|
678
|
+
for (const row of rows) {
|
|
679
|
+
const post = (payload) => send(prefix.route, prefix.base + '/' + row.endpoint, { method: 'POST', body: envelope(row.endpoint, payload) })
|
|
680
|
+
auth.callbackMode = 'present'
|
|
681
|
+
auth.libraryDecision = true
|
|
682
|
+
auth.libraryCalls = 0
|
|
683
|
+
const own = await post(row.payload(sessionId))
|
|
684
|
+
assert.equal(own.res.status, 200, `${prefix.name} ${row.endpoint}: the bound session resolves its own library`)
|
|
685
|
+
assert.equal(auth.libraryCalls, 0)
|
|
686
|
+
for (const bad of ['', 'ghost-session', 42]) {
|
|
687
|
+
const denied = await post(row.payload(bad))
|
|
688
|
+
assert.equal(denied.res.status, 403, `${prefix.name} ${row.endpoint}: sessionId=${JSON.stringify(bad)} must not resolve to a target`)
|
|
689
|
+
assert.equal(denied.res.text, JSON.stringify({ ok: false, error: { code: 'dsh-memu-memory/forbidden', message: 'forbidden', details: {} } }))
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
})
|
|
694
|
+
|
|
695
|
+
test('global review queue: embedded sessions may read, writes need a live binding, standalone needs review.manage', async () => {
|
|
696
|
+
const seedGlobalReview = () => {
|
|
697
|
+
state.updateGlobalIndex((index) => {
|
|
698
|
+
index.entries['mem-global-review'] = {
|
|
699
|
+
title: 'global review', content: 'global pending body', status: 'pending_review', layer: 'long_term',
|
|
700
|
+
domain: 'general', visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
|
|
701
|
+
reviewReason: 'matrix conflict', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
702
|
+
}
|
|
703
|
+
})
|
|
704
|
+
state.flushState()
|
|
705
|
+
}
|
|
706
|
+
const post = (prefix, endpoint, payload) => send(prefix.route, prefix.base + '/' + endpoint, { method: 'POST', body: envelope(endpoint, payload) })
|
|
707
|
+
|
|
708
|
+
for (const prefix of prefixes) {
|
|
709
|
+
seedGlobalReview()
|
|
710
|
+
auth.callbackMode = 'present'
|
|
711
|
+
auth.libraryDecision = true
|
|
712
|
+
auth.libraryCalls = 0
|
|
713
|
+
|
|
714
|
+
// Embedded read: a well-formed session reads the global queue without any
|
|
715
|
+
// host callback — the queue is conversation-visible by design.
|
|
716
|
+
const read = await post(prefix, 'listReviews', { sessionId })
|
|
717
|
+
assert.equal(read.res.status, 200)
|
|
718
|
+
const readJson = JSON.parse(read.res.text)
|
|
719
|
+
assert.equal(readJson.result.ok, true)
|
|
720
|
+
assert.equal(readJson.result.value.scope, 'global')
|
|
721
|
+
assert.ok(readJson.result.value.items.some((item) => item.id === 'mem-global-review'))
|
|
722
|
+
assert.equal(auth.libraryCalls, 0, 'embedded reads never consult the host callback')
|
|
723
|
+
|
|
724
|
+
// Embedded write: only a session whose binding still exists may resolve.
|
|
725
|
+
const resolved = await post(prefix, 'resolveReview', { sessionId, id: 'mem-global-review', action: 'reject', resolution: 'replace' })
|
|
726
|
+
assert.equal(resolved.res.status, 200)
|
|
727
|
+
assert.equal(JSON.parse(resolved.res.text).result.ok, true)
|
|
728
|
+
assert.equal(state.loadGlobalIndex().entries['mem-global-review'].status, 'archived')
|
|
729
|
+
|
|
730
|
+
for (const bad of ['', 'ghost-session']) {
|
|
731
|
+
seedGlobalReview()
|
|
732
|
+
auth.libraryCalls = 0
|
|
733
|
+
const denied = await post(prefix, 'resolveReview', { sessionId: bad, id: 'mem-global-review', action: 'reject' })
|
|
734
|
+
assert.equal(denied.res.status, 403, `${prefix.name} resolveReview with sessionId=${JSON.stringify(bad)} must fail closed`)
|
|
735
|
+
assert.equal(state.loadGlobalIndex().entries['mem-global-review'].status, 'pending_review', 'a denied review write must not touch the queue')
|
|
736
|
+
const readDenied = await post(prefix, 'listReviews', { sessionId: bad })
|
|
737
|
+
assert.equal(readDenied.res.status, 403, `${prefix.name} listReviews with sessionId=${JSON.stringify(bad)} must fail closed`)
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// Standalone management plane: the global queue authorizes with
|
|
741
|
+
// libraryId null and the dedicated review.manage operation, and a host
|
|
742
|
+
// that does not implement it fails closed.
|
|
743
|
+
const standalone = async (endpoint, payload) => {
|
|
744
|
+
seedGlobalReview()
|
|
745
|
+
auth.callbackMode = 'present'
|
|
746
|
+
auth.libraryDecision = true
|
|
747
|
+
auth.libraryCalls = 0
|
|
748
|
+
auth.libraryRequests.length = 0
|
|
749
|
+
const granted = await post(prefix, endpoint, payload)
|
|
750
|
+
assert.equal(granted.res.status, 200, `${prefix.name} ${endpoint}: review.manage true must grant the standalone request`)
|
|
751
|
+
assert.equal(auth.libraryCalls, 1)
|
|
752
|
+
const request = auth.libraryRequests.at(-1)
|
|
753
|
+
assert.equal(request.libraryId, null, 'the global queue authorizes with libraryId null')
|
|
754
|
+
assert.equal(request.operation, 'review.manage')
|
|
755
|
+
|
|
756
|
+
auth.libraryDecision = false
|
|
757
|
+
auth.libraryCalls = 0
|
|
758
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: review.manage false must deny`)
|
|
759
|
+
assert.equal(auth.libraryCalls, 1)
|
|
760
|
+
|
|
761
|
+
auth.callbackMode = 'throw'
|
|
762
|
+
auth.libraryDecision = true
|
|
763
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: a thrown callback must deny`)
|
|
764
|
+
|
|
765
|
+
auth.callbackMode = 'absent'
|
|
766
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 200, `${prefix.name} ${endpoint}: a host without the callback falls back to the HTTP boundary (2026-11-01 flip)`)
|
|
767
|
+
auth.callbackMode = 'present'
|
|
768
|
+
}
|
|
769
|
+
await standalone('listReviews', {})
|
|
770
|
+
await standalone('resolveReview', { id: 'mem-global-review', action: 'reject' })
|
|
771
|
+
|
|
772
|
+
// The private branch keeps its library checks: a bound session cannot
|
|
773
|
+
// address another library's queue, and a granted standalone private read is
|
|
774
|
+
// a plain library read, not review.manage.
|
|
775
|
+
const privateLib = state.createLibrary({ name: 'auth-review-private', cwd: path.join(home, 'auth-review-private') })
|
|
776
|
+
auth.libraryDecision = true
|
|
777
|
+
assert.equal((await post(prefix, 'listReviews', { libraryId: privateLib.id, sessionId })).res.status, 403)
|
|
778
|
+
assert.equal((await post(prefix, 'resolveReview', { libraryId: privateLib.id, sessionId, id: 'mem-global-review', action: 'reject' })).res.status, 403)
|
|
779
|
+
auth.libraryRequests.length = 0
|
|
780
|
+
auth.libraryCalls = 0
|
|
781
|
+
const standalonePrivate = await post(prefix, 'listReviews', { libraryId: privateLib.id })
|
|
782
|
+
assert.equal(standalonePrivate.res.status, 200)
|
|
783
|
+
assert.equal(auth.libraryRequests.at(-1).operation, 'read', 'a private-queue read is a plain library read')
|
|
784
|
+
}
|
|
785
|
+
})
|
|
786
|
+
|
|
787
|
+
// 全局生命周期(1.3.12):scope:'global' 的 archiveMemory/updateMemory/deleteMemory
|
|
788
|
+
// 与全局复核队列同一管理面凭据模型——embedded 要活绑定、standalone 走 libraryId=null
|
|
789
|
+
// 的 review.manage;scope 与 libraryId 同时出现是作用域冲突,先于 dispatch 拒绝。
|
|
790
|
+
test('global lifecycle: scope global follows the global management credential model', async () => {
|
|
791
|
+
const seedGlobalActive = () => {
|
|
792
|
+
state.updateGlobalIndex((index) => {
|
|
793
|
+
index.entries['mem-global-lifecycle'] = {
|
|
794
|
+
title: 'global lifecycle', content: 'global lifecycle body', status: 'active', layer: 'long_term',
|
|
795
|
+
domain: 'general', visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
|
|
796
|
+
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
797
|
+
}
|
|
798
|
+
})
|
|
799
|
+
state.flushState()
|
|
800
|
+
}
|
|
801
|
+
const post = (prefix, endpoint, payload) => send(prefix.route, prefix.base + '/' + endpoint, { method: 'POST', body: envelope(endpoint, payload) })
|
|
802
|
+
for (const prefix of prefixes) {
|
|
803
|
+
seedGlobalActive()
|
|
804
|
+
auth.callbackMode = 'present'
|
|
805
|
+
auth.libraryDecision = true
|
|
806
|
+
auth.libraryCalls = 0
|
|
807
|
+
const embedded = await post(prefix, 'archiveMemory', { scope: 'global', sessionId, id: 'mem-global-lifecycle' })
|
|
808
|
+
assert.equal(embedded.res.status, 200, `${prefix.name}: a live binding may archive global memory without the host callback`)
|
|
809
|
+
assert.equal(JSON.parse(embedded.res.text).result.ok, true)
|
|
810
|
+
assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'archived')
|
|
811
|
+
assert.equal(auth.libraryCalls, 0)
|
|
812
|
+
|
|
813
|
+
seedGlobalActive()
|
|
814
|
+
const ghost = await post(prefix, 'archiveMemory', { scope: 'global', sessionId: 'ghost-session', id: 'mem-global-lifecycle' })
|
|
815
|
+
assert.equal(ghost.res.status, 403, `${prefix.name}: a dangling session is never a credential`)
|
|
816
|
+
assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'active', 'a denied write must not touch the store')
|
|
817
|
+
|
|
818
|
+
const conflict = await post(prefix, 'archiveMemory', { scope: 'global', libraryId: 'lib-whatever', id: 'mem-global-lifecycle' })
|
|
819
|
+
assert.equal(conflict.res.status, 403, `${prefix.name}: scope global alongside a libraryId is a scope conflict`)
|
|
820
|
+
|
|
821
|
+
const rows = [
|
|
822
|
+
['archiveMemory', { scope: 'global', id: 'mem-global-lifecycle' }],
|
|
823
|
+
['updateMemory', { scope: 'global', id: 'mem-global-lifecycle', patch: { status: 'active' } }],
|
|
824
|
+
['deleteMemory', { scope: 'global', id: 'mem-global-lifecycle', confirmed: true }],
|
|
825
|
+
]
|
|
826
|
+
for (const [endpoint, payload] of rows) {
|
|
827
|
+
seedGlobalActive()
|
|
828
|
+
if (endpoint !== 'archiveMemory') {
|
|
829
|
+
state.updateGlobalIndex((index) => { index.entries['mem-global-lifecycle'].status = 'archived' })
|
|
830
|
+
}
|
|
831
|
+
auth.callbackMode = 'present'
|
|
832
|
+
auth.libraryDecision = true
|
|
833
|
+
auth.libraryCalls = 0
|
|
834
|
+
auth.libraryRequests.length = 0
|
|
835
|
+
const granted = await post(prefix, endpoint, payload)
|
|
836
|
+
assert.equal(granted.res.status, 200, `${prefix.name} ${endpoint}: review.manage true must grant`)
|
|
837
|
+
assert.equal(JSON.parse(granted.res.text).result.ok, true)
|
|
838
|
+
assert.equal(auth.libraryCalls, 1)
|
|
839
|
+
assert.equal(auth.libraryRequests.at(-1).libraryId, null, 'global lifecycle authorizes with libraryId null')
|
|
840
|
+
assert.equal(auth.libraryRequests.at(-1).operation, 'review.manage')
|
|
841
|
+
|
|
842
|
+
seedGlobalActive()
|
|
843
|
+
auth.libraryDecision = false
|
|
844
|
+
auth.libraryCalls = 0
|
|
845
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: review.manage false must deny`)
|
|
846
|
+
assert.equal(auth.libraryCalls, 1)
|
|
847
|
+
|
|
848
|
+
auth.callbackMode = 'throw'
|
|
849
|
+
auth.libraryDecision = true
|
|
850
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: a thrown callback must deny`)
|
|
851
|
+
|
|
852
|
+
auth.callbackMode = 'absent'
|
|
853
|
+
assert.equal((await post(prefix, endpoint, payload)).res.status, 200, `${prefix.name} ${endpoint}: absent callback falls back to the HTTP boundary`)
|
|
854
|
+
auth.callbackMode = 'present'
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
})
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
// ---- 403 响应必须保留可解析的错误信封 ----
|
|
861
|
+
// 无 libraryId 的 browseWall("全部记忆库"视图)曾被硬拒 403:capability 缺席的宿主
|
|
862
|
+
// 上整个记忆墙挂掉。契约:无 libraryId 走同一 capability 模型——缺席回退放行、实现
|
|
863
|
+
// 了回调的宿主由 callback 决定;403 响应必须是 JSON 信封(standalone fetch 会
|
|
864
|
+
// response.json(),裸文本抛 SyntaxError)。
|
|
865
|
+
|
|
866
|
+
test('browseWall all-libraries view: absent capability allows, present callback decides, envelope on 403', async () => {
|
|
867
|
+
state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
|
|
868
|
+
const lib = state.createLibrary({ name: 'auth-wall-all', cwd: path.join(home, 'auth-wall-all') })
|
|
869
|
+
state.updatePrivateIndex(lib.id, (index) => {
|
|
870
|
+
index.entries['mem-wall-all'] = { title: 'wall all body', content: 'wall all body', status: 'active', layer: 'long_term', visibility: 'shared', disclosure: 'can_tell', source: 'user_said', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
|
871
|
+
})
|
|
872
|
+
state.flushState()
|
|
873
|
+
|
|
874
|
+
for (const prefix of prefixes) {
|
|
875
|
+
// capability 缺席(当前版本宿主):跨库视图放行——记忆墙的核心视图不能 403。
|
|
876
|
+
auth.libraryCalls = 0
|
|
877
|
+
const allowed = await send(prefix.route, prefix.base + '/browseWall', { method: 'POST', body: envelope('browseWall', { libraryId: '' }) })
|
|
878
|
+
assert.equal(allowed.res.status, 200, `${prefix.name} browseWall(''): absent capability falls back to the HTTP boundary`)
|
|
879
|
+
const payload = JSON.parse(allowed.res.text)
|
|
880
|
+
assert.ok(payload.result.value.items.length >= 1, 'the wall returns entries across libraries')
|
|
881
|
+
|
|
882
|
+
// 实现了 capability 的宿主:多库枚举由回调决定(deny → 403 JSON 信封)。
|
|
883
|
+
auth.libraryDecision = false
|
|
884
|
+
auth.libraryCalls = 0
|
|
885
|
+
const denied = await send(prefix.route, prefix.base + '/browseWall', { method: 'POST', body: envelope('browseWall', { libraryId: '' }) })
|
|
886
|
+
assert.equal(denied.res.status, 403, 'a host that implements the capability may deny the multi-library read')
|
|
887
|
+
assert.equal(auth.libraryCalls, 1, 'present capability is consulted for the multi-library read')
|
|
888
|
+
|
|
889
|
+
// 403 响应体必须是 JSON 信封:standalone fetch 客户端 response.json() 之后再读
|
|
890
|
+
// error.message;裸 "forbidden" 会在客户端触发 SyntaxError。
|
|
891
|
+
assert.equal(denied.res.headers['content-type'] || denied.res.headers['Content-Type'], 'application/json')
|
|
892
|
+
const parsed = JSON.parse(denied.res.text)
|
|
893
|
+
assert.equal(parsed.ok, false)
|
|
894
|
+
assert.equal(parsed.error.code, 'dsh-memu-memory/forbidden')
|
|
895
|
+
assert.equal(typeof parsed.error.message, 'string')
|
|
896
|
+
auth.libraryDecision = true
|
|
897
|
+
}
|
|
898
|
+
})
|
|
899
|
+
|
|
900
|
+
// standalone fetch 包装器:403 信封透传 error.message,而不是只报状态码
|
|
901
|
+
// 以保留服务端提供的拒绝原因。
|
|
902
|
+
test('standalone rpc wrapper surfaces the server error message instead of the status code', () => {
|
|
903
|
+
const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
|
|
904
|
+
assert.match(client, /envelope\.error\?\.message \|\| \('Invalid RPC response: ' \+ response\.status\)/)
|
|
905
|
+
})
|
|
906
|
+
|
|
907
|
+
// 0.2.3-alpha.1 起宿主把 connection.requestRejection 换成 connection.admit。
|
|
908
|
+
// 只探测前者(或只探测挂在模块而非服务上的 isTrustedApiRequest)的守卫在新宿主上会静默放行。
|
|
909
|
+
test('a host that only exposes connection.admit stays guarded', async () => {
|
|
910
|
+
const routes = []
|
|
911
|
+
const admit = { calls: 0, decision: undefined }
|
|
912
|
+
registerRpc({
|
|
913
|
+
inject: (_deps, build) => build({
|
|
914
|
+
effect: (fn) => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
|
|
915
|
+
webServer: { register: (spec) => { routes.push(spec); return () => {} } },
|
|
916
|
+
connection: { admit: () => { admit.calls += 1; return admit.decision } },
|
|
917
|
+
logger: {},
|
|
918
|
+
}),
|
|
919
|
+
})
|
|
920
|
+
const route = routes.find(spec => spec.path === '/dsh-memu-memory')
|
|
921
|
+
assert.ok(route, 'the admit-only host registered its RPC route')
|
|
922
|
+
const fire = async (decision) => {
|
|
923
|
+
admit.decision = decision
|
|
924
|
+
admit.calls = 0
|
|
925
|
+
resetProbe()
|
|
926
|
+
const chunks = []
|
|
927
|
+
let resolveDone
|
|
928
|
+
const done = new Promise((resolve) => { resolveDone = resolve })
|
|
929
|
+
const timer = setTimeout(() => resolveDone(new Error('response did not end')), 3000)
|
|
930
|
+
timer.unref?.()
|
|
931
|
+
const res = {
|
|
932
|
+
status: 0,
|
|
933
|
+
writeHead(code) { this.status = code; return this },
|
|
934
|
+
write() { return true },
|
|
935
|
+
end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); resolveDone() },
|
|
936
|
+
get text() { return Buffer.concat(chunks).toString('utf8') },
|
|
937
|
+
}
|
|
938
|
+
const req = {
|
|
939
|
+
method: 'POST', url: '/dsh-memu-memory', headers: {},
|
|
940
|
+
async *[Symbol.asyncIterator]() { chunks.push(Buffer.from('body read')) },
|
|
941
|
+
}
|
|
942
|
+
probe.active = true
|
|
943
|
+
try {
|
|
944
|
+
await route.handler(req, res)
|
|
945
|
+
await done
|
|
946
|
+
} finally { probe.active = false }
|
|
947
|
+
return { status: res.status, text: res.text, admitCalls: admit.calls, reads: [...probe.reads], writes: [...probe.writes] }
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const refused = await fire({ rejection: 403 })
|
|
951
|
+
assert.equal(refused.status, 403, 'admit rejection becomes the HTTP status')
|
|
952
|
+
assert.equal(refused.admitCalls, 1, 'admit runs exactly once')
|
|
953
|
+
assert.equal(refused.text.includes('body read'), false, 'the body is not read before admission')
|
|
954
|
+
assert.deepEqual(refused.reads, [])
|
|
955
|
+
assert.deepEqual(refused.writes, [])
|
|
956
|
+
|
|
957
|
+
const admitted = await fire({ peer: {} })
|
|
958
|
+
assert.ok(admitted.status !== 403 && admitted.status !== 401, 'an admitted peer passes the guard')
|
|
959
|
+
assert.equal(admitted.admitCalls, 1)
|
|
960
|
+
// §13.6:这台宿主实际走了哪一级探测,要能在指纹里读到(台账核对用的就是这一行)。
|
|
961
|
+
const surface = await import('../lib/host-surface.js')
|
|
962
|
+
assert.equal(surface.hostSurface().rpcGuard, 'admit', 'the probe records which guard shape this host exposes')
|
|
963
|
+
})
|