codemem 0.50.0-beta.4 → 0.50.0-beta.5
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/dist/index.js +1085 -598
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_LEDGER_RETENTION_BATCH_SIZE, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, LedgerRetentionRunner, MUTATING_TOOL_NAMES, MemoryStore, NON_SELECTED_EXPOSURE_RETENTION_DAYS, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, ReplicationBackfillRunner, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncAttemptRetentionRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, ViewerWriterLockHeldError, ViewerWriterLockUnavailableError, acquireViewerWriterLock, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, canonicalViewerDbPath, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1ApplyOnlyMigrations, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, isViewerWriterLockHeld, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, readViewerPidFile, readViewerWriterLockOwner, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting,
|
|
2
|
+
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, BetterSqliteCoordinatorStore, COORDINATOR_FREE_BINDING_UNVERIFIED, COORDINATOR_FREE_WITNESS_UNAVAILABLE, COORDINATOR_JOIN_CONFIRMATION_REQUIRED, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_LEDGER_RETENTION_BATCH_SIZE, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, INVITE_TOKEN_LOOKUP_VERSION, InviteTokenRefusal, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, LedgerRetentionRunner, MUTATING_TOOL_NAMES, MemoryStore, NON_SELECTED_EXPOSURE_RETENTION_DAYS, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, ReplicationBackfillRunner, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SessionRepositoryIdentityRunner, SummaryDedupBackfillRunner, SyncAttemptRetentionRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, ViewerWriterLockHeldError, ViewerWriterLockUnavailableError, acquireViewerWriterLock, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPairingPayload, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, canonicalViewerDbPath, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1ApplyOnlyMigrations, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, isViewerWriterLockHeld, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, peerTransportBlocker, peerTransportExecutor, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, processStartIdentity, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCodememConfigFileForMutation, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readDeviceStorageShape, readImportPayload, readLocalProjectMigrationReport, readPeerProjectFilterAuthority, readViewerPidFile, readViewerWriterLockOwner, recordAutomaticRecall, recordConfiguredCoordinatorHistory, recordPairingTransportEvidence, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retrievalLedgerStats, retryRawEventFailures, runDeviceRejoin, runLedgerRetentionPass, runSyncDaemon, runSyncPass, sanitizeHookPayload, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerPidFilePaths, viewerRuntimeDir, viewerUrl, viewerUrl as viewerUrl$1, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
|
|
3
3
|
import { Command, Option } from "commander";
|
|
4
4
|
import omelette from "omelette";
|
|
5
5
|
import { appendFileSync, closeSync, constants, copyFileSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
6
6
|
import { homedir, networkInterfaces } from "node:os";
|
|
7
|
-
import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
8
8
|
import { isDeepStrictEqual, styleText } from "node:util";
|
|
9
9
|
import { createHash, randomInt, randomUUID } from "node:crypto";
|
|
10
10
|
import { isUtf8 } from "node:buffer";
|
|
@@ -1816,14 +1816,14 @@ async function nativeDeliveryAcknowledgement(deliver, serialized) {
|
|
|
1816
1816
|
}
|
|
1817
1817
|
function assertNativeRecoverySnapshot(snapshot) {
|
|
1818
1818
|
const { dir, dirFd, path, fd, details, serialized, lock } = snapshot;
|
|
1819
|
-
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$
|
|
1819
|
+
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1820
1820
|
assertLock(lock);
|
|
1821
1821
|
for (const current of [fstatSync(fd), lstatSync(path)]) {
|
|
1822
1822
|
requireFile(current);
|
|
1823
|
-
if (!sameSnapshot(details, current)) fail$
|
|
1823
|
+
if (!sameSnapshot(details, current)) fail$3("changed_during_read");
|
|
1824
1824
|
}
|
|
1825
|
-
if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail$
|
|
1826
|
-
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$
|
|
1825
|
+
if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail$3("changed_during_read");
|
|
1826
|
+
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1827
1827
|
assertLock(lock);
|
|
1828
1828
|
}
|
|
1829
1829
|
function finishNativeRecovery(snapshot, keepReceipt) {
|
|
@@ -1884,11 +1884,11 @@ async function recoverNativeHookReceipt({ provider, receipt, deliver, keepReceip
|
|
|
1884
1884
|
let result;
|
|
1885
1885
|
try {
|
|
1886
1886
|
const metadata = parseReceipt(receipt);
|
|
1887
|
-
if (typeof deliver !== "function") fail$
|
|
1887
|
+
if (typeof deliver !== "function") fail$3("invalid_delivery");
|
|
1888
1888
|
const dir = providerDirectory(provider);
|
|
1889
1889
|
const directory = requireSafeSpoolDirectory(dir);
|
|
1890
1890
|
dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
|
|
1891
|
-
if (!sameInode(directory, fstatSync(dirFd))) fail$
|
|
1891
|
+
if (!sameInode(directory, fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1892
1892
|
lock = acquireLock(dir, receipt.slice(`rejected-${metadata.status}-${metadata.reason}-`.length, -9), dirFd);
|
|
1893
1893
|
result = await deliverNativeRecovery({
|
|
1894
1894
|
dir,
|
|
@@ -1914,7 +1914,7 @@ function inspectionError(code) {
|
|
|
1914
1914
|
if (code === "unsafe_entry") message = "Stop capture and verify the receipt before retrying. It must remain the same regular file, not a symlink. On POSIX, it must not be group- or other-writable. No permissions were changed.";
|
|
1915
1915
|
return new RawEventSpoolInspectionError(code, message);
|
|
1916
1916
|
}
|
|
1917
|
-
function fail$
|
|
1917
|
+
function fail$3(code) {
|
|
1918
1918
|
throw inspectionError(code);
|
|
1919
1919
|
}
|
|
1920
1920
|
function hasCode(error, code) {
|
|
@@ -1927,17 +1927,17 @@ function sameSnapshot(a, b) {
|
|
|
1927
1927
|
return sameInode(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
1928
1928
|
}
|
|
1929
1929
|
function requireFile(stat) {
|
|
1930
|
-
if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail$
|
|
1930
|
+
if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail$3("unsafe_entry");
|
|
1931
1931
|
}
|
|
1932
1932
|
function requireDirectory(dir) {
|
|
1933
1933
|
const stat = lstatSync(dir);
|
|
1934
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) fail$
|
|
1934
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) fail$3("unsafe_directory");
|
|
1935
1935
|
return stat;
|
|
1936
1936
|
}
|
|
1937
1937
|
function requireSafeSpoolDirectory(dir) {
|
|
1938
1938
|
const stat = requireDirectory(dir);
|
|
1939
1939
|
const parent = requireDirectory(dirname(resolve(dir)));
|
|
1940
|
-
if (posix$1 && (stat.uid !== process.geteuid?.() || (stat.mode & 18) !== 0 || parent.uid !== process.geteuid?.() && parent.uid !== 0 || (parent.mode & 18) !== 0 && (parent.mode & 512) === 0)) fail$
|
|
1940
|
+
if (posix$1 && (stat.uid !== process.geteuid?.() || (stat.mode & 18) !== 0 || parent.uid !== process.geteuid?.() && parent.uid !== 0 || (parent.mode & 18) !== 0 && (parent.mode & 512) === 0)) fail$3("unsafe_directory");
|
|
1941
1941
|
return stat;
|
|
1942
1942
|
}
|
|
1943
1943
|
function openFile(path) {
|
|
@@ -1947,7 +1947,7 @@ function openFile(path) {
|
|
|
1947
1947
|
try {
|
|
1948
1948
|
for (const actual of [fstatSync(fd), lstatSync(path)]) {
|
|
1949
1949
|
requireFile(actual);
|
|
1950
|
-
if (!sameInode(actual, expected)) fail$
|
|
1950
|
+
if (!sameInode(actual, expected)) fail$3("unsafe_entry");
|
|
1951
1951
|
}
|
|
1952
1952
|
return fd;
|
|
1953
1953
|
} catch (error) {
|
|
@@ -1969,9 +1969,9 @@ function readLimited(fd, limit) {
|
|
|
1969
1969
|
return null;
|
|
1970
1970
|
}
|
|
1971
1971
|
function parseReceipt(receipt) {
|
|
1972
|
-
if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail$
|
|
1972
|
+
if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail$3("invalid_receipt");
|
|
1973
1973
|
const match = retainedPattern.exec(receipt);
|
|
1974
|
-
if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail$
|
|
1974
|
+
if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail$3("invalid_receipt");
|
|
1975
1975
|
if (match[1] === "400-invalid_payload") return {
|
|
1976
1976
|
receipt,
|
|
1977
1977
|
status: 400,
|
|
@@ -1987,7 +1987,7 @@ function providerDirectory(provider) {
|
|
|
1987
1987
|
if (provider === "claude") return spoolDir();
|
|
1988
1988
|
if (provider === "codex") return codexHookSpoolDir();
|
|
1989
1989
|
if (provider === "pi") return piHookSpoolDir();
|
|
1990
|
-
return fail$
|
|
1990
|
+
return fail$3("invalid_provider");
|
|
1991
1991
|
}
|
|
1992
1992
|
function safeFailure(error, lock) {
|
|
1993
1993
|
let failure;
|
|
@@ -2105,9 +2105,9 @@ function classifyLock(path, receipt) {
|
|
|
2105
2105
|
try {
|
|
2106
2106
|
const before = fstatSync(fd);
|
|
2107
2107
|
const bytes = before.size <= 1024 ? readLimited(fd, 1024) : null;
|
|
2108
|
-
if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail$
|
|
2108
|
+
if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail$3(code);
|
|
2109
2109
|
const record = JSON.parse(bytes.toString("utf8"));
|
|
2110
|
-
if (Object.keys(record).sort().join() !== "pid,purpose,receipt,token,version" || record.purpose !== lockPurpose || record.version !== 1 || record.receipt !== receipt || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token)) fail$
|
|
2110
|
+
if (Object.keys(record).sort().join() !== "pid,purpose,receipt,token,version" || record.purpose !== lockPurpose || record.version !== 1 || record.receipt !== receipt || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token)) fail$3(code);
|
|
2111
2111
|
try {
|
|
2112
2112
|
process.kill(record.pid, 0);
|
|
2113
2113
|
code = "lock_busy";
|
|
@@ -2118,7 +2118,7 @@ function classifyLock(path, receipt) {
|
|
|
2118
2118
|
closeSync(fd);
|
|
2119
2119
|
}
|
|
2120
2120
|
} catch {}
|
|
2121
|
-
return fail$
|
|
2121
|
+
return fail$3(code);
|
|
2122
2122
|
}
|
|
2123
2123
|
function cleanupNewLock(fd, path, dirFd) {
|
|
2124
2124
|
try {
|
|
@@ -2141,7 +2141,7 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2141
2141
|
fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | (constants.O_NOFOLLOW ?? 0), 384);
|
|
2142
2142
|
} catch (error) {
|
|
2143
2143
|
if (hasCode(error, "EEXIST")) return classifyLock(path, receipt);
|
|
2144
|
-
return fail$
|
|
2144
|
+
return fail$3("lock_failed");
|
|
2145
2145
|
}
|
|
2146
2146
|
try {
|
|
2147
2147
|
const serialized = JSON.stringify({
|
|
@@ -2152,11 +2152,11 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2152
2152
|
token: randomUUID()
|
|
2153
2153
|
});
|
|
2154
2154
|
const data = Buffer.from(serialized);
|
|
2155
|
-
if (writeSync(fd, data) !== data.length) fail$
|
|
2155
|
+
if (writeSync(fd, data) !== data.length) fail$3("lock_repair_required");
|
|
2156
2156
|
fsyncSync(fd);
|
|
2157
2157
|
const details = fstatSync(fd);
|
|
2158
2158
|
requireFile(details);
|
|
2159
|
-
if (!sameSnapshot(details, lstatSync(path))) fail$
|
|
2159
|
+
if (!sameSnapshot(details, lstatSync(path))) fail$3("lock_repair_required");
|
|
2160
2160
|
return {
|
|
2161
2161
|
fd,
|
|
2162
2162
|
path,
|
|
@@ -2164,12 +2164,12 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2164
2164
|
details
|
|
2165
2165
|
};
|
|
2166
2166
|
} catch {
|
|
2167
|
-
return fail$
|
|
2167
|
+
return fail$3(cleanupNewLock(fd, path, dirFd) ? "lock_failed" : "lock_repair_required");
|
|
2168
2168
|
}
|
|
2169
2169
|
}
|
|
2170
2170
|
function assertLock(lock) {
|
|
2171
2171
|
const bytes = readLimited(lock.fd, 1024);
|
|
2172
|
-
if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail$
|
|
2172
|
+
if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail$3("lock_repair_required");
|
|
2173
2173
|
}
|
|
2174
2174
|
function releaseLock(lock, dirFd) {
|
|
2175
2175
|
try {
|
|
@@ -2206,17 +2206,17 @@ function linkIfAbsent(source, target) {
|
|
|
2206
2206
|
function requireLinkedSnapshot(path, before) {
|
|
2207
2207
|
const current = lstatSync(path);
|
|
2208
2208
|
requireFile(current);
|
|
2209
|
-
if (!sameInode(before, current)) fail$
|
|
2210
|
-
if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail$
|
|
2209
|
+
if (!sameInode(before, current)) fail$3("retention_conflict");
|
|
2210
|
+
if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail$3("unsafe_entry");
|
|
2211
2211
|
}
|
|
2212
2212
|
function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
2213
2213
|
const source = join(dir, receipt);
|
|
2214
2214
|
const target = join(dir, metadata.receipt);
|
|
2215
2215
|
const alternateStatus = metadata.status === 400 ? "413-payload_too_large" : "400-invalid_payload";
|
|
2216
|
-
if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail$
|
|
2216
|
+
if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail$3("retention_conflict");
|
|
2217
2217
|
const existing = statIfPresent(target);
|
|
2218
2218
|
if (!statIfPresent(source)) {
|
|
2219
|
-
if (!existing) fail$
|
|
2219
|
+
if (!existing) fail$3("receipt_not_found");
|
|
2220
2220
|
const fd = openFile(target);
|
|
2221
2221
|
try {
|
|
2222
2222
|
assertOwnership();
|
|
@@ -2234,9 +2234,9 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
|
2234
2234
|
const fd = openFile(source);
|
|
2235
2235
|
try {
|
|
2236
2236
|
const before = fstatSync(fd);
|
|
2237
|
-
if (existing && !sameInode(existing, before)) fail$
|
|
2237
|
+
if (existing && !sameInode(existing, before)) fail$3("retention_conflict");
|
|
2238
2238
|
fsyncSync(fd);
|
|
2239
|
-
if (!sameSnapshot(before, lstatSync(source))) fail$
|
|
2239
|
+
if (!sameSnapshot(before, lstatSync(source))) fail$3("unsafe_entry");
|
|
2240
2240
|
assertOwnership();
|
|
2241
2241
|
if (!existing) linkIfAbsent(source, target);
|
|
2242
2242
|
fsyncSync(dirFd);
|
|
@@ -2256,17 +2256,17 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
|
2256
2256
|
/** Delivery callers must also hold the provider's ingest lock to coordinate ordinary drain cleanup. */
|
|
2257
2257
|
function retainNativeHookReceipt({ dir, receipt, status, reason }) {
|
|
2258
2258
|
try {
|
|
2259
|
-
if (typeof receipt !== "string" || !isOriginalName(receipt)) fail$
|
|
2259
|
+
if (typeof receipt !== "string" || !isOriginalName(receipt)) fail$3("invalid_receipt");
|
|
2260
2260
|
const metadata = parseReceipt(`rejected-${status}-${reason}-${receipt}.retained`);
|
|
2261
2261
|
const directory = requireSafeSpoolDirectory(dir);
|
|
2262
2262
|
const dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
|
|
2263
2263
|
try {
|
|
2264
|
-
if (!sameInode(directory, fstatSync(dirFd))) fail$
|
|
2264
|
+
if (!sameInode(directory, fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
2265
2265
|
const lock = acquireLock(dir, receipt, dirFd);
|
|
2266
2266
|
let result;
|
|
2267
2267
|
try {
|
|
2268
2268
|
result = retainLinked(dir, dirFd, receipt, metadata, () => {
|
|
2269
|
-
if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail$
|
|
2269
|
+
if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail$3("unsafe_directory");
|
|
2270
2270
|
assertLock(lock);
|
|
2271
2271
|
});
|
|
2272
2272
|
} catch (error) {
|
|
@@ -3958,7 +3958,7 @@ function buildCoordinatorDiagnoseTeamSetupCommand() {
|
|
|
3958
3958
|
}
|
|
3959
3959
|
//#endregion
|
|
3960
3960
|
//#region src/commands/coordinator-enable-device.ts
|
|
3961
|
-
function fail$
|
|
3961
|
+
function fail$2(options, code, message) {
|
|
3962
3962
|
if (options.json) return emitJsonError(code, message);
|
|
3963
3963
|
p.log.error(message);
|
|
3964
3964
|
process.exitCode = 1;
|
|
@@ -3973,7 +3973,7 @@ async function enableDevice(group, device, options) {
|
|
|
3973
3973
|
dbPath: resolveDbOpt(options),
|
|
3974
3974
|
remoteUrl: "",
|
|
3975
3975
|
adminSecret: ""
|
|
3976
|
-
})) return fail$
|
|
3976
|
+
})) return fail$2(options, "device_not_enabled", "The device was not enabled. It has no enrollment in this group, or it is permanently blocked.");
|
|
3977
3977
|
if (options.json) {
|
|
3978
3978
|
console.log(JSON.stringify({
|
|
3979
3979
|
ok: true,
|
|
@@ -3985,9 +3985,9 @@ async function enableDevice(group, device, options) {
|
|
|
3985
3985
|
p.log.success("Device enabled.");
|
|
3986
3986
|
} catch (error) {
|
|
3987
3987
|
const code = error instanceof Error ? error.message : "";
|
|
3988
|
-
if (code === "device_removed") return fail$
|
|
3989
|
-
if (code === "device_revoked") return fail$
|
|
3990
|
-
return fail$
|
|
3988
|
+
if (code === "device_removed") return fail$2(options, code, "This device was removed. It must rejoin before it can be enabled.");
|
|
3989
|
+
if (code === "device_revoked") return fail$2(options, code, "This device is permanently blocked.");
|
|
3990
|
+
return fail$2(options, "enable_failed", "Could not enable the device. Check the coordinator database and device IDs.");
|
|
3991
3991
|
}
|
|
3992
3992
|
}
|
|
3993
3993
|
function buildCoordinatorEnableDeviceCommand() {
|
|
@@ -4026,7 +4026,7 @@ function reportUsageError(options, message) {
|
|
|
4026
4026
|
}
|
|
4027
4027
|
return false;
|
|
4028
4028
|
}
|
|
4029
|
-
function usage(options) {
|
|
4029
|
+
function usage$1(options) {
|
|
4030
4030
|
if (options.prepare === options.resume || options.prepare && (options.capability || options.reviewDigest || options.accountAdmission) || options.accountAdmission && options.capability !== void 0 || options.resume && !options.reviewDigest || options.resume && (options.json || !process.stderr.isTTY)) return reportUsageError(options, "Use --prepare first, then review its device, current Identity, capture counts and digest. Resume interactively with --resume --review-digest; use either --capability for operator admission or --account-admission for signed-in account admission, never both.");
|
|
4031
4031
|
if (options.capability !== void 0 && !/^[A-Za-z0-9._-]{1,512}$/.test(options.capability)) return reportUsageError(options, "Supply --capability exactly as issued, without whitespace or unsupported characters, and at most 512 characters. The prepared attempt has not been consumed.");
|
|
4032
4032
|
if (options.reviewDigest !== void 0 && !/^[0-9a-f]{64}$/.test(options.reviewDigest)) return reportUsageError(options, "Supply --review-digest as the exact 64-character lowercase hexadecimal digest from --prepare. Enrollment has not started.");
|
|
@@ -4113,7 +4113,7 @@ function resolveEnrollmentProfile(options) {
|
|
|
4113
4113
|
};
|
|
4114
4114
|
}
|
|
4115
4115
|
async function enroll(groupId, options) {
|
|
4116
|
-
if (!usage(options)) return;
|
|
4116
|
+
if (!usage$1(options)) return;
|
|
4117
4117
|
if (!groupUsage(options, groupId)) return;
|
|
4118
4118
|
if (!pathEnvironmentUsage(options, {
|
|
4119
4119
|
config: options.config,
|
|
@@ -4337,7 +4337,7 @@ function invitationFailure(raw) {
|
|
|
4337
4337
|
const described = describeFailure(raw);
|
|
4338
4338
|
return new InvitationCreateError(described.code, described.message);
|
|
4339
4339
|
}
|
|
4340
|
-
function fail(code, message) {
|
|
4340
|
+
function fail$1(code, message) {
|
|
4341
4341
|
const exitCode = USAGE_ERRORS.has(code) ? 2 : 1;
|
|
4342
4342
|
if (message) throw new InvitationCreateError(code, message, exitCode);
|
|
4343
4343
|
const described = describeFailure(code);
|
|
@@ -4350,12 +4350,12 @@ function resolveTeamId(store, team) {
|
|
|
4350
4350
|
const key = team.normalize("NFC").toLowerCase();
|
|
4351
4351
|
const byName = rows.filter((row) => row.display_name.normalize("NFC").toLowerCase() === key);
|
|
4352
4352
|
if (byName.length === 1 && byName[0]) return byName[0].team_id;
|
|
4353
|
-
if (byName.length > 1) fail("team_ambiguous", `More than one Team is named "${team}". Pass its Team ID instead.`);
|
|
4354
|
-
return fail("team_not_found", `No active Team named "${team}" on this device. Create it in Sharing, or run this on a device where it exists.`);
|
|
4353
|
+
if (byName.length > 1) fail$1("team_ambiguous", `More than one Team is named "${team}". Pass its Team ID instead.`);
|
|
4354
|
+
return fail$1("team_not_found", `No active Team named "${team}" on this device. Create it in Sharing, or run this on a device where it exists.`);
|
|
4355
4355
|
}
|
|
4356
4356
|
function requestBody(store, opts, legacyArgs) {
|
|
4357
|
-
if (legacyArgs.length > 0 || Boolean(opts.team) === Boolean(opts.addDevice)) fail("invitation_kind_required", "Choose --team <name> or --add-device. codemem no longer creates invitations that only connect a device. To connect a device without sharing Projects, use `codemem coordinator device enroll`.");
|
|
4358
|
-
if (opts.review && opts.reviewedOnboardingDigest !== void 0) fail("usage_error", "Use --review or --reviewed-onboarding-digest, not both.");
|
|
4357
|
+
if (legacyArgs.length > 0 || Boolean(opts.team) === Boolean(opts.addDevice)) fail$1("invitation_kind_required", "Choose --team <name> or --add-device. codemem no longer creates invitations that only connect a device. To connect a device without sharing Projects, use `codemem coordinator device enroll`.");
|
|
4358
|
+
if (opts.review && opts.reviewedOnboardingDigest !== void 0) fail$1("usage_error", "Use --review or --reviewed-onboarding-digest, not both.");
|
|
4359
4359
|
return {
|
|
4360
4360
|
...opts.team ? {
|
|
4361
4361
|
kind: "team_member",
|
|
@@ -4371,7 +4371,7 @@ function requestBody(store, opts, legacyArgs) {
|
|
|
4371
4371
|
}
|
|
4372
4372
|
function unwrap(outcome) {
|
|
4373
4373
|
if (outcome.httpStatus === 200) return outcome.body;
|
|
4374
|
-
return fail(String(outcome.body.error ?? "invitation_create_failed"));
|
|
4374
|
+
return fail$1(String(outcome.body.error ?? "invitation_create_failed"));
|
|
4375
4375
|
}
|
|
4376
4376
|
function printReview(body, opts) {
|
|
4377
4377
|
const preview = body.preview;
|
|
@@ -4412,7 +4412,7 @@ async function runInvitationCreate(opts, legacyArgs, deps) {
|
|
|
4412
4412
|
printReview(unwrap(await deps.preview(store, body)), opts);
|
|
4413
4413
|
return;
|
|
4414
4414
|
}
|
|
4415
|
-
if (!opts.reviewedOnboardingDigest) fail("reviewed_onboarding_digest_required");
|
|
4415
|
+
if (!opts.reviewedOnboardingDigest) fail$1("reviewed_onboarding_digest_required");
|
|
4416
4416
|
printCreated(unwrap(await deps.create(store, body)), opts);
|
|
4417
4417
|
} finally {
|
|
4418
4418
|
store.close();
|
|
@@ -4866,6 +4866,83 @@ function buildCoordinatorQualifyOwnerCommand() {
|
|
|
4866
4866
|
return command;
|
|
4867
4867
|
}
|
|
4868
4868
|
//#endregion
|
|
4869
|
+
//#region src/commands/coordinator-record-token-floor.ts
|
|
4870
|
+
/** Sealing batches before the command stops and asks for another run. */
|
|
4871
|
+
var MAX_BATCHES = 1e3;
|
|
4872
|
+
function fail(options, code, message) {
|
|
4873
|
+
if (options.json) return emitJsonError(code, message);
|
|
4874
|
+
p.log.error(message);
|
|
4875
|
+
process.exitCode = 1;
|
|
4876
|
+
}
|
|
4877
|
+
var REFUSALS = {
|
|
4878
|
+
coordinator_metadata_unavailable: "This coordinator database has no metadata table. Start `codemem coordinator serve` on it once, then try again.",
|
|
4879
|
+
invite_token_key_unavailable: "No invitation token key is available. Configure CODEMEM_INVITE_TOKEN_KEY, or let the coordinator create its key file.",
|
|
4880
|
+
invite_token_key_invalid: "The configured invitation token key is not a 32-byte key."
|
|
4881
|
+
};
|
|
4882
|
+
function refusalMessage(error) {
|
|
4883
|
+
return REFUSALS[error.code] ?? error.message;
|
|
4884
|
+
}
|
|
4885
|
+
/** Seals the tokens stored before the floor, batch by batch, until none remain. */
|
|
4886
|
+
async function sealStoredTokens(store) {
|
|
4887
|
+
let progress = await store.sealStoredInviteTokens(100);
|
|
4888
|
+
for (let batch = 1; batch < MAX_BATCHES; batch += 1) {
|
|
4889
|
+
if (progress.remaining_plaintext_invites + progress.remaining_plaintext_join_requests + progress.remaining_spent_ciphertext === 0) break;
|
|
4890
|
+
progress = await store.sealStoredInviteTokens(100);
|
|
4891
|
+
}
|
|
4892
|
+
return progress;
|
|
4893
|
+
}
|
|
4894
|
+
/** Why this coordinator could not seal with its key, or null when it can. */
|
|
4895
|
+
function keyRefusal(store) {
|
|
4896
|
+
return store.prepareInviteTokenKey().then(() => null, (error) => {
|
|
4897
|
+
if (error instanceof InviteTokenRefusal) return error;
|
|
4898
|
+
throw error;
|
|
4899
|
+
});
|
|
4900
|
+
}
|
|
4901
|
+
/** The coordinator store at `dbPath`, or null when the file is not a readable coordinator database. */
|
|
4902
|
+
function openStore(dbPath) {
|
|
4903
|
+
try {
|
|
4904
|
+
return new BetterSqliteCoordinatorStore(dbPath);
|
|
4905
|
+
} catch {
|
|
4906
|
+
return null;
|
|
4907
|
+
}
|
|
4908
|
+
}
|
|
4909
|
+
async function recordFloor(versionText, options) {
|
|
4910
|
+
const version = Number(versionText);
|
|
4911
|
+
if (!/^\d+$/u.test(versionText.trim()) || !Number.isSafeInteger(version) || version < 1) return fail(options, "invalid_version", "Enter the lookup version as a whole number, such as 1.");
|
|
4912
|
+
if (version > INVITE_TOKEN_LOOKUP_VERSION) return fail(options, "version_above_build", `This codemem release has invitation token lookup version ${INVITE_TOKEN_LOOKUP_VERSION}. It cannot record a higher floor.`);
|
|
4913
|
+
const dbPath = resolveDbOpt(options) ?? DEFAULT_COORDINATOR_DB_PATH;
|
|
4914
|
+
if (!existsSync(dbPath)) return fail(options, "coordinator_database_missing", `No coordinator database at ${dbPath}.`);
|
|
4915
|
+
const store = openStore(dbPath);
|
|
4916
|
+
if (!store) return fail(options, "coordinator_database_unreadable", `Could not open ${dbPath} as a coordinator database.`);
|
|
4917
|
+
try {
|
|
4918
|
+
const keyRefused = await keyRefusal(store);
|
|
4919
|
+
if (keyRefused) return fail(options, keyRefused.code, `${refusalMessage(keyRefused)} The floor was not recorded.`);
|
|
4920
|
+
const fence = await store.raiseInviteTokenLookupFloor(version);
|
|
4921
|
+
const progress = await sealStoredTokens(store);
|
|
4922
|
+
if (options.json) {
|
|
4923
|
+
console.log(JSON.stringify({
|
|
4924
|
+
ok: true,
|
|
4925
|
+
...fence,
|
|
4926
|
+
...progress
|
|
4927
|
+
}, null, 2));
|
|
4928
|
+
return;
|
|
4929
|
+
}
|
|
4930
|
+
p.log.success(`Recorded invitation token lookup floor ${fence.min_serving_lookup_version}. This coordinator now encrypts invitation tokens.`);
|
|
4931
|
+
p.log.info(`Sealed ${progress.sealed_invites} stored invitations in the last batch; ${progress.remaining_plaintext_invites} still hold their token.`);
|
|
4932
|
+
} catch (error) {
|
|
4933
|
+
if (error instanceof InviteTokenRefusal) return fail(options, error.code, refusalMessage(error));
|
|
4934
|
+
return fail(options, "record_floor_failed", "Could not record the floor. Check the coordinator database.");
|
|
4935
|
+
} finally {
|
|
4936
|
+
await store.close();
|
|
4937
|
+
}
|
|
4938
|
+
}
|
|
4939
|
+
function buildCoordinatorRecordTokenFloorCommand() {
|
|
4940
|
+
const command = new Command("record-floor").configureHelp(helpStyle).description("Confirm that no codemem release older than this invitation token lookup version opens the coordinator database, then encrypt its stored invitation tokens").argument("<version>", `lookup version; at most ${INVITE_TOKEN_LOOKUP_VERSION} for this release`);
|
|
4941
|
+
addDbOption(command);
|
|
4942
|
+
addJsonOption(command);
|
|
4943
|
+
return command.action(recordFloor);
|
|
4944
|
+
}
|
|
4945
|
+
//#endregion
|
|
4869
4946
|
//#region src/commands/coordinator-review-device-owner.ts
|
|
4870
4947
|
var REVIEW_REASONS = [
|
|
4871
4948
|
"group_unavailable",
|
|
@@ -5351,7 +5428,8 @@ function inviteImportProfile(invite, opts) {
|
|
|
5351
5428
|
keysDir: opts.keysDir ?? null,
|
|
5352
5429
|
configPath: opts.config ?? null,
|
|
5353
5430
|
recipientDisplayName: opts.recipientName?.trim() || null,
|
|
5354
|
-
deviceDisplayName: opts.deviceName?.trim() || null
|
|
5431
|
+
deviceDisplayName: opts.deviceName?.trim() || null,
|
|
5432
|
+
confirmCoordinatorJoin: opts.confirmCoordinatorJoin === true
|
|
5355
5433
|
};
|
|
5356
5434
|
}
|
|
5357
5435
|
async function acceptInviteWithProfileCheck(profile, reviewedOnboardingDigest) {
|
|
@@ -5364,6 +5442,37 @@ async function acceptInviteWithProfileCheck(profile, reviewedOnboardingDigest) {
|
|
|
5364
5442
|
reviewedOnboardingDigest: digest
|
|
5365
5443
|
});
|
|
5366
5444
|
}
|
|
5445
|
+
var COORDINATOR_JOIN_WARNING = "Joining a coordinator permanently turns off syncing without a coordinator for this device's key, including other codemem profiles that use the same key.";
|
|
5446
|
+
function addInviteAcceptOptions(command) {
|
|
5447
|
+
addDbOption(command);
|
|
5448
|
+
addConfigOption(command);
|
|
5449
|
+
addJsonOption(command);
|
|
5450
|
+
command.option("--confirm-coordinator-join", "Join even though it permanently turns off syncing without a coordinator for this device's key");
|
|
5451
|
+
}
|
|
5452
|
+
/** The invitation is fine; this device couldn't record the join before sending it. */
|
|
5453
|
+
function explainRecordFailure(error) {
|
|
5454
|
+
if (error instanceof Error && error.message === COORDINATOR_FREE_WITNESS_UNAVAILABLE) throw new Error("codemem couldn't save this device's coordinator record. Unlock or repair the keychain, or make the codemem keys folder writable, then try again.");
|
|
5455
|
+
if (error instanceof Error && error.message === COORDINATOR_FREE_BINDING_UNVERIFIED) throw new Error("codemem couldn't check this device's coordinator record because a file in the codemem keys folder is missing or damaged. Restore the keys folder that belongs with this database, then try again.");
|
|
5456
|
+
throw error;
|
|
5457
|
+
}
|
|
5458
|
+
/** Accepts after the user confirms a join that turns off syncing without a coordinator. */
|
|
5459
|
+
async function acceptInviteWithJoinConfirmation(profile, opts) {
|
|
5460
|
+
const accept = (accepted) => acceptInviteWithProfileCheck(accepted, opts.reviewedOnboardingDigest).catch(explainRecordFailure);
|
|
5461
|
+
try {
|
|
5462
|
+
return await accept(profile);
|
|
5463
|
+
} catch (error) {
|
|
5464
|
+
if (!(error instanceof Error) || error.message !== COORDINATOR_JOIN_CONFIRMATION_REQUIRED) throw error;
|
|
5465
|
+
if (opts.json || !process.stdin.isTTY) throw new Error(`${COORDINATOR_JOIN_WARNING} To join, run the command again with --confirm-coordinator-join.`);
|
|
5466
|
+
if (await p.confirm({
|
|
5467
|
+
message: `${COORDINATOR_JOIN_WARNING} Join this coordinator?`,
|
|
5468
|
+
initialValue: false
|
|
5469
|
+
}) !== true) throw new Error("Invitation not accepted.");
|
|
5470
|
+
return accept({
|
|
5471
|
+
...profile,
|
|
5472
|
+
confirmCoordinatorJoin: true
|
|
5473
|
+
});
|
|
5474
|
+
}
|
|
5475
|
+
}
|
|
5367
5476
|
function rejectConflictingInviteReviewOptions(opts) {
|
|
5368
5477
|
if (!opts.review || opts.reviewedOnboardingDigest === void 0) return false;
|
|
5369
5478
|
const message = "Use --review or --reviewed-onboarding-digest, not both.";
|
|
@@ -5978,9 +6087,7 @@ function buildCoordinatorCommand() {
|
|
|
5978
6087
|
grant.addCommand(revokeBootstrapGrantCmd);
|
|
5979
6088
|
invitation.addCommand(buildCoordinatorInvitationCreateCommand());
|
|
5980
6089
|
const importInviteCmd = new Command("accept").configureHelp(helpStyle).description("Accept a coordinator invitation or review recipient access").argument("<invite>", "invite value or link").option("-R, --recipient-name <name>", "recipient Identity display name").option("-N, --device-name <name>", "device display name").option("--review", "Review recipient access without accepting").option("--reviewed-onboarding-digest <digest>", "Accept the reviewed recipient access").option("--keys-dir <path>", "keys directory");
|
|
5981
|
-
|
|
5982
|
-
addConfigOption(importInviteCmd);
|
|
5983
|
-
addJsonOption(importInviteCmd);
|
|
6090
|
+
addInviteAcceptOptions(importInviteCmd);
|
|
5984
6091
|
importInviteCmd.action(async (invite, opts) => {
|
|
5985
6092
|
try {
|
|
5986
6093
|
if (rejectConflictingInviteReviewOptions(opts)) return;
|
|
@@ -5989,7 +6096,7 @@ function buildCoordinatorCommand() {
|
|
|
5989
6096
|
printInviteReview(await coordinatorReviewInviteAction(profile), opts);
|
|
5990
6097
|
return;
|
|
5991
6098
|
}
|
|
5992
|
-
const result = await
|
|
6099
|
+
const result = await acceptInviteWithJoinConfirmation(profile, opts);
|
|
5993
6100
|
if (opts.json) {
|
|
5994
6101
|
console.log(JSON.stringify(result, null, 2));
|
|
5995
6102
|
return;
|
|
@@ -6009,7 +6116,7 @@ function buildCoordinatorCommand() {
|
|
|
6009
6116
|
process.exitCode = 1;
|
|
6010
6117
|
}
|
|
6011
6118
|
});
|
|
6012
|
-
invitation.addCommand(importInviteCmd);
|
|
6119
|
+
invitation.addCommand(importInviteCmd).addCommand(buildCoordinatorRecordTokenFloorCommand());
|
|
6013
6120
|
const listJoinRequestsCmd = new Command("list").configureHelp(helpStyle).description("List pending coordinator join requests").argument("[group]", "group id").option("--group <group>", "group id").option("--remote-url <url>", "remote coordinator URL override").option("--admin-secret <secret>", "remote coordinator admin secret override");
|
|
6014
6121
|
addDbOption(listJoinRequestsCmd);
|
|
6015
6122
|
addJsonOption(listJoinRequestsCmd);
|
|
@@ -6438,9 +6545,8 @@ function estimateReplicationOpsBytes(db) {
|
|
|
6438
6545
|
try {
|
|
6439
6546
|
const row = db.prepare(`SELECT COALESCE(SUM(pgsize), 0) AS total_bytes
|
|
6440
6547
|
FROM dbstat
|
|
6441
|
-
WHERE name =
|
|
6442
|
-
|
|
6443
|
-
OR name LIKE 'sqlite_autoindex_replication_ops_%'`).get();
|
|
6548
|
+
WHERE name IN (SELECT name FROM sqlite_schema WHERE tbl_name =
|
|
6549
|
+
COALESCE((SELECT tbl_name FROM sqlite_schema WHERE name='idx_replication_ops_created'),'replication_ops'))`).get();
|
|
6444
6550
|
return Number(row?.total_bytes ?? 0);
|
|
6445
6551
|
} catch {
|
|
6446
6552
|
return 0;
|
|
@@ -7026,6 +7132,10 @@ var runMemoryRedactSecrets = (opts) => {
|
|
|
7026
7132
|
});
|
|
7027
7133
|
p.log.info(`Affected memories:\n${lines.join("\n")}`);
|
|
7028
7134
|
}
|
|
7135
|
+
if (result.unpropagatedRedactions.length > 0) {
|
|
7136
|
+
const ids = result.unpropagatedRedactions.map((entry) => `#${entry.id}`).join(", ");
|
|
7137
|
+
p.log.warn(`Redacted here only: ${result.unpropagatedRedactions.length} memories in synced scopes that this device cannot show it created, so peers that received them keep the unredacted copy: ${ids}. Redact them on the device that wrote them, or remove them from the peers.`);
|
|
7138
|
+
}
|
|
7029
7139
|
p.outro("Re-run with no changes to confirm idempotency");
|
|
7030
7140
|
} catch (error) {
|
|
7031
7141
|
p.log.error(error instanceof Error ? error.message : String(error));
|
|
@@ -9681,6 +9791,11 @@ function createRetentionRunners(dbPath, syncConfig, logger, signal) {
|
|
|
9681
9791
|
signal,
|
|
9682
9792
|
logger
|
|
9683
9793
|
}));
|
|
9794
|
+
runners.push(new SessionRepositoryIdentityRunner({
|
|
9795
|
+
dbPath,
|
|
9796
|
+
signal,
|
|
9797
|
+
logger
|
|
9798
|
+
}));
|
|
9684
9799
|
runners.push(new ReplicationBackfillRunner({
|
|
9685
9800
|
dbPath,
|
|
9686
9801
|
signal,
|
|
@@ -9853,7 +9968,7 @@ async function pruneUntilDone(db, batchSize) {
|
|
|
9853
9968
|
if (pass.complete || !progressed) return totals;
|
|
9854
9969
|
}
|
|
9855
9970
|
}
|
|
9856
|
-
function reportFailure$
|
|
9971
|
+
function reportFailure$2(opts, code, message, exitCode) {
|
|
9857
9972
|
if (opts.json) {
|
|
9858
9973
|
emitJsonError(code, message, exitCode);
|
|
9859
9974
|
return;
|
|
@@ -9872,7 +9987,7 @@ function reportHuman(purged) {
|
|
|
9872
9987
|
async function runPruneRetrievalLedger(opts) {
|
|
9873
9988
|
const batchSize = parseBatchSize(opts.batchSize);
|
|
9874
9989
|
if (batchSize === null) {
|
|
9875
|
-
reportFailure$
|
|
9990
|
+
reportFailure$2(opts, "invalid_batch_size", `--batch-size must be an integer from 1 to 10000 (got "${opts.batchSize}")`, 2);
|
|
9876
9991
|
return;
|
|
9877
9992
|
}
|
|
9878
9993
|
let db = null;
|
|
@@ -9895,7 +10010,7 @@ async function runPruneRetrievalLedger(opts) {
|
|
|
9895
10010
|
}, null, 2));
|
|
9896
10011
|
} else reportHuman(purged);
|
|
9897
10012
|
} catch (error) {
|
|
9898
|
-
reportFailure$
|
|
10013
|
+
reportFailure$2(opts, "prune_retrieval_ledger_failed", error instanceof Error ? error.message : String(error), 1);
|
|
9899
10014
|
} finally {
|
|
9900
10015
|
db?.close();
|
|
9901
10016
|
}
|
|
@@ -11487,53 +11602,38 @@ function waitForViewerStartup(child, timeoutMs) {
|
|
|
11487
11602
|
});
|
|
11488
11603
|
}
|
|
11489
11604
|
//#endregion
|
|
11490
|
-
//#region src/commands/
|
|
11491
|
-
|
|
11492
|
-
|
|
11493
|
-
|
|
11494
|
-
|
|
11495
|
-
|
|
11496
|
-
|
|
11497
|
-
|
|
11498
|
-
|
|
11499
|
-
|
|
11500
|
-
|
|
11501
|
-
|
|
11502
|
-
|
|
11503
|
-
|
|
11504
|
-
|
|
11505
|
-
|
|
11506
|
-
|
|
11507
|
-
|
|
11605
|
+
//#region src/commands/viewer-stop-verification.ts
|
|
11606
|
+
/**
|
|
11607
|
+
* Which process `codemem serve stop` and `restart` may signal for a database.
|
|
11608
|
+
*
|
|
11609
|
+
* A Viewer is signalled only when it is shown to serve this database, and only while its
|
|
11610
|
+
* pid still names the process that was shown to. Verification happens once and records the
|
|
11611
|
+
* process's identity (start time and command line) and which proof it passed. Right
|
|
11612
|
+
* before each signal, that same proof runs again without HTTP, then the identity is read
|
|
11613
|
+
* again and must match exactly, so the last thing checked before a signal is which process
|
|
11614
|
+
* the pid names.
|
|
11615
|
+
*
|
|
11616
|
+
* A Viewer must be the process listening on its port. A CLI or MCP process that has the
|
|
11617
|
+
* database open, or that an answer at the port names, is never a candidate.
|
|
11618
|
+
*
|
|
11619
|
+
* Proofs:
|
|
11620
|
+
* - A Viewer that holds the database's lock records itself as its owner. The record must
|
|
11621
|
+
* name the pid, its start time and the canonical database, and the lock must be held.
|
|
11622
|
+
* - A Viewer from a release before the lock records nothing. It must be the process
|
|
11623
|
+
* listening on its port, report this database in its prompt-pack profile, and have the
|
|
11624
|
+
* database file or its write-ahead log open, as `lsof` shows. Each is required: a
|
|
11625
|
+
* process can have a database open without serving it. Those releases cannot read a
|
|
11626
|
+
* transitioned store, so for one only the lock proof is accepted.
|
|
11627
|
+
*
|
|
11628
|
+
* On macOS and Linux, a check that needs `lsof` refuses when `lsof` cannot run. On native
|
|
11629
|
+
* Windows there is no `lsof` or `ps`: a Viewer there cannot be identified at all, and the
|
|
11630
|
+
* database proofs that need `lsof` are not asked of it.
|
|
11631
|
+
*/
|
|
11508
11632
|
function isLikelyViewerCommand(command) {
|
|
11509
11633
|
const lowered = command.toLowerCase();
|
|
11510
11634
|
if (!/\b(?:serve|service)\s+start\b/.test(lowered)) return false;
|
|
11511
11635
|
return lowered.includes("codemem") || lowered.includes("packages/cli/dist/index.js") || lowered.includes("/cli/dist/index.js") || lowered.includes("packages/cli/src/index.ts");
|
|
11512
11636
|
}
|
|
11513
|
-
function prepareViewerDatabase(dbPath) {
|
|
11514
|
-
return initDatabase(dbPath ?? void 0).path;
|
|
11515
|
-
}
|
|
11516
|
-
function pickViewerPidCandidate(statsPid, listenerPid) {
|
|
11517
|
-
if (statsPid && listenerPid && statsPid !== listenerPid) return null;
|
|
11518
|
-
return statsPid ?? listenerPid ?? null;
|
|
11519
|
-
}
|
|
11520
|
-
function lookupListeningPid(host, port) {
|
|
11521
|
-
if (!isLocalHost(host)) return null;
|
|
11522
|
-
const result = spawnSync("lsof", [
|
|
11523
|
-
"-nP",
|
|
11524
|
-
`-iTCP:${port}`,
|
|
11525
|
-
"-sTCP:LISTEN",
|
|
11526
|
-
"-t"
|
|
11527
|
-
], {
|
|
11528
|
-
encoding: "utf-8",
|
|
11529
|
-
timeout: 1e3
|
|
11530
|
-
});
|
|
11531
|
-
if (result.status !== 0) return null;
|
|
11532
|
-
const first = (result.stdout || "").split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0);
|
|
11533
|
-
if (!first) return null;
|
|
11534
|
-
const parsed = Number.parseInt(first, 10);
|
|
11535
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
11536
|
-
}
|
|
11537
11637
|
function readProcessCommand(pid) {
|
|
11538
11638
|
const result = spawnSync("ps", [
|
|
11539
11639
|
"-p",
|
|
@@ -11548,12 +11648,212 @@ function readProcessCommand(pid) {
|
|
|
11548
11648
|
const cmd = (result.stdout || "").trim();
|
|
11549
11649
|
return cmd.length > 0 ? cmd : null;
|
|
11550
11650
|
}
|
|
11551
|
-
function
|
|
11552
|
-
|
|
11553
|
-
if (listenerPid && listenerPid !== pid) return false;
|
|
11651
|
+
function readProcessIdentity(pid) {
|
|
11652
|
+
const started = processStartIdentity(pid);
|
|
11554
11653
|
const command = readProcessCommand(pid);
|
|
11555
|
-
|
|
11556
|
-
|
|
11654
|
+
return started && command ? {
|
|
11655
|
+
started,
|
|
11656
|
+
command
|
|
11657
|
+
} : null;
|
|
11658
|
+
}
|
|
11659
|
+
function sameProcess(a, b) {
|
|
11660
|
+
return a.started === b.started && a.command === b.command;
|
|
11661
|
+
}
|
|
11662
|
+
var LSOF_TIMEOUT_MS = 2e3;
|
|
11663
|
+
/** Why `lsof` could not answer, from the error Node reports for the attempt. */
|
|
11664
|
+
function lsofFailure(error) {
|
|
11665
|
+
if (error.code === "ENOENT") return "lsof is not installed or not on PATH";
|
|
11666
|
+
if (error.code === "ETIMEDOUT") return `lsof did not answer within ${LSOF_TIMEOUT_MS} ms`;
|
|
11667
|
+
if (error.code === "EACCES" || error.code === "EPERM") return "lsof could not be run (permission denied)";
|
|
11668
|
+
return `lsof could not be run (${error.code ?? error.message})`;
|
|
11669
|
+
}
|
|
11670
|
+
/**
|
|
11671
|
+
* The lines `lsof` prints, or why it could not run. `lsof` exits 1 when it finds nothing
|
|
11672
|
+
* to list; that is an answer, and the lines are then empty. With `-w` it prints no
|
|
11673
|
+
* warnings, so anything on stderr then is a failure.
|
|
11674
|
+
*/
|
|
11675
|
+
function runLsof(args) {
|
|
11676
|
+
const result = spawnSync("lsof", ["-w", ...args], {
|
|
11677
|
+
encoding: "utf-8",
|
|
11678
|
+
timeout: LSOF_TIMEOUT_MS
|
|
11679
|
+
});
|
|
11680
|
+
if (result.error) return {
|
|
11681
|
+
ok: false,
|
|
11682
|
+
reason: lsofFailure(result.error)
|
|
11683
|
+
};
|
|
11684
|
+
if (result.signal) return {
|
|
11685
|
+
ok: false,
|
|
11686
|
+
reason: `lsof was stopped by ${result.signal}`
|
|
11687
|
+
};
|
|
11688
|
+
const stderr = (result.stderr || "").trim();
|
|
11689
|
+
if (result.status !== 0 && (result.status !== 1 || stderr)) {
|
|
11690
|
+
const detail = stderr.split(/\r?\n/)[0];
|
|
11691
|
+
return {
|
|
11692
|
+
ok: false,
|
|
11693
|
+
reason: `lsof failed with status ${result.status}${detail ? `: ${detail}` : ""}`
|
|
11694
|
+
};
|
|
11695
|
+
}
|
|
11696
|
+
return {
|
|
11697
|
+
ok: true,
|
|
11698
|
+
lines: (result.stdout || "").split(/\r?\n/).filter((line) => line.length > 0)
|
|
11699
|
+
};
|
|
11700
|
+
}
|
|
11701
|
+
/** The pid listening on TCP `port`, null when none is, or why that could not be read. */
|
|
11702
|
+
function listeningPid(port) {
|
|
11703
|
+
const result = runLsof([
|
|
11704
|
+
"-nP",
|
|
11705
|
+
`-iTCP:${port}`,
|
|
11706
|
+
"-sTCP:LISTEN",
|
|
11707
|
+
"-t"
|
|
11708
|
+
]);
|
|
11709
|
+
if (!result.ok) return result;
|
|
11710
|
+
const first = result.lines.map((line) => line.trim()).find((line) => line.length > 0);
|
|
11711
|
+
const parsed = first ? Number.parseInt(first, 10) : NaN;
|
|
11712
|
+
return {
|
|
11713
|
+
ok: true,
|
|
11714
|
+
pid: Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
|
11715
|
+
};
|
|
11716
|
+
}
|
|
11717
|
+
/**
|
|
11718
|
+
* Whether process `pid` has the database file, or its write-ahead log, open. A name `lsof`
|
|
11719
|
+
* marks ` (deleted)`, as Linux does for a file removed while open, is another file than the
|
|
11720
|
+
* one at the path now and does not count. Names are resolved as the database's is.
|
|
11721
|
+
*/
|
|
11722
|
+
function holdsDatabaseOpen(pid, canonical) {
|
|
11723
|
+
const result = runLsof([
|
|
11724
|
+
"-p",
|
|
11725
|
+
String(pid),
|
|
11726
|
+
"-Fn"
|
|
11727
|
+
]);
|
|
11728
|
+
if (!result.ok) return result;
|
|
11729
|
+
const wanted = /* @__PURE__ */ new Set([canonical, `${canonical}-wal`]);
|
|
11730
|
+
const names = /* @__PURE__ */ new Set([basename(canonical), `${basename(canonical)}-wal`]);
|
|
11731
|
+
return {
|
|
11732
|
+
ok: true,
|
|
11733
|
+
open: result.lines.some((line) => {
|
|
11734
|
+
if (!line.startsWith("n/")) return false;
|
|
11735
|
+
const file = line.slice(1);
|
|
11736
|
+
if (!names.has(basename(file))) return false;
|
|
11737
|
+
return wanted.has(canonicalViewerDbPath(file));
|
|
11738
|
+
})
|
|
11739
|
+
};
|
|
11740
|
+
}
|
|
11741
|
+
/** The database a Viewer reports in its prompt-pack profile, or null when it reports none. */
|
|
11742
|
+
async function reportedDatabase(address, fetchImpl) {
|
|
11743
|
+
try {
|
|
11744
|
+
const response = await fetchImpl(viewerUrl(address, "/api/prompt-pack-profile"), { signal: AbortSignal.timeout(1e3) });
|
|
11745
|
+
if (!response.ok) return null;
|
|
11746
|
+
const payload = await response.json();
|
|
11747
|
+
return typeof payload?.db_path === "string" && payload.db_path ? payload.db_path : null;
|
|
11748
|
+
} catch {
|
|
11749
|
+
return null;
|
|
11750
|
+
}
|
|
11751
|
+
}
|
|
11752
|
+
function lockProof(pid, identity, dbPath) {
|
|
11753
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11754
|
+
return owner?.pid === pid && owner.db_path === canonicalViewerDbPath(dbPath) && owner.started === identity.started && isViewerWriterLockHeld(dbPath);
|
|
11755
|
+
}
|
|
11756
|
+
function refuse(reason) {
|
|
11757
|
+
return {
|
|
11758
|
+
ok: false,
|
|
11759
|
+
reason
|
|
11760
|
+
};
|
|
11761
|
+
}
|
|
11762
|
+
/** The listener and open-file proofs of a Viewer from before the lock; a reason when they fail. */
|
|
11763
|
+
function openDatabaseProof(pid, port, canonical) {
|
|
11764
|
+
const listener = listeningPid(port);
|
|
11765
|
+
if (!listener.ok) return listener.reason;
|
|
11766
|
+
if (listener.pid !== pid) return `it is not the process listening on port ${port}`;
|
|
11767
|
+
const open = holdsDatabaseOpen(pid, canonical);
|
|
11768
|
+
if (!open.ok) return open.reason;
|
|
11769
|
+
return open.open ? null : "it does not have the database open";
|
|
11770
|
+
}
|
|
11771
|
+
/** Why the process is not a codemem Viewer listening at its address, or null when it is. */
|
|
11772
|
+
function viewerProcessFailure(pid, identity, port, platform) {
|
|
11773
|
+
if (!identity) return "its process could not be identified";
|
|
11774
|
+
if (!isLikelyViewerCommand(identity.command)) return "its process does not look like a codemem viewer";
|
|
11775
|
+
if (platform === "win32") return null;
|
|
11776
|
+
const listener = listeningPid(port);
|
|
11777
|
+
if (!listener.ok) return listener.reason;
|
|
11778
|
+
return listener.pid === pid ? null : `it is not the process listening on port ${port}`;
|
|
11779
|
+
}
|
|
11780
|
+
function verified(pid, identity, proof, recheck) {
|
|
11781
|
+
return {
|
|
11782
|
+
ok: true,
|
|
11783
|
+
viewer: {
|
|
11784
|
+
pid,
|
|
11785
|
+
identity,
|
|
11786
|
+
proof,
|
|
11787
|
+
recheck
|
|
11788
|
+
}
|
|
11789
|
+
};
|
|
11790
|
+
}
|
|
11791
|
+
/**
|
|
11792
|
+
* Why a Viewer without the lock cannot be serving this database, or null. Releases
|
|
11793
|
+
* from before the lock cannot read a transitioned store, so for one the lock is the
|
|
11794
|
+
* only proof. A store whose names cannot be read is refused rather than guessed.
|
|
11795
|
+
*/
|
|
11796
|
+
function transitionedStoreRefusal(dbPath) {
|
|
11797
|
+
if (!existsSync(dbPath)) return null;
|
|
11798
|
+
try {
|
|
11799
|
+
if (readDeviceStorageShape(dbPath) === "legacy") return null;
|
|
11800
|
+
return "it does not hold the database's lock, and only a Viewer that holds it can serve this database's storage format";
|
|
11801
|
+
} catch (error) {
|
|
11802
|
+
return `the database's storage format could not be read (${error instanceof Error ? error.message : String(error)})`;
|
|
11803
|
+
}
|
|
11804
|
+
}
|
|
11805
|
+
/** The proof for a Viewer from before the lock: listener, open database, reported database. */
|
|
11806
|
+
async function verifyPreLockViewer(pid, identity, address, canonical, fetchImpl) {
|
|
11807
|
+
const failed = openDatabaseProof(pid, address.port, canonical);
|
|
11808
|
+
if (failed) return refuse(failed);
|
|
11809
|
+
const reported = await reportedDatabase(address, fetchImpl);
|
|
11810
|
+
if (reported === null) return refuse("it did not report which database it serves");
|
|
11811
|
+
if (canonicalViewerDbPath(reported) !== canonical) return refuse("it reports another database");
|
|
11812
|
+
return verified(pid, identity, "open-database", () => {
|
|
11813
|
+
return openDatabaseProof(pid, address.port, canonical) === null;
|
|
11814
|
+
});
|
|
11815
|
+
}
|
|
11816
|
+
/**
|
|
11817
|
+
* Whether the codemem Viewer `pid`, answering at `address`, serves the database at
|
|
11818
|
+
* `dbPath`. Returns what to recheck before each signal, or why it is refused.
|
|
11819
|
+
*/
|
|
11820
|
+
async function verifyViewerForDatabase(pid, address, dbPath, deps = {}) {
|
|
11821
|
+
const identity = (deps.readIdentity ?? readProcessIdentity)(pid);
|
|
11822
|
+
const platform = deps.platform ?? process.platform;
|
|
11823
|
+
const notViewer = viewerProcessFailure(pid, identity, address.port, platform);
|
|
11824
|
+
if (notViewer || !identity) return refuse(notViewer ?? "its process could not be identified");
|
|
11825
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11826
|
+
if (owner?.pid === pid) {
|
|
11827
|
+
if (!lockProof(pid, identity, dbPath)) return refuse("the database's lock record names it with another start time or database, or the lock is not held");
|
|
11828
|
+
return verified(pid, identity, "lock", () => lockProof(pid, identity, dbPath));
|
|
11829
|
+
}
|
|
11830
|
+
if (owner && isViewerWriterLockHeld(dbPath)) return refuse("another process holds the database's lock");
|
|
11831
|
+
const format = transitionedStoreRefusal(dbPath);
|
|
11832
|
+
if (format) return refuse(format);
|
|
11833
|
+
if (platform === "win32") return verified(pid, identity, "unidentifiable-platform", () => true);
|
|
11834
|
+
return verifyPreLockViewer(pid, identity, address, canonicalViewerDbPath(dbPath), deps.fetch ?? fetch);
|
|
11835
|
+
}
|
|
11836
|
+
//#endregion
|
|
11837
|
+
//#region src/commands/serve.ts
|
|
11838
|
+
function extractViewerPid(payload) {
|
|
11839
|
+
if (!payload || typeof payload !== "object") return null;
|
|
11840
|
+
const rawPid = payload.viewer_pid;
|
|
11841
|
+
if (typeof rawPid !== "number" || !Number.isFinite(rawPid) || rawPid <= 0) return null;
|
|
11842
|
+
return Math.trunc(rawPid);
|
|
11843
|
+
}
|
|
11844
|
+
function isLocalHost(host) {
|
|
11845
|
+
const normalized = host.trim().toLowerCase();
|
|
11846
|
+
return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0" || normalized === "::";
|
|
11847
|
+
}
|
|
11848
|
+
function isLoopbackOnlyHost(host) {
|
|
11849
|
+
return isLoopbackHost(host);
|
|
11850
|
+
}
|
|
11851
|
+
function warnIfViewerExposed(host, port) {
|
|
11852
|
+
if (isLoopbackOnlyHost(host)) return;
|
|
11853
|
+
p.log.warn(`Viewer bound to ${host}:${port}. codemem's viewer trust model assumes localhost-only access; do not expose it through a reverse proxy, tunnel, or public bind without adding your own auth layer.`);
|
|
11854
|
+
}
|
|
11855
|
+
function prepareViewerDatabase(dbPath) {
|
|
11856
|
+
return initDatabase(dbPath ?? void 0).path;
|
|
11557
11857
|
}
|
|
11558
11858
|
function pidFilePath(dbPath) {
|
|
11559
11859
|
return join(viewerRuntimeDir(dbPath), "viewer.pid");
|
|
@@ -11655,7 +11955,7 @@ async function respondsLikeCodememViewer(record, fetchImpl = fetch) {
|
|
|
11655
11955
|
}
|
|
11656
11956
|
async function lookupViewerPidFromStats(host, port) {
|
|
11657
11957
|
try {
|
|
11658
|
-
const res = await fetch(viewerUrl({
|
|
11958
|
+
const res = await fetch(viewerUrl$1({
|
|
11659
11959
|
host,
|
|
11660
11960
|
port
|
|
11661
11961
|
}, "/api/stats"), { signal: AbortSignal.timeout(1e3) });
|
|
@@ -11690,22 +11990,89 @@ async function waitForProcessExit(pid, timeoutMs = 3e4) {
|
|
|
11690
11990
|
}
|
|
11691
11991
|
return !isProcessRunning(pid);
|
|
11692
11992
|
}
|
|
11693
|
-
|
|
11993
|
+
/**
|
|
11994
|
+
* Whether `pid` still names the verified process. The proof that chose it runs first and
|
|
11995
|
+
* the identity read last, so nothing is checked between that read and the signal.
|
|
11996
|
+
* "changed" means the pid names another process now: the verified one has exited.
|
|
11997
|
+
*/
|
|
11998
|
+
function confirmVerified(viewer, readIdentity) {
|
|
11999
|
+
const proven = viewer.recheck();
|
|
12000
|
+
const now = readIdentity(viewer.pid);
|
|
12001
|
+
if (now && !sameProcess(now, viewer.identity)) return "changed";
|
|
12002
|
+
if (!proven) return "not-target";
|
|
12003
|
+
return now ? "same" : "unknown";
|
|
12004
|
+
}
|
|
12005
|
+
/**
|
|
12006
|
+
* Stops a verified process: SIGTERM, then after the wait SIGKILL. Each signal is sent only
|
|
12007
|
+
* when the pid still names the process as it was verified and it still passes its proof.
|
|
12008
|
+
* A process that exited during the wait, whose pid may name another process now, is
|
|
12009
|
+
* never signalled again.
|
|
12010
|
+
*/
|
|
12011
|
+
async function terminateVerified(viewer, options = {}) {
|
|
12012
|
+
const readIdentity = options.readIdentity ?? readProcessIdentity;
|
|
12013
|
+
const { pid } = viewer;
|
|
12014
|
+
if (confirmVerified(viewer, readIdentity) !== "same") return {
|
|
12015
|
+
signalled: false,
|
|
12016
|
+
stopped: false
|
|
12017
|
+
};
|
|
11694
12018
|
try {
|
|
11695
12019
|
process.kill(pid, "SIGTERM");
|
|
11696
12020
|
} catch {
|
|
11697
|
-
return
|
|
12021
|
+
return {
|
|
12022
|
+
signalled: true,
|
|
12023
|
+
stopped: true
|
|
12024
|
+
};
|
|
11698
12025
|
}
|
|
11699
|
-
if (await waitForProcessExit(pid,
|
|
12026
|
+
if (await waitForProcessExit(pid, options.gracefulMs ?? 3e4)) return {
|
|
12027
|
+
signalled: true,
|
|
12028
|
+
stopped: true
|
|
12029
|
+
};
|
|
12030
|
+
const confirmation = confirmVerified(viewer, readIdentity);
|
|
12031
|
+
if (confirmation === "changed") return {
|
|
12032
|
+
signalled: true,
|
|
12033
|
+
stopped: true
|
|
12034
|
+
};
|
|
12035
|
+
if (confirmation !== "same") return {
|
|
12036
|
+
signalled: true,
|
|
12037
|
+
stopped: false
|
|
12038
|
+
};
|
|
11700
12039
|
try {
|
|
11701
12040
|
process.kill(pid, "SIGKILL");
|
|
11702
12041
|
} catch {
|
|
11703
|
-
return
|
|
12042
|
+
return {
|
|
12043
|
+
signalled: true,
|
|
12044
|
+
stopped: true
|
|
12045
|
+
};
|
|
12046
|
+
}
|
|
12047
|
+
return {
|
|
12048
|
+
signalled: true,
|
|
12049
|
+
stopped: await waitForProcessExit(pid, options.forceMs ?? 5e3)
|
|
12050
|
+
};
|
|
12051
|
+
}
|
|
12052
|
+
/**
|
|
12053
|
+
* Stops a process its caller has just checked, such as a maintenance worker. Its identity
|
|
12054
|
+
* is read once before SIGTERM and must match again before SIGKILL; when it cannot be read,
|
|
12055
|
+
* SIGTERM is the only signal.
|
|
12056
|
+
*/
|
|
12057
|
+
async function terminateProcessPid(pid, options = {}) {
|
|
12058
|
+
const identity = (options.readIdentity ?? readProcessIdentity)(pid);
|
|
12059
|
+
if (!identity) {
|
|
12060
|
+
try {
|
|
12061
|
+
process.kill(pid, "SIGTERM");
|
|
12062
|
+
} catch {
|
|
12063
|
+
return true;
|
|
12064
|
+
}
|
|
12065
|
+
return waitForProcessExit(pid, options.gracefulMs ?? 3e4);
|
|
11704
12066
|
}
|
|
11705
|
-
return
|
|
12067
|
+
return (await terminateVerified({
|
|
12068
|
+
pid,
|
|
12069
|
+
identity,
|
|
12070
|
+
recheck: () => true
|
|
12071
|
+
}, options)).stopped;
|
|
11706
12072
|
}
|
|
11707
|
-
|
|
11708
|
-
|
|
12073
|
+
/** Stops a Viewer that `verifyViewerForDatabase` verified. */
|
|
12074
|
+
async function terminateVerifiedViewer(viewer, options = {}) {
|
|
12075
|
+
return terminateVerified(viewer, options);
|
|
11709
12076
|
}
|
|
11710
12077
|
/**
|
|
11711
12078
|
* Stops a leftover maintenance worker for this database. Reads the current PID
|
|
@@ -11752,42 +12119,70 @@ var viewerLockDependencies = {
|
|
|
11752
12119
|
}),
|
|
11753
12120
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
11754
12121
|
};
|
|
11755
|
-
|
|
11756
|
-
|
|
11757
|
-
|
|
11758
|
-
|
|
11759
|
-
|
|
11760
|
-
|
|
11761
|
-
|
|
11762
|
-
|
|
11763
|
-
|
|
11764
|
-
|
|
11765
|
-
|
|
11766
|
-
|
|
11767
|
-
|
|
11768
|
-
|
|
11769
|
-
}
|
|
11770
|
-
|
|
11771
|
-
|
|
11772
|
-
|
|
11773
|
-
|
|
11774
|
-
|
|
11775
|
-
|
|
12122
|
+
/**
|
|
12123
|
+
* The codemem Viewer to consider at `target`: on macOS and Linux the process listening on
|
|
12124
|
+
* the port, else the pid its answer names, which verification then refuses because it is
|
|
12125
|
+
* not the listener. Null when no codemem Viewer is there, so that an unrelated listener is
|
|
12126
|
+
* not reported.
|
|
12127
|
+
*/
|
|
12128
|
+
async function viewerCandidateAt(target, options) {
|
|
12129
|
+
if (!isLocalHost(target.host)) return null;
|
|
12130
|
+
const statsPid = await lookupViewerPidFromStats(target.host, target.port);
|
|
12131
|
+
if ((options.platform ?? process.platform) === "win32") return statsPid ? { pid: statsPid } : null;
|
|
12132
|
+
const listener = listeningPid(target.port);
|
|
12133
|
+
const pid = (listener.ok ? listener.pid : null) ?? statsPid;
|
|
12134
|
+
if (!pid) return null;
|
|
12135
|
+
const command = (options.readIdentity ?? readProcessIdentity)(pid)?.command;
|
|
12136
|
+
return command && isLikelyViewerCommand(command) ? { pid } : null;
|
|
12137
|
+
}
|
|
12138
|
+
/** Verifies that Viewer `pid` at `address` serves this database, then stops it. */
|
|
12139
|
+
async function stopVerifiedViewer(pid, address, dbPath, options) {
|
|
12140
|
+
const verification = await verifyViewerForDatabase(pid, address, dbPath, options);
|
|
12141
|
+
if (!verification.ok) return { refused: {
|
|
12142
|
+
pid,
|
|
12143
|
+
...address,
|
|
12144
|
+
reason: verification.reason
|
|
12145
|
+
} };
|
|
12146
|
+
const termination = await terminateVerifiedViewer(verification.viewer, options);
|
|
12147
|
+
if (!termination.signalled) return { refused: {
|
|
12148
|
+
pid,
|
|
12149
|
+
...address,
|
|
12150
|
+
reason: "its process changed or stopped serving the database before it could be signalled"
|
|
12151
|
+
} };
|
|
11776
12152
|
return {
|
|
11777
|
-
stopped:
|
|
11778
|
-
pid
|
|
12153
|
+
stopped: termination.stopped,
|
|
12154
|
+
pid
|
|
11779
12155
|
};
|
|
11780
12156
|
}
|
|
11781
|
-
/**
|
|
11782
|
-
async function
|
|
11783
|
-
|
|
11784
|
-
|
|
11785
|
-
|
|
11786
|
-
|
|
11787
|
-
|
|
12157
|
+
/** Tries the Viewers this database's PID records name; the first stopped, or the first refusal. */
|
|
12158
|
+
async function stopRecordedViewers(dbPath, options) {
|
|
12159
|
+
let refusal = null;
|
|
12160
|
+
for (const { path, record } of readViewerPidRecords(dbPath)) {
|
|
12161
|
+
if (!isLocalHost(record.host) || !await respondsLikeCodememViewer(record)) continue;
|
|
12162
|
+
const attempt = await stopVerifiedViewer(record.pid, record, dbPath, options);
|
|
12163
|
+
if ("refused" in attempt) {
|
|
12164
|
+
refusal ??= attempt;
|
|
12165
|
+
continue;
|
|
12166
|
+
}
|
|
12167
|
+
if (attempt.stopped) removeFile(path);
|
|
12168
|
+
return attempt;
|
|
12169
|
+
}
|
|
12170
|
+
return refusal;
|
|
12171
|
+
}
|
|
12172
|
+
async function stopExistingViewer(dbPath, target, options = {}) {
|
|
12173
|
+
const candidate = await viewerCandidateAt(target, options);
|
|
12174
|
+
const atPort = candidate ? await stopVerifiedViewer(candidate.pid, target, dbPath, options) : null;
|
|
12175
|
+
if (atPort && !("refused" in atPort)) {
|
|
12176
|
+
if (atPort.stopped) removeStoppedViewerPidRecords(dbPath, atPort.pid);
|
|
12177
|
+
return atPort;
|
|
12178
|
+
}
|
|
12179
|
+
const recorded = await stopRecordedViewers(dbPath, options);
|
|
12180
|
+
if (recorded && !("refused" in recorded)) return recorded;
|
|
12181
|
+
const refusal = atPort ?? recorded;
|
|
11788
12182
|
return {
|
|
11789
|
-
stopped:
|
|
11790
|
-
pid:
|
|
12183
|
+
stopped: false,
|
|
12184
|
+
pid: null,
|
|
12185
|
+
...refusal && "refused" in refusal ? { refused: refusal.refused } : {}
|
|
11791
12186
|
};
|
|
11792
12187
|
}
|
|
11793
12188
|
function removeFile(path) {
|
|
@@ -12314,9 +12709,55 @@ async function takeOverViewerRuntime(dbPath, target) {
|
|
|
12314
12709
|
})) p.log.warn("Existing maintenance worker is not trusted or did not stop; starting viewer anyway");
|
|
12315
12710
|
return true;
|
|
12316
12711
|
}
|
|
12712
|
+
/**
|
|
12713
|
+
* Open the Viewer's store. When sqlite-vec cannot load, the Viewer starts with embeddings
|
|
12714
|
+
* disabled. The Viewer answers requests while packs are built, so its store assembles
|
|
12715
|
+
* packs in a worker thread.
|
|
12716
|
+
*/
|
|
12717
|
+
async function openViewerStore(dbPath, server) {
|
|
12718
|
+
let store;
|
|
12719
|
+
try {
|
|
12720
|
+
store = server.getStore();
|
|
12721
|
+
} catch (err) {
|
|
12722
|
+
if (isEmbeddingDisabled() || !isSqliteVecLoadFailure(err)) throw err;
|
|
12723
|
+
p.log.warn("sqlite-vec failed to load; retrying viewer startup with embeddings disabled");
|
|
12724
|
+
for (const line of sqliteVecFailureDiagnostics(err, dbPath)) p.log.warn(`sqlite-vec diagnostic: ${line}`);
|
|
12725
|
+
process.env.CODEMEM_EMBEDDING_DISABLED = "1";
|
|
12726
|
+
await server.closeStoreAsync();
|
|
12727
|
+
store = server.getStore();
|
|
12728
|
+
p.log.warn("Embeddings disabled for this viewer process; raw-event ingestion remains active.");
|
|
12729
|
+
}
|
|
12730
|
+
store.enablePackWorker();
|
|
12731
|
+
recordConfiguredCoordinatorHistory(store.db, readCoordinatorSyncConfig());
|
|
12732
|
+
return store;
|
|
12733
|
+
}
|
|
12734
|
+
/**
|
|
12735
|
+
* The sync listener is network-facing, so it runs on the guarded server. Its
|
|
12736
|
+
* routes and any direct Noise streams share one request limiter.
|
|
12737
|
+
*/
|
|
12738
|
+
function syncListenerOptions(serverModule, appOpts, syncConfig) {
|
|
12739
|
+
const limiter = serverModule.createSyncListenerLimiter();
|
|
12740
|
+
const syncApp = serverModule.createSyncApp({
|
|
12741
|
+
...appOpts,
|
|
12742
|
+
syncRequestRateLimit: { limiter }
|
|
12743
|
+
});
|
|
12744
|
+
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
12745
|
+
return {
|
|
12746
|
+
fetch: syncApp.fetch,
|
|
12747
|
+
hostname: syncConfig.syncHost,
|
|
12748
|
+
port: syncConfig.syncPort,
|
|
12749
|
+
createServer: serverModule.createGuardedSyncServer({
|
|
12750
|
+
limiter,
|
|
12751
|
+
directNoise: {
|
|
12752
|
+
storeFactory: appOpts.storeFactory,
|
|
12753
|
+
keysDir
|
|
12754
|
+
}
|
|
12755
|
+
})
|
|
12756
|
+
};
|
|
12757
|
+
}
|
|
12317
12758
|
async function startForegroundViewer(invocation) {
|
|
12318
12759
|
const serverModule = await import("@codemem/server");
|
|
12319
|
-
const { createApp,
|
|
12760
|
+
const { createApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
|
|
12320
12761
|
const createRawEventInbox = createViewerRawEventInbox;
|
|
12321
12762
|
const coordinatorMaintenanceDependencies = createServeCoordinatorMaintenanceDependencies(serverModule);
|
|
12322
12763
|
const { serve } = await import("@hono/node-server");
|
|
@@ -12327,18 +12768,10 @@ async function startForegroundViewer(invocation) {
|
|
|
12327
12768
|
if (!await takeOverViewerRuntime(dbPath, invocation)) return;
|
|
12328
12769
|
const preparedDb = prepareViewerDatabase(invocation.dbPath);
|
|
12329
12770
|
const observer = new ObserverClient();
|
|
12330
|
-
|
|
12331
|
-
|
|
12332
|
-
|
|
12333
|
-
}
|
|
12334
|
-
if (isEmbeddingDisabled() || !isSqliteVecLoadFailure(err)) throw err;
|
|
12335
|
-
p.log.warn("sqlite-vec failed to load; retrying viewer startup with embeddings disabled");
|
|
12336
|
-
for (const line of sqliteVecFailureDiagnostics(err, resolveDbPath(invocation.dbPath ?? void 0))) p.log.warn(`sqlite-vec diagnostic: ${line}`);
|
|
12337
|
-
process.env.CODEMEM_EMBEDDING_DISABLED = "1";
|
|
12338
|
-
await closeStoreAsync();
|
|
12339
|
-
store = getStore();
|
|
12340
|
-
p.log.warn("Embeddings disabled for this viewer process; raw-event ingestion remains active.");
|
|
12341
|
-
}
|
|
12771
|
+
const store = await openViewerStore(dbPath, {
|
|
12772
|
+
getStore,
|
|
12773
|
+
closeStoreAsync
|
|
12774
|
+
});
|
|
12342
12775
|
const rawEventProcessing = startRawEventProcessing(dbPath, store, observer, createRawEventInbox);
|
|
12343
12776
|
const syncAbort = new AbortController();
|
|
12344
12777
|
const config = invocation.configPath ? readCodememConfigFileAtPath(invocation.configPath) : readCodememConfigFile();
|
|
@@ -12375,11 +12808,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12375
12808
|
let syncServer = null;
|
|
12376
12809
|
let syncListenerReady = false;
|
|
12377
12810
|
if (syncEnabled) {
|
|
12378
|
-
syncServer = serve({
|
|
12379
|
-
fetch: createSyncApp(appOpts).fetch,
|
|
12380
|
-
hostname: syncConfig.syncHost,
|
|
12381
|
-
port: syncConfig.syncPort
|
|
12382
|
-
}, (info) => {
|
|
12811
|
+
syncServer = serve(syncListenerOptions(serverModule, appOpts, syncConfig), (info) => {
|
|
12383
12812
|
syncListenerReady = true;
|
|
12384
12813
|
p.log.step(`Sync protocol listening on http://${info.address}:${info.port}`);
|
|
12385
12814
|
});
|
|
@@ -12544,6 +12973,10 @@ async function stopBeforeStart(invocation, dbPath, stop) {
|
|
|
12544
12973
|
host: invocation.host,
|
|
12545
12974
|
port: invocation.port
|
|
12546
12975
|
});
|
|
12976
|
+
if (result.refused) {
|
|
12977
|
+
reportRefusedViewer(dbPath, result.refused);
|
|
12978
|
+
return false;
|
|
12979
|
+
}
|
|
12547
12980
|
if (result.pid && !result.stopped) {
|
|
12548
12981
|
p.intro("codemem viewer");
|
|
12549
12982
|
p.log.error(`Viewer is still shutting down (pid ${result.pid})`);
|
|
@@ -12566,6 +12999,13 @@ async function stopBeforeStart(invocation, dbPath, stop) {
|
|
|
12566
12999
|
}
|
|
12567
13000
|
return waitForStoppedViewer(invocation, dbPath);
|
|
12568
13001
|
}
|
|
13002
|
+
/** A Viewer that answered but was not shown to serve this database. Nothing was signalled. */
|
|
13003
|
+
function reportRefusedViewer(dbPath, viewer) {
|
|
13004
|
+
p.intro("codemem viewer");
|
|
13005
|
+
p.log.error(`The viewer at ${viewer.host}:${viewer.port} (pid ${viewer.pid}) could not be confirmed to serve ${dbPath}: ${viewer.reason}. Nothing was stopped.`);
|
|
13006
|
+
p.log.info("It may serve another database, or come from a release that does not record its database. Pass the --db-path and --port it was started with, or stop it yourself after checking it.");
|
|
13007
|
+
process.exitCode = 1;
|
|
13008
|
+
}
|
|
12569
13009
|
/**
|
|
12570
13010
|
* After a stop that found no Viewer to stop: whether something still holds the
|
|
12571
13011
|
* database. The owner record is only reported; nothing is signalled because of it.
|
|
@@ -14810,11 +15250,230 @@ var setupCommand = new Command("setup").configureHelp(helpStyle).description("In
|
|
|
14810
15250
|
runSetup(opts);
|
|
14811
15251
|
});
|
|
14812
15252
|
//#endregion
|
|
14813
|
-
//#region src/commands/sync-
|
|
14814
|
-
function
|
|
14815
|
-
|
|
14816
|
-
|
|
14817
|
-
|
|
15253
|
+
//#region src/commands/sync-bootstrap.ts
|
|
15254
|
+
function reportError(opts, code, message, exitCode = 1) {
|
|
15255
|
+
if (opts.json) {
|
|
15256
|
+
emitJsonError(code, message, exitCode);
|
|
15257
|
+
return;
|
|
15258
|
+
}
|
|
15259
|
+
p.log.error(message);
|
|
15260
|
+
process.exitCode = exitCode;
|
|
15261
|
+
}
|
|
15262
|
+
/** The pinned peer to bootstrap from, or null after reporting why it can't be used. */
|
|
15263
|
+
function bootstrapPeer(store, peerDeviceId, opts) {
|
|
15264
|
+
const peer = drizzle(store.db, { schema }).select().from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get();
|
|
15265
|
+
if (!peer) {
|
|
15266
|
+
reportError(opts, "peer_not_found", `Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15267
|
+
return null;
|
|
15268
|
+
}
|
|
15269
|
+
if (!peer.pinned_fingerprint) {
|
|
15270
|
+
reportError(opts, "peer_not_pinned", `Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15271
|
+
return null;
|
|
15272
|
+
}
|
|
15273
|
+
return peer;
|
|
15274
|
+
}
|
|
15275
|
+
/**
|
|
15276
|
+
* Once direct Noise is on, a peer pinned by fingerprint alone can't be
|
|
15277
|
+
* reached. Say how to fix it before any request, including a grant's, leaves.
|
|
15278
|
+
*/
|
|
15279
|
+
function peerKeyReady(store, peer, opts, transport) {
|
|
15280
|
+
if (!peerTransportBlocker(store.db, peer.peer_device_id, transport.directNoise)) return true;
|
|
15281
|
+
reportError(opts, "peer_key_missing", `Peer ${peer.name || peer.peer_device_id} has no saved public key, so codemem can't open an encrypted connection to it. On that device, run \`codemem sync pair --payload-only\` and save the output. Then run \`codemem sync pair --accept-file <file>\` here. The payload's public key must match the pinned fingerprint.`);
|
|
15282
|
+
return false;
|
|
15283
|
+
}
|
|
15284
|
+
function localStateIsClean(store, opts) {
|
|
15285
|
+
if (opts.force) return true;
|
|
15286
|
+
const dirty = hasUnsyncedSharedMemoryChanges(store.db);
|
|
15287
|
+
if (!dirty.dirty) return true;
|
|
15288
|
+
reportError(opts, "local_unsynced_changes", `${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15289
|
+
return false;
|
|
15290
|
+
}
|
|
15291
|
+
function resetBoundary(payload) {
|
|
15292
|
+
const reset = payload.sync_reset;
|
|
15293
|
+
if (!reset || typeof reset.generation !== "number" || typeof reset.snapshot_id !== "string") return null;
|
|
15294
|
+
return {
|
|
15295
|
+
generation: reset.generation,
|
|
15296
|
+
snapshot_id: reset.snapshot_id,
|
|
15297
|
+
baseline_cursor: typeof reset.baseline_cursor === "string" ? reset.baseline_cursor : null
|
|
15298
|
+
};
|
|
15299
|
+
}
|
|
15300
|
+
/** Asks one address for its status. Returns the reset boundary or why the address failed. */
|
|
15301
|
+
async function statusAt(context, peer, baseUrl) {
|
|
15302
|
+
const statusUrl = `${baseUrl}/v1/status`;
|
|
15303
|
+
const headers = buildDirectPeerAuthHeaders({
|
|
15304
|
+
deviceId: context.deviceId,
|
|
15305
|
+
recipientId: context.peerDeviceId,
|
|
15306
|
+
dbPath: context.store.dbPath,
|
|
15307
|
+
method: "GET",
|
|
15308
|
+
url: statusUrl,
|
|
15309
|
+
bodyBytes: Buffer.alloc(0),
|
|
15310
|
+
bootstrapGrantId: context.opts.bootstrapGrant,
|
|
15311
|
+
keysDir: context.keysDir
|
|
15312
|
+
});
|
|
15313
|
+
try {
|
|
15314
|
+
const [code, payload] = await context.execute("GET", statusUrl, {
|
|
15315
|
+
operation: "status",
|
|
15316
|
+
headers
|
|
15317
|
+
});
|
|
15318
|
+
if (code !== 200 || !payload) return `status ${code}`;
|
|
15319
|
+
if (payload.fingerprint !== peer.pinned_fingerprint) return "fingerprint mismatch";
|
|
15320
|
+
return resetBoundary(payload) ?? "missing sync_reset boundary";
|
|
15321
|
+
} catch (err) {
|
|
15322
|
+
return err instanceof Error ? err.message : String(err);
|
|
15323
|
+
}
|
|
15324
|
+
}
|
|
15325
|
+
async function findBoundary(context, peer, addresses) {
|
|
15326
|
+
const addressResults = [];
|
|
15327
|
+
for (const address of addresses) {
|
|
15328
|
+
const baseUrl = buildBaseUrl(address);
|
|
15329
|
+
if (!baseUrl) continue;
|
|
15330
|
+
const outcome = await statusAt(context, peer, baseUrl);
|
|
15331
|
+
if (typeof outcome === "string") {
|
|
15332
|
+
addressResults.push({
|
|
15333
|
+
address: baseUrl,
|
|
15334
|
+
result: outcome
|
|
15335
|
+
});
|
|
15336
|
+
continue;
|
|
15337
|
+
}
|
|
15338
|
+
addressResults.push({
|
|
15339
|
+
address: baseUrl,
|
|
15340
|
+
result: "ok"
|
|
15341
|
+
});
|
|
15342
|
+
return {
|
|
15343
|
+
boundary: outcome,
|
|
15344
|
+
baseUrl,
|
|
15345
|
+
addressResults
|
|
15346
|
+
};
|
|
15347
|
+
}
|
|
15348
|
+
return {
|
|
15349
|
+
boundary: null,
|
|
15350
|
+
baseUrl: "",
|
|
15351
|
+
addressResults
|
|
15352
|
+
};
|
|
15353
|
+
}
|
|
15354
|
+
function reportUnreachable(opts, addressResults) {
|
|
15355
|
+
const summary = addressResults.map((r) => `${r.address}: ${r.result}`).join("; ");
|
|
15356
|
+
const detail = summary ? `no reachable peer with valid reset boundary. Tried: ${summary}` : "peer unreachable or missing reset boundary";
|
|
15357
|
+
if (opts.json) console.log(JSON.stringify({
|
|
15358
|
+
ok: false,
|
|
15359
|
+
error: detail,
|
|
15360
|
+
addresses: addressResults
|
|
15361
|
+
}));
|
|
15362
|
+
else p.log.error(detail);
|
|
15363
|
+
process.exitCode = 1;
|
|
15364
|
+
}
|
|
15365
|
+
function reportApplied(opts, result) {
|
|
15366
|
+
if (opts.json) {
|
|
15367
|
+
const { ok, applied, deleted } = result;
|
|
15368
|
+
console.log(JSON.stringify({
|
|
15369
|
+
ok,
|
|
15370
|
+
applied,
|
|
15371
|
+
deleted,
|
|
15372
|
+
error: result.error ?? null
|
|
15373
|
+
}));
|
|
15374
|
+
} else {
|
|
15375
|
+
if (result.ok) p.log.success(`Applied ${result.applied} memories (removed ${result.deleted} stale).`);
|
|
15376
|
+
else p.log.error(result.error || "Bootstrap apply failed.");
|
|
15377
|
+
p.outro(result.ok ? "Bootstrap complete" : "Bootstrap failed");
|
|
15378
|
+
}
|
|
15379
|
+
if (!result.ok) process.exitCode = 1;
|
|
15380
|
+
}
|
|
15381
|
+
async function copyFromPeer(context, peer, boundary, baseUrl) {
|
|
15382
|
+
const { opts, store, peerDeviceId } = context;
|
|
15383
|
+
if (!opts.json) {
|
|
15384
|
+
p.intro("codemem sync bootstrap");
|
|
15385
|
+
p.log.step(`Bootstrapping from ${peer.name || peerDeviceId}...`);
|
|
15386
|
+
}
|
|
15387
|
+
const resetInfo = {
|
|
15388
|
+
...boundary,
|
|
15389
|
+
retained_floor_cursor: null,
|
|
15390
|
+
reset_required: true,
|
|
15391
|
+
reason: "initial_bootstrap"
|
|
15392
|
+
};
|
|
15393
|
+
const { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, context.deviceId, {
|
|
15394
|
+
keysDir: context.keysDir,
|
|
15395
|
+
dbPath: store.dbPath,
|
|
15396
|
+
bootstrapGrantId: opts.bootstrapGrant,
|
|
15397
|
+
recipientId: peerDeviceId,
|
|
15398
|
+
pageSize: Math.max(1, Number.parseInt(opts.pageSize, 10) || 2e3),
|
|
15399
|
+
requestExecutor: context.execute
|
|
15400
|
+
});
|
|
15401
|
+
reportApplied(opts, applyBootstrapSnapshot(store.db, peerDeviceId, items, resetInfo, store.scanner));
|
|
15402
|
+
}
|
|
15403
|
+
/**
|
|
15404
|
+
* Every request goes through the shared transport policy. A bootstrap grant
|
|
15405
|
+
* rides along so a noise_required seed can pin this device before Noise.
|
|
15406
|
+
*/
|
|
15407
|
+
function bootstrapExecutor(store, ids, opts, transport) {
|
|
15408
|
+
const grant = opts.bootstrapGrant?.trim();
|
|
15409
|
+
return peerTransportExecutor({
|
|
15410
|
+
db: store.db,
|
|
15411
|
+
peerDeviceId: ids.peerDeviceId,
|
|
15412
|
+
localDeviceId: ids.deviceId,
|
|
15413
|
+
keysDir: opts.keysDir,
|
|
15414
|
+
dbPath: store.dbPath,
|
|
15415
|
+
bootstrapGrantId: grant || void 0,
|
|
15416
|
+
...transport.directNoise
|
|
15417
|
+
});
|
|
15418
|
+
}
|
|
15419
|
+
async function bootstrapStore(store, peerDeviceId, opts, transport) {
|
|
15420
|
+
const peer = bootstrapPeer(store, peerDeviceId, opts);
|
|
15421
|
+
if (!peer || !peerKeyReady(store, peer, opts, transport)) return;
|
|
15422
|
+
if (!localStateIsClean(store, opts)) return;
|
|
15423
|
+
const keysDir = opts.keysDir ?? void 0;
|
|
15424
|
+
const [deviceId] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15425
|
+
const addresses = JSON.parse(String(peer.addresses_json ?? "[]"));
|
|
15426
|
+
if (!addresses.length) {
|
|
15427
|
+
reportError(opts, "no_peer_addresses", "Peer has no known addresses. Run a sync first or add addresses.");
|
|
15428
|
+
return;
|
|
15429
|
+
}
|
|
15430
|
+
const context = {
|
|
15431
|
+
store,
|
|
15432
|
+
opts,
|
|
15433
|
+
peerDeviceId,
|
|
15434
|
+
deviceId,
|
|
15435
|
+
keysDir,
|
|
15436
|
+
execute: bootstrapExecutor(store, {
|
|
15437
|
+
peerDeviceId,
|
|
15438
|
+
deviceId
|
|
15439
|
+
}, opts, transport)
|
|
15440
|
+
};
|
|
15441
|
+
const found = await findBoundary(context, peer, addresses);
|
|
15442
|
+
if (!found.boundary || !found.baseUrl) {
|
|
15443
|
+
reportUnreachable(opts, found.addressResults);
|
|
15444
|
+
return;
|
|
15445
|
+
}
|
|
15446
|
+
await copyFromPeer(context, peer, found.boundary, found.baseUrl);
|
|
15447
|
+
}
|
|
15448
|
+
async function runSyncBootstrap(peerArg, opts, transport = {}) {
|
|
15449
|
+
const peerDeviceId = (peerArg || opts.peer || "").trim();
|
|
15450
|
+
if (!peerDeviceId) {
|
|
15451
|
+
reportError(opts, "usage_error", "missing required argument: <peer-device-id>", 2);
|
|
15452
|
+
return;
|
|
15453
|
+
}
|
|
15454
|
+
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15455
|
+
try {
|
|
15456
|
+
await bootstrapStore(store, peerDeviceId, opts, transport);
|
|
15457
|
+
} catch (error) {
|
|
15458
|
+
reportError(opts, error instanceof DeviceIdentityError ? error.code : "bootstrap_failed", error instanceof Error ? error.message : "Bootstrap failed");
|
|
15459
|
+
} finally {
|
|
15460
|
+
store.close();
|
|
15461
|
+
}
|
|
15462
|
+
}
|
|
15463
|
+
function buildSyncBootstrapCommand() {
|
|
15464
|
+
const command = new Command("bootstrap").configureHelp(helpStyle).description("Copy existing memories from a peer").argument("[peer-device-id]", "peer device ID to bootstrap from").option("--bootstrap-grant <grant-id>", "bootstrap grant id for seed-authorized bootstrap").option("--page-size <n>", "items per snapshot page (default: 2000)", "2000").option("--keys-dir <path>", "keys directory").option("--force", "skip dirty-local-state safety check");
|
|
15465
|
+
addDbOption(command);
|
|
15466
|
+
addJsonOption(command);
|
|
15467
|
+
command.addOption(new Option("--peer <device-id>", "peer device ID").hideHelp());
|
|
15468
|
+
command.action((peerArg, opts) => runSyncBootstrap(peerArg, opts));
|
|
15469
|
+
return command;
|
|
15470
|
+
}
|
|
15471
|
+
//#endregion
|
|
15472
|
+
//#region src/commands/sync-helpers.ts
|
|
15473
|
+
function formatSyncAttempt(row) {
|
|
15474
|
+
const status = row.ok ? "ok" : "error";
|
|
15475
|
+
const error = String(row.error || "");
|
|
15476
|
+
const suffix = error ? ` | ${error}` : "";
|
|
14818
15477
|
return `${row.peer_device_id}|${status}|in=${row.ops_in}|out=${row.ops_out}|${row.finished_at ?? ""}${suffix}`;
|
|
14819
15478
|
}
|
|
14820
15479
|
function buildServeLifecycleArgs(action, opts, scriptPath, execArgv = []) {
|
|
@@ -14849,6 +15508,244 @@ function collectAdvertiseAddresses(explicitAddress, configuredHost, port, interf
|
|
|
14849
15508
|
return [...new Set(addresses)];
|
|
14850
15509
|
}
|
|
14851
15510
|
//#endregion
|
|
15511
|
+
//#region src/commands/sync-migration.ts
|
|
15512
|
+
function reportText(report) {
|
|
15513
|
+
switch (report.state) {
|
|
15514
|
+
case "off": return "Project migration reporting is off.";
|
|
15515
|
+
case "not_applicable": return "This device uses basic peer sync. No Project migration is needed.";
|
|
15516
|
+
case "waiting_for_coordinator": return "Coordinator settings are missing. Existing sharing stays in effect.";
|
|
15517
|
+
case "local_report": {
|
|
15518
|
+
const counts = report.projects;
|
|
15519
|
+
return `${counts ? `Project candidates: ${counts.candidate_projects}. Projects in multiple setups: ${counts.multiple_sources}. Locally authored rows in those setups: ${counts.own_source_rows}.` : "The local Project inventory is unavailable."}\nLocal filter evidence: ${report.local_filters}. Other devices have not been checked.\n${report.maintenance_window}\n${report.storage_fence}`;
|
|
15520
|
+
}
|
|
15521
|
+
}
|
|
15522
|
+
}
|
|
15523
|
+
function migrationStatus(opts) {
|
|
15524
|
+
try {
|
|
15525
|
+
const config = readCodememConfigFileForMutation(opts.config ?? getCodememConfigPath());
|
|
15526
|
+
if (config.status !== "valid" && (config.status !== "missing" || opts.config || process.env.CODEMEM_CONFIG)) throw new Error("migration_config_unavailable");
|
|
15527
|
+
const db = connectReadOnly(resolveDbPath(resolveDbOpt(opts)));
|
|
15528
|
+
try {
|
|
15529
|
+
const report = readLocalProjectMigrationReport(db, config.status === "valid" ? config.data : {});
|
|
15530
|
+
if (opts.json) process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
15531
|
+
else p.log.info(reportText(report));
|
|
15532
|
+
} finally {
|
|
15533
|
+
db.close();
|
|
15534
|
+
}
|
|
15535
|
+
} catch {
|
|
15536
|
+
const message = "Could not read the migration report. Check the database and configuration paths.";
|
|
15537
|
+
if (opts.json) emitJsonError("migration_report_unavailable", message);
|
|
15538
|
+
else {
|
|
15539
|
+
p.log.error(message);
|
|
15540
|
+
process.exitCode = 1;
|
|
15541
|
+
}
|
|
15542
|
+
}
|
|
15543
|
+
}
|
|
15544
|
+
function buildSyncMigrationCommand() {
|
|
15545
|
+
const status = new Command("status").configureHelp(helpStyle).description("Report local Project sharing data without changing access");
|
|
15546
|
+
addDbOption(status);
|
|
15547
|
+
addConfigOption(status);
|
|
15548
|
+
addJsonOption(status);
|
|
15549
|
+
status.action(migrationStatus);
|
|
15550
|
+
return new Command("migration").configureHelp(helpStyle).description("Inspect the Project sharing migration").addCommand(status);
|
|
15551
|
+
}
|
|
15552
|
+
//#endregion
|
|
15553
|
+
//#region src/commands/sync-pair.ts
|
|
15554
|
+
var PAIR_FILTERS_REFUSED = "These filters would send this pairing Projects it does not receive now. Only an administrator's device can do that. This device can send less. Nothing was changed.";
|
|
15555
|
+
var STALE_PIN = "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.";
|
|
15556
|
+
/** A refusal with its JSON error code. Usage errors exit 2 in JSON mode, like other commands. */
|
|
15557
|
+
var PairRefusal = class extends Error {
|
|
15558
|
+
code;
|
|
15559
|
+
jsonExitCode;
|
|
15560
|
+
constructor(code, message, jsonExitCode = 1) {
|
|
15561
|
+
super(message);
|
|
15562
|
+
this.code = code;
|
|
15563
|
+
this.jsonExitCode = jsonExitCode;
|
|
15564
|
+
}
|
|
15565
|
+
};
|
|
15566
|
+
var usage = (message) => new PairRefusal("usage_error", message, 2);
|
|
15567
|
+
function reportFailure$1(opts, error) {
|
|
15568
|
+
const code = error instanceof PairRefusal || error instanceof DeviceIdentityError ? error.code : "pairing_failed";
|
|
15569
|
+
const message = error instanceof Error ? error.message : "Pairing failed";
|
|
15570
|
+
const jsonExitCode = error instanceof PairRefusal ? error.jsonExitCode : 1;
|
|
15571
|
+
if (opts.json) {
|
|
15572
|
+
emitJsonError(code, message, jsonExitCode);
|
|
15573
|
+
return;
|
|
15574
|
+
}
|
|
15575
|
+
p.log.error(message);
|
|
15576
|
+
process.exitCode = 1;
|
|
15577
|
+
}
|
|
15578
|
+
/** The filters the pair flags ask for, or null when no filter flag was given. */
|
|
15579
|
+
function pairFilterChange(opts) {
|
|
15580
|
+
if (opts.default) return {
|
|
15581
|
+
include: null,
|
|
15582
|
+
exclude: null
|
|
15583
|
+
};
|
|
15584
|
+
if (opts.all) return {
|
|
15585
|
+
include: [],
|
|
15586
|
+
exclude: []
|
|
15587
|
+
};
|
|
15588
|
+
if (!opts.include && !opts.exclude) return null;
|
|
15589
|
+
return {
|
|
15590
|
+
include: parseProjectList(opts.include),
|
|
15591
|
+
exclude: parseProjectList(opts.exclude)
|
|
15592
|
+
};
|
|
15593
|
+
}
|
|
15594
|
+
function checkModeFlags(opts) {
|
|
15595
|
+
const acceptRequested = opts.accept != null || opts.acceptFile != null;
|
|
15596
|
+
if (opts.payloadOnly && acceptRequested) throw usage("--payload-only cannot be combined with --accept or --accept-file");
|
|
15597
|
+
if (opts.accept && opts.acceptFile) throw usage("Use only one of --accept or --accept-file");
|
|
15598
|
+
}
|
|
15599
|
+
function readStdin() {
|
|
15600
|
+
return new Promise((resolve, reject) => {
|
|
15601
|
+
let text = "";
|
|
15602
|
+
process.stdin.setEncoding("utf8");
|
|
15603
|
+
process.stdin.on("data", (chunk) => {
|
|
15604
|
+
text += chunk;
|
|
15605
|
+
});
|
|
15606
|
+
process.stdin.on("end", () => resolve(text));
|
|
15607
|
+
process.stdin.on("error", reject);
|
|
15608
|
+
});
|
|
15609
|
+
}
|
|
15610
|
+
async function readAcceptText(opts) {
|
|
15611
|
+
if (!opts.acceptFile) return opts.accept;
|
|
15612
|
+
try {
|
|
15613
|
+
return opts.acceptFile === "-" ? await readStdin() : readFileSync(opts.acceptFile, "utf8");
|
|
15614
|
+
} catch (error) {
|
|
15615
|
+
const detail = error instanceof Error ? `: ${error.message}` : "";
|
|
15616
|
+
throw new PairRefusal("read_error", `Failed to read pairing payload from ${opts.acceptFile}${detail}`);
|
|
15617
|
+
}
|
|
15618
|
+
}
|
|
15619
|
+
function checkFilterFlags(opts, acceptText) {
|
|
15620
|
+
if ((opts.accept != null || opts.acceptFile != null) && !(acceptText ?? "").trim()) throw usage("Empty pairing payload; provide JSON via --accept or --accept-file");
|
|
15621
|
+
const filtered = opts.include || opts.exclude || opts.all || opts.default;
|
|
15622
|
+
if (!acceptText && filtered) throw usage("Project filters are outbound-only and must be set on the device running --accept");
|
|
15623
|
+
if (!acceptText?.trim()) return;
|
|
15624
|
+
if (opts.all && opts.default) throw usage("Use only one of --all or --default");
|
|
15625
|
+
if ((opts.all || opts.default) && (opts.include || opts.exclude)) throw usage("--include/--exclude cannot be combined with --all/--default");
|
|
15626
|
+
}
|
|
15627
|
+
function payloadAddresses(opts, payload) {
|
|
15628
|
+
if (opts.address?.trim()) return [opts.address.trim()];
|
|
15629
|
+
if (!Array.isArray(payload.addresses)) return [];
|
|
15630
|
+
return payload.addresses.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim());
|
|
15631
|
+
}
|
|
15632
|
+
function parsePayload(opts, text) {
|
|
15633
|
+
let payload;
|
|
15634
|
+
try {
|
|
15635
|
+
payload = JSON.parse(text);
|
|
15636
|
+
} catch (error) {
|
|
15637
|
+
throw new PairRefusal("invalid_payload", `Invalid pairing payload${error instanceof Error ? `: ${error.message}` : ""}`);
|
|
15638
|
+
}
|
|
15639
|
+
const deviceId = String(payload.device_id || "").trim();
|
|
15640
|
+
const fingerprint = String(payload.fingerprint || "").trim();
|
|
15641
|
+
const publicKey = String(payload.public_key || "").trim();
|
|
15642
|
+
const addresses = payloadAddresses(opts, payload);
|
|
15643
|
+
if (!deviceId || !fingerprint || !publicKey || addresses.length === 0) throw new PairRefusal("invalid_payload", "Pairing payload missing device_id, fingerprint, public_key, or addresses");
|
|
15644
|
+
if (fingerprintPublicKey(publicKey) !== fingerprint) throw new PairRefusal("fingerprint_mismatch", "Pairing payload fingerprint mismatch");
|
|
15645
|
+
return {
|
|
15646
|
+
payload,
|
|
15647
|
+
deviceId,
|
|
15648
|
+
fingerprint,
|
|
15649
|
+
publicKey,
|
|
15650
|
+
addresses
|
|
15651
|
+
};
|
|
15652
|
+
}
|
|
15653
|
+
function refuseStalePin(store, pairing) {
|
|
15654
|
+
const pinned = store.db.prepare("SELECT pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").pluck().get(pairing.deviceId);
|
|
15655
|
+
const existing = String(pinned ?? "").trim();
|
|
15656
|
+
if (existing && existing !== pairing.fingerprint) throw new PairRefusal("peer_conflict", STALE_PIN);
|
|
15657
|
+
}
|
|
15658
|
+
/**
|
|
15659
|
+
* The conflict check, the pin, the transport evidence and the checked filter
|
|
15660
|
+
* write share one immediate transaction. A re-pin from another process waits
|
|
15661
|
+
* for it or is seen by it, and a refused filter write rolls back the pin.
|
|
15662
|
+
*/
|
|
15663
|
+
function savePairing(store, opts, pairing) {
|
|
15664
|
+
const { deviceId } = pairing;
|
|
15665
|
+
const db = store.db;
|
|
15666
|
+
const change = pairFilterChange(opts);
|
|
15667
|
+
db.transaction(() => {
|
|
15668
|
+
refuseStalePin(store, pairing);
|
|
15669
|
+
if (change !== null && !peerProjectFilterChangeOnlyNarrows(db, deviceId, change) && !readPeerProjectFilterAuthority(db)) throw new Error(PAIR_FILTERS_REFUSED);
|
|
15670
|
+
updatePeerAddresses(db, deviceId, pairing.addresses, {
|
|
15671
|
+
name: opts.name,
|
|
15672
|
+
pinnedFingerprint: pairing.fingerprint,
|
|
15673
|
+
publicKey: pairing.publicKey,
|
|
15674
|
+
replaceTrust: true
|
|
15675
|
+
});
|
|
15676
|
+
recordPairingTransportEvidence(db, deviceId, pairing.payload);
|
|
15677
|
+
if (change && setPeerProjectFilterChecked(db, deviceId, change) !== "saved") throw new Error(PAIR_FILTERS_REFUSED);
|
|
15678
|
+
}).immediate();
|
|
15679
|
+
}
|
|
15680
|
+
function acceptPairing(store, opts, text) {
|
|
15681
|
+
const pairing = parsePayload(opts, text);
|
|
15682
|
+
savePairing(store, opts, pairing);
|
|
15683
|
+
if (opts.json) {
|
|
15684
|
+
console.log(JSON.stringify({
|
|
15685
|
+
ok: true,
|
|
15686
|
+
peer_device_id: pairing.deviceId
|
|
15687
|
+
}));
|
|
15688
|
+
return;
|
|
15689
|
+
}
|
|
15690
|
+
p.log.success(`Paired with ${pairing.deviceId}`);
|
|
15691
|
+
}
|
|
15692
|
+
function readCliConfig$1(configPath) {
|
|
15693
|
+
return configPath ? readCodememConfigFileAtPath(configPath) : readCodememConfigFile();
|
|
15694
|
+
}
|
|
15695
|
+
function localPairingPayload(store, opts) {
|
|
15696
|
+
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
15697
|
+
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15698
|
+
const publicKey = loadPublicKey(keysDir);
|
|
15699
|
+
if (!publicKey) throw new PairRefusal("missing_key", "Public key missing");
|
|
15700
|
+
const config = readCliConfig$1(opts.config);
|
|
15701
|
+
const addresses = collectAdvertiseAddresses(opts.address?.trim() ?? null, typeof config.sync_host === "string" ? config.sync_host : null, typeof config.sync_port === "number" ? config.sync_port : 7337, networkInterfaces());
|
|
15702
|
+
return JSON.stringify(buildPairingPayload({
|
|
15703
|
+
deviceId,
|
|
15704
|
+
fingerprint,
|
|
15705
|
+
publicKey,
|
|
15706
|
+
addresses
|
|
15707
|
+
}));
|
|
15708
|
+
}
|
|
15709
|
+
function printPairingPayload(store, opts) {
|
|
15710
|
+
const payloadText = localPairingPayload(store, opts);
|
|
15711
|
+
if (opts.payloadOnly || opts.json) {
|
|
15712
|
+
process.stdout.write(`${payloadText}\n`);
|
|
15713
|
+
return;
|
|
15714
|
+
}
|
|
15715
|
+
const escaped = payloadText.replaceAll("'", "'\\''");
|
|
15716
|
+
console.log("Pairing payload");
|
|
15717
|
+
console.log(payloadText);
|
|
15718
|
+
console.log("On the other device, save this JSON to pairing.json, then run:");
|
|
15719
|
+
console.log(" codemem sync pair --accept-file pairing.json");
|
|
15720
|
+
console.log("If you prefer inline JSON, run:");
|
|
15721
|
+
console.log(` codemem sync pair --accept '${escaped}'`);
|
|
15722
|
+
console.log("For machine-friendly output next time, run:");
|
|
15723
|
+
console.log(" codemem sync pair --payload-only");
|
|
15724
|
+
console.log("On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.");
|
|
15725
|
+
}
|
|
15726
|
+
async function runPair(opts) {
|
|
15727
|
+
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15728
|
+
try {
|
|
15729
|
+
checkModeFlags(opts);
|
|
15730
|
+
const acceptText = await readAcceptText(opts);
|
|
15731
|
+
checkFilterFlags(opts, acceptText);
|
|
15732
|
+
if (acceptText?.trim()) acceptPairing(store, opts, acceptText);
|
|
15733
|
+
else printPairingPayload(store, opts);
|
|
15734
|
+
} catch (error) {
|
|
15735
|
+
reportFailure$1(opts, error);
|
|
15736
|
+
} finally {
|
|
15737
|
+
store.close();
|
|
15738
|
+
}
|
|
15739
|
+
}
|
|
15740
|
+
function buildSyncPairCommand() {
|
|
15741
|
+
const command = new Command("pair").configureHelp(helpStyle).description("Create or accept a device pairing request").option("--accept <json>", "accept pairing payload JSON from another device").option("--accept-file <path>", "accept pairing payload from file path, or '-' for stdin").option("--payload-only", "when generating pairing payload, print JSON only").option("--name <name>", "label for the peer").option("--address <host:port>", "override peer address (host:port)").option("--include <projects>", "outbound-only allowlist for accepted peer").option("--exclude <projects>", "outbound-only blocklist for accepted peer").option("--all", "with --accept, push all projects to that peer").option("--default", "with --accept, use default/global push filters");
|
|
15742
|
+
addDbOption(command);
|
|
15743
|
+
addConfigOption(command);
|
|
15744
|
+
addJsonOption(command);
|
|
15745
|
+
command.action(runPair);
|
|
15746
|
+
return command;
|
|
15747
|
+
}
|
|
15748
|
+
//#endregion
|
|
14852
15749
|
//#region src/commands/sync-rejoin.ts
|
|
14853
15750
|
function readProfile(options) {
|
|
14854
15751
|
const config = options.config ? readCodememConfigFileAtPath(options.config) : readCodememConfigFile();
|
|
@@ -15329,251 +16226,7 @@ onceCmd.action(async (opts) => {
|
|
|
15329
16226
|
}
|
|
15330
16227
|
});
|
|
15331
16228
|
syncCommand.addCommand(onceCmd);
|
|
15332
|
-
|
|
15333
|
-
/** The filters the pair flags ask for, or null when no filter flag was given. */
|
|
15334
|
-
function pairFilterChange(opts) {
|
|
15335
|
-
if (opts.default) return {
|
|
15336
|
-
include: null,
|
|
15337
|
-
exclude: null
|
|
15338
|
-
};
|
|
15339
|
-
if (opts.all) return {
|
|
15340
|
-
include: [],
|
|
15341
|
-
exclude: []
|
|
15342
|
-
};
|
|
15343
|
-
if (!opts.include && !opts.exclude) return null;
|
|
15344
|
-
return {
|
|
15345
|
-
include: parseProjectList(opts.include),
|
|
15346
|
-
exclude: parseProjectList(opts.exclude)
|
|
15347
|
-
};
|
|
15348
|
-
}
|
|
15349
|
-
/** What the running `sync pair` asked for. Set before its handler runs and cleared after it. */
|
|
15350
|
-
var pairRun = null;
|
|
15351
|
-
function beginPairRun(opts) {
|
|
15352
|
-
pairRun = pairFilterChange(opts);
|
|
15353
|
-
}
|
|
15354
|
-
/** Stores an accepted pairing, unless its filter flags would widen on a device that may not. */
|
|
15355
|
-
function updatePeerAddresses$1(...args) {
|
|
15356
|
-
const [db, peerDeviceId] = args;
|
|
15357
|
-
if (pairRun !== null && !readPeerProjectFilterAuthority(db) && !peerProjectFilterChangeOnlyNarrows(db, peerDeviceId, pairRun)) throw new Error(PAIR_FILTERS_REFUSED);
|
|
15358
|
-
updatePeerAddresses(...args);
|
|
15359
|
-
}
|
|
15360
|
-
/** The filter write of an accepted pairing rechecks authority inside the transaction. */
|
|
15361
|
-
function setPeerProjectFilter(db, peerDeviceId, lists) {
|
|
15362
|
-
if (setPeerProjectFilterChecked(db, peerDeviceId, lists) !== "saved") throw new Error(PAIR_FILTERS_REFUSED);
|
|
15363
|
-
}
|
|
15364
|
-
var pairCmd = new Command("pair").configureHelp(helpStyle).description("Create or accept a device pairing request").option("--accept <json>", "accept pairing payload JSON from another device").option("--accept-file <path>", "accept pairing payload from file path, or '-' for stdin").option("--payload-only", "when generating pairing payload, print JSON only").option("--name <name>", "label for the peer").option("--address <host:port>", "override peer address (host:port)").option("--include <projects>", "outbound-only allowlist for accepted peer").option("--exclude <projects>", "outbound-only blocklist for accepted peer").option("--all", "with --accept, push all projects to that peer").option("--default", "with --accept, use default/global push filters");
|
|
15365
|
-
addDbOption(pairCmd);
|
|
15366
|
-
addConfigOption(pairCmd);
|
|
15367
|
-
addJsonOption(pairCmd);
|
|
15368
|
-
pairCmd.hook("preAction", (_command, action) => beginPairRun(action.opts()));
|
|
15369
|
-
pairCmd.hook("postAction", () => {
|
|
15370
|
-
pairRun = null;
|
|
15371
|
-
});
|
|
15372
|
-
pairCmd.action(async (opts) => {
|
|
15373
|
-
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15374
|
-
try {
|
|
15375
|
-
const acceptModeRequested = opts.accept != null || opts.acceptFile != null;
|
|
15376
|
-
if (opts.payloadOnly && acceptModeRequested) {
|
|
15377
|
-
if (opts.json) {
|
|
15378
|
-
emitJsonError("usage_error", "--payload-only cannot be combined with --accept or --accept-file", 2);
|
|
15379
|
-
return;
|
|
15380
|
-
}
|
|
15381
|
-
p.log.error("--payload-only cannot be combined with --accept or --accept-file");
|
|
15382
|
-
process.exitCode = 1;
|
|
15383
|
-
return;
|
|
15384
|
-
}
|
|
15385
|
-
if (opts.accept && opts.acceptFile) {
|
|
15386
|
-
if (opts.json) {
|
|
15387
|
-
emitJsonError("usage_error", "Use only one of --accept or --accept-file", 2);
|
|
15388
|
-
return;
|
|
15389
|
-
}
|
|
15390
|
-
p.log.error("Use only one of --accept or --accept-file");
|
|
15391
|
-
process.exitCode = 1;
|
|
15392
|
-
return;
|
|
15393
|
-
}
|
|
15394
|
-
let acceptText = opts.accept;
|
|
15395
|
-
if (opts.acceptFile) try {
|
|
15396
|
-
acceptText = opts.acceptFile === "-" ? await new Promise((resolve, reject) => {
|
|
15397
|
-
let text = "";
|
|
15398
|
-
process.stdin.setEncoding("utf8");
|
|
15399
|
-
process.stdin.on("data", (chunk) => {
|
|
15400
|
-
text += chunk;
|
|
15401
|
-
});
|
|
15402
|
-
process.stdin.on("end", () => resolve(text));
|
|
15403
|
-
process.stdin.on("error", reject);
|
|
15404
|
-
}) : readFileSync(opts.acceptFile, "utf8");
|
|
15405
|
-
} catch (error) {
|
|
15406
|
-
const msg = error instanceof Error ? `Failed to read pairing payload from ${opts.acceptFile}: ${error.message}` : `Failed to read pairing payload from ${opts.acceptFile}`;
|
|
15407
|
-
if (opts.json) {
|
|
15408
|
-
emitJsonError("read_error", msg);
|
|
15409
|
-
return;
|
|
15410
|
-
}
|
|
15411
|
-
p.log.error(msg);
|
|
15412
|
-
process.exitCode = 1;
|
|
15413
|
-
return;
|
|
15414
|
-
}
|
|
15415
|
-
if (acceptModeRequested && !(acceptText ?? "").trim()) {
|
|
15416
|
-
if (opts.json) {
|
|
15417
|
-
emitJsonError("usage_error", "Empty pairing payload; provide JSON via --accept or --accept-file", 2);
|
|
15418
|
-
return;
|
|
15419
|
-
}
|
|
15420
|
-
p.log.error("Empty pairing payload; provide JSON via --accept or --accept-file");
|
|
15421
|
-
process.exitCode = 1;
|
|
15422
|
-
return;
|
|
15423
|
-
}
|
|
15424
|
-
if (!acceptText && (opts.include || opts.exclude || opts.all || opts.default)) {
|
|
15425
|
-
if (opts.json) {
|
|
15426
|
-
emitJsonError("usage_error", "Project filters are outbound-only and must be set on the device running --accept", 2);
|
|
15427
|
-
return;
|
|
15428
|
-
}
|
|
15429
|
-
p.log.error("Project filters are outbound-only and must be set on the device running --accept");
|
|
15430
|
-
process.exitCode = 1;
|
|
15431
|
-
return;
|
|
15432
|
-
}
|
|
15433
|
-
if (acceptText?.trim()) {
|
|
15434
|
-
if (opts.all && opts.default) {
|
|
15435
|
-
if (opts.json) {
|
|
15436
|
-
emitJsonError("usage_error", "Use only one of --all or --default", 2);
|
|
15437
|
-
return;
|
|
15438
|
-
}
|
|
15439
|
-
p.log.error("Use only one of --all or --default");
|
|
15440
|
-
process.exitCode = 1;
|
|
15441
|
-
return;
|
|
15442
|
-
}
|
|
15443
|
-
if ((opts.all || opts.default) && (opts.include || opts.exclude)) {
|
|
15444
|
-
if (opts.json) {
|
|
15445
|
-
emitJsonError("usage_error", "--include/--exclude cannot be combined with --all/--default", 2);
|
|
15446
|
-
return;
|
|
15447
|
-
}
|
|
15448
|
-
p.log.error("--include/--exclude cannot be combined with --all/--default");
|
|
15449
|
-
process.exitCode = 1;
|
|
15450
|
-
return;
|
|
15451
|
-
}
|
|
15452
|
-
let payload;
|
|
15453
|
-
try {
|
|
15454
|
-
payload = JSON.parse(acceptText);
|
|
15455
|
-
} catch (error) {
|
|
15456
|
-
const msg = error instanceof Error ? `Invalid pairing payload: ${error.message}` : "Invalid pairing payload";
|
|
15457
|
-
if (opts.json) {
|
|
15458
|
-
emitJsonError("invalid_payload", msg);
|
|
15459
|
-
return;
|
|
15460
|
-
}
|
|
15461
|
-
p.log.error(msg);
|
|
15462
|
-
process.exitCode = 1;
|
|
15463
|
-
return;
|
|
15464
|
-
}
|
|
15465
|
-
const deviceId = String(payload.device_id || "").trim();
|
|
15466
|
-
const fingerprint = String(payload.fingerprint || "").trim();
|
|
15467
|
-
const publicKey = String(payload.public_key || "").trim();
|
|
15468
|
-
const resolvedAddresses = opts.address?.trim() ? [opts.address.trim()] : Array.isArray(payload.addresses) ? payload.addresses.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim()) : [];
|
|
15469
|
-
if (!deviceId || !fingerprint || !publicKey || resolvedAddresses.length === 0) {
|
|
15470
|
-
const msg = "Pairing payload missing device_id, fingerprint, public_key, or addresses";
|
|
15471
|
-
if (opts.json) {
|
|
15472
|
-
emitJsonError("invalid_payload", msg);
|
|
15473
|
-
return;
|
|
15474
|
-
}
|
|
15475
|
-
p.log.error(msg);
|
|
15476
|
-
process.exitCode = 1;
|
|
15477
|
-
return;
|
|
15478
|
-
}
|
|
15479
|
-
if (fingerprintPublicKey(publicKey) !== fingerprint) {
|
|
15480
|
-
if (opts.json) {
|
|
15481
|
-
emitJsonError("fingerprint_mismatch", "Pairing payload fingerprint mismatch");
|
|
15482
|
-
return;
|
|
15483
|
-
}
|
|
15484
|
-
p.log.error("Pairing payload fingerprint mismatch");
|
|
15485
|
-
process.exitCode = 1;
|
|
15486
|
-
return;
|
|
15487
|
-
}
|
|
15488
|
-
const existingPeer = drizzle(store.db, { schema }).select({ pinned_fingerprint: schema.syncPeers.pinned_fingerprint }).from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, deviceId)).get();
|
|
15489
|
-
const existingFingerprint = String(existingPeer?.pinned_fingerprint ?? "").trim();
|
|
15490
|
-
if (existingFingerprint && existingFingerprint !== fingerprint) {
|
|
15491
|
-
const msg = "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.";
|
|
15492
|
-
if (opts.json) {
|
|
15493
|
-
emitJsonError("peer_conflict", msg);
|
|
15494
|
-
return;
|
|
15495
|
-
}
|
|
15496
|
-
p.log.error(msg);
|
|
15497
|
-
process.exitCode = 1;
|
|
15498
|
-
return;
|
|
15499
|
-
}
|
|
15500
|
-
updatePeerAddresses$1(store.db, deviceId, resolvedAddresses, {
|
|
15501
|
-
name: opts.name,
|
|
15502
|
-
pinnedFingerprint: fingerprint,
|
|
15503
|
-
publicKey,
|
|
15504
|
-
replaceTrust: true
|
|
15505
|
-
});
|
|
15506
|
-
if (opts.default) setPeerProjectFilter(store.db, deviceId, {
|
|
15507
|
-
include: null,
|
|
15508
|
-
exclude: null
|
|
15509
|
-
});
|
|
15510
|
-
else if (opts.all || opts.include || opts.exclude) setPeerProjectFilter(store.db, deviceId, {
|
|
15511
|
-
include: opts.all ? [] : parseProjectList(opts.include),
|
|
15512
|
-
exclude: opts.all ? [] : parseProjectList(opts.exclude)
|
|
15513
|
-
});
|
|
15514
|
-
if (opts.json) {
|
|
15515
|
-
console.log(JSON.stringify({
|
|
15516
|
-
ok: true,
|
|
15517
|
-
peer_device_id: deviceId
|
|
15518
|
-
}));
|
|
15519
|
-
return;
|
|
15520
|
-
}
|
|
15521
|
-
p.log.success(`Paired with ${deviceId}`);
|
|
15522
|
-
return;
|
|
15523
|
-
}
|
|
15524
|
-
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
15525
|
-
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15526
|
-
const publicKey = loadPublicKey(keysDir);
|
|
15527
|
-
if (!publicKey) {
|
|
15528
|
-
if (opts.json) {
|
|
15529
|
-
emitJsonError("missing_key", "Public key missing");
|
|
15530
|
-
return;
|
|
15531
|
-
}
|
|
15532
|
-
p.log.error("Public key missing");
|
|
15533
|
-
process.exitCode = 1;
|
|
15534
|
-
return;
|
|
15535
|
-
}
|
|
15536
|
-
const config = readCliConfig(opts.config);
|
|
15537
|
-
const explicitAddress = opts.address?.trim();
|
|
15538
|
-
const configuredHost = typeof config.sync_host === "string" ? config.sync_host : null;
|
|
15539
|
-
const configuredPort = typeof config.sync_port === "number" ? config.sync_port : 7337;
|
|
15540
|
-
const addresses = collectAdvertiseAddresses(explicitAddress ?? null, configuredHost, configuredPort, networkInterfaces());
|
|
15541
|
-
const payloadObj = {
|
|
15542
|
-
device_id: deviceId,
|
|
15543
|
-
fingerprint,
|
|
15544
|
-
public_key: publicKey,
|
|
15545
|
-
address: addresses[0] ?? "",
|
|
15546
|
-
addresses
|
|
15547
|
-
};
|
|
15548
|
-
const payloadText = JSON.stringify(payloadObj);
|
|
15549
|
-
if (opts.payloadOnly || opts.json) {
|
|
15550
|
-
process.stdout.write(`${payloadText}\n`);
|
|
15551
|
-
return;
|
|
15552
|
-
}
|
|
15553
|
-
const escaped = payloadText.replaceAll("'", "'\\''");
|
|
15554
|
-
console.log("Pairing payload");
|
|
15555
|
-
console.log(payloadText);
|
|
15556
|
-
console.log("On the other device, save this JSON to pairing.json, then run:");
|
|
15557
|
-
console.log(" codemem sync pair --accept-file pairing.json");
|
|
15558
|
-
console.log("If you prefer inline JSON, run:");
|
|
15559
|
-
console.log(` codemem sync pair --accept '${escaped}'`);
|
|
15560
|
-
console.log("For machine-friendly output next time, run:");
|
|
15561
|
-
console.log(" codemem sync pair --payload-only");
|
|
15562
|
-
console.log("On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.");
|
|
15563
|
-
} catch (error) {
|
|
15564
|
-
const code = error instanceof DeviceIdentityError ? error.code : "pairing_failed";
|
|
15565
|
-
const message = error instanceof Error ? error.message : "Pairing failed";
|
|
15566
|
-
if (opts.json) {
|
|
15567
|
-
emitJsonError(code, message);
|
|
15568
|
-
return;
|
|
15569
|
-
}
|
|
15570
|
-
p.log.error(message);
|
|
15571
|
-
process.exitCode = 1;
|
|
15572
|
-
} finally {
|
|
15573
|
-
store.close();
|
|
15574
|
-
}
|
|
15575
|
-
});
|
|
15576
|
-
syncCommand.addCommand(pairCmd);
|
|
16229
|
+
syncCommand.addCommand(buildSyncPairCommand());
|
|
15577
16230
|
var doctorCmd = new Command("doctor").configureHelp(helpStyle).description("Check sync configuration and connectivity");
|
|
15578
16231
|
addDbOption(doctorCmd);
|
|
15579
16232
|
addConfigOption(doctorCmd);
|
|
@@ -15824,16 +16477,19 @@ peersCommand.action((opts) => {
|
|
|
15824
16477
|
store.close();
|
|
15825
16478
|
}
|
|
15826
16479
|
});
|
|
15827
|
-
/**
|
|
15828
|
-
|
|
15829
|
-
|
|
15830
|
-
|
|
15831
|
-
|
|
16480
|
+
/**
|
|
16481
|
+
* What the user is told after unpairing. With a coordinator, codemem can pair the devices
|
|
16482
|
+
* again, so Remove device is named as the way to stop everywhere. Without one, nothing
|
|
16483
|
+
* pairs them again.
|
|
16484
|
+
*/
|
|
16485
|
+
function peerRemovalNotices(label, coordinatorConfigured) {
|
|
16486
|
+
if (!coordinatorConfigured) return [`This device stops syncing with ${label}. ${label} keeps syncing with your other devices.`];
|
|
16487
|
+
return [`This device stops syncing with ${label}. If both devices share a Team Project, codemem can pair them again automatically.`, `To stop syncing with ${label} on all your devices, use Remove device.`];
|
|
15832
16488
|
}
|
|
15833
16489
|
function reportPeerRemoved(match, result, options) {
|
|
15834
16490
|
const label = match.name || match.peer_device_id;
|
|
15835
16491
|
const { binding, removed } = result;
|
|
15836
|
-
const notices = peerRemovalNotices(label,
|
|
16492
|
+
const notices = peerRemovalNotices(label, Boolean(readCoordinatorSyncConfig().syncCoordinatorUrl.trim()));
|
|
15837
16493
|
if (options.json) {
|
|
15838
16494
|
const payload = {
|
|
15839
16495
|
ok: true,
|
|
@@ -15847,24 +16503,20 @@ function reportPeerRemoved(match, result, options) {
|
|
|
15847
16503
|
identity_devices: removed.identityDevices
|
|
15848
16504
|
},
|
|
15849
16505
|
binding,
|
|
15850
|
-
|
|
16506
|
+
remove_from_projects: "needs_admin_device",
|
|
15851
16507
|
notice: notices.join(" ")
|
|
15852
16508
|
};
|
|
15853
16509
|
console.log(JSON.stringify(payload, null, 2));
|
|
15854
16510
|
return;
|
|
15855
16511
|
}
|
|
15856
16512
|
p.intro("codemem sync peers remove");
|
|
15857
|
-
p.log.success(
|
|
16513
|
+
p.log.success(`Unpaired this device from ${label}.`);
|
|
15858
16514
|
const progressRows = removed.replicationCursors + removed.replicationCursorsV2 + removed.syncChannelProgress;
|
|
15859
|
-
p.log.message([
|
|
15860
|
-
` pairing: ${removed.syncPeers}`,
|
|
15861
|
-
` sync progress rows: ${progressRows}`,
|
|
15862
|
-
` Identity bindings ended: ${removed.identityDevices}`
|
|
15863
|
-
].join("\n"));
|
|
16515
|
+
p.log.message([` pairing: ${removed.syncPeers}`, ` sync progress rows: ${progressRows}`].join("\n"));
|
|
15864
16516
|
for (const notice of notices) p.log.warn(notice);
|
|
15865
16517
|
p.outro(match.peer_device_id);
|
|
15866
16518
|
}
|
|
15867
|
-
async function removeSyncPeer(peerRef, opts
|
|
16519
|
+
async function removeSyncPeer(peerRef, opts) {
|
|
15868
16520
|
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15869
16521
|
try {
|
|
15870
16522
|
const match = resolvePeerMatch(drizzle(store.db, { schema }), peerRef);
|
|
@@ -15889,10 +16541,9 @@ async function removeSyncPeer(peerRef, opts, dependencies = {}) {
|
|
|
15889
16541
|
const label = match.name || match.peer_device_id;
|
|
15890
16542
|
let result;
|
|
15891
16543
|
try {
|
|
15892
|
-
result =
|
|
16544
|
+
result = removePeerFromThisDevice(store.db, {
|
|
15893
16545
|
localDeviceId: store.deviceId,
|
|
15894
|
-
peerDeviceId: match.peer_device_id
|
|
15895
|
-
lookupCoordinatorAnswer: dependencies.lookupCoordinatorAnswer
|
|
16546
|
+
peerDeviceId: match.peer_device_id
|
|
15896
16547
|
});
|
|
15897
16548
|
} catch {
|
|
15898
16549
|
const message = `Could not remove peer ${label}. Nothing was changed.`;
|
|
@@ -15909,7 +16560,7 @@ async function removeSyncPeer(peerRef, opts, dependencies = {}) {
|
|
|
15909
16560
|
store.close();
|
|
15910
16561
|
}
|
|
15911
16562
|
}
|
|
15912
|
-
var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("
|
|
16563
|
+
var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("Unpair this device from a sync peer by device id or exact name").argument("<peer>", "peer device id or exact name");
|
|
15913
16564
|
addDbOption(peersRemoveCmd);
|
|
15914
16565
|
addJsonOption(peersRemoveCmd);
|
|
15915
16566
|
peersRemoveCmd.action((peerRef, opts) => removeSyncPeer(peerRef, opts));
|
|
@@ -15917,172 +16568,7 @@ peersCommand.addCommand(peersRemoveCmd);
|
|
|
15917
16568
|
syncCommand.addCommand(peersCommand);
|
|
15918
16569
|
syncCommand.addCommand(relayKeysCommand);
|
|
15919
16570
|
syncCommand.addCommand(approveRelayKeyCommand);
|
|
15920
|
-
|
|
15921
|
-
addDbOption(bootstrapCmd);
|
|
15922
|
-
addJsonOption(bootstrapCmd);
|
|
15923
|
-
bootstrapCmd.addOption(new Option("--peer <device-id>", "peer device ID").hideHelp());
|
|
15924
|
-
bootstrapCmd.action(async (peerArg, opts) => {
|
|
15925
|
-
const peerDeviceId = (peerArg || opts.peer || "").trim();
|
|
15926
|
-
if (!peerDeviceId) {
|
|
15927
|
-
if (opts.json) {
|
|
15928
|
-
emitJsonError("usage_error", "missing required argument: <peer-device-id>", 2);
|
|
15929
|
-
return;
|
|
15930
|
-
}
|
|
15931
|
-
p.log.error("missing required argument: <peer-device-id>");
|
|
15932
|
-
process.exitCode = 2;
|
|
15933
|
-
return;
|
|
15934
|
-
}
|
|
15935
|
-
const dbPath = resolveDbPath(resolveDbOpt(opts));
|
|
15936
|
-
const store = new MemoryStore(dbPath);
|
|
15937
|
-
try {
|
|
15938
|
-
const pageSize = Math.max(1, Number.parseInt(opts.pageSize, 10) || 2e3);
|
|
15939
|
-
const keysDir = opts.keysDir ?? void 0;
|
|
15940
|
-
const peer = drizzle(store.db, { schema }).select().from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get();
|
|
15941
|
-
if (!peer) {
|
|
15942
|
-
if (opts.json) emitJsonError("peer_not_found", `Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15943
|
-
else p.log.error(`Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15944
|
-
process.exitCode = 1;
|
|
15945
|
-
return;
|
|
15946
|
-
}
|
|
15947
|
-
if (!peer.pinned_fingerprint) {
|
|
15948
|
-
if (opts.json) emitJsonError("peer_not_pinned", `Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15949
|
-
else p.log.error(`Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15950
|
-
process.exitCode = 1;
|
|
15951
|
-
return;
|
|
15952
|
-
}
|
|
15953
|
-
if (!opts.force) {
|
|
15954
|
-
const dirty = hasUnsyncedSharedMemoryChanges(store.db);
|
|
15955
|
-
if (dirty.dirty) {
|
|
15956
|
-
if (opts.json) emitJsonError("local_unsynced_changes", `${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15957
|
-
else p.log.error(`${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15958
|
-
process.exitCode = 1;
|
|
15959
|
-
return;
|
|
15960
|
-
}
|
|
15961
|
-
}
|
|
15962
|
-
const [deviceId] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15963
|
-
const addresses = JSON.parse(String(peer.addresses_json ?? "[]"));
|
|
15964
|
-
if (!addresses.length) {
|
|
15965
|
-
if (opts.json) emitJsonError("no_peer_addresses", "Peer has no known addresses. Run a sync first or add addresses.");
|
|
15966
|
-
else p.log.error("Peer has no known addresses. Run a sync first or add addresses.");
|
|
15967
|
-
process.exitCode = 1;
|
|
15968
|
-
return;
|
|
15969
|
-
}
|
|
15970
|
-
let boundary = null;
|
|
15971
|
-
let baseUrl = "";
|
|
15972
|
-
const addressResults = [];
|
|
15973
|
-
for (const address of addresses) {
|
|
15974
|
-
const candidate = buildBaseUrl(address);
|
|
15975
|
-
if (!candidate) continue;
|
|
15976
|
-
const statusUrl = `${candidate}/v1/status`;
|
|
15977
|
-
const headers = buildDirectPeerAuthHeaders({
|
|
15978
|
-
deviceId,
|
|
15979
|
-
recipientId: peerDeviceId,
|
|
15980
|
-
dbPath: store.dbPath,
|
|
15981
|
-
method: "GET",
|
|
15982
|
-
url: statusUrl,
|
|
15983
|
-
bodyBytes: Buffer.alloc(0),
|
|
15984
|
-
bootstrapGrantId: opts.bootstrapGrant,
|
|
15985
|
-
keysDir
|
|
15986
|
-
});
|
|
15987
|
-
try {
|
|
15988
|
-
const [code, payload] = await requestJson("GET", statusUrl, { headers });
|
|
15989
|
-
if (code !== 200 || !payload) {
|
|
15990
|
-
addressResults.push({
|
|
15991
|
-
address: candidate,
|
|
15992
|
-
result: `status ${code}`
|
|
15993
|
-
});
|
|
15994
|
-
continue;
|
|
15995
|
-
}
|
|
15996
|
-
if (payload.fingerprint !== peer.pinned_fingerprint) {
|
|
15997
|
-
addressResults.push({
|
|
15998
|
-
address: candidate,
|
|
15999
|
-
result: "fingerprint mismatch"
|
|
16000
|
-
});
|
|
16001
|
-
continue;
|
|
16002
|
-
}
|
|
16003
|
-
const reset = payload.sync_reset;
|
|
16004
|
-
if (reset && typeof reset.generation === "number" && typeof reset.snapshot_id === "string") {
|
|
16005
|
-
boundary = {
|
|
16006
|
-
generation: reset.generation,
|
|
16007
|
-
snapshot_id: reset.snapshot_id,
|
|
16008
|
-
baseline_cursor: typeof reset.baseline_cursor === "string" ? reset.baseline_cursor : null
|
|
16009
|
-
};
|
|
16010
|
-
baseUrl = candidate;
|
|
16011
|
-
addressResults.push({
|
|
16012
|
-
address: candidate,
|
|
16013
|
-
result: "ok"
|
|
16014
|
-
});
|
|
16015
|
-
break;
|
|
16016
|
-
}
|
|
16017
|
-
addressResults.push({
|
|
16018
|
-
address: candidate,
|
|
16019
|
-
result: "missing sync_reset boundary"
|
|
16020
|
-
});
|
|
16021
|
-
} catch (err) {
|
|
16022
|
-
addressResults.push({
|
|
16023
|
-
address: candidate,
|
|
16024
|
-
result: err instanceof Error ? err.message : String(err)
|
|
16025
|
-
});
|
|
16026
|
-
}
|
|
16027
|
-
}
|
|
16028
|
-
if (!boundary || !baseUrl) {
|
|
16029
|
-
const summary = addressResults.map((r) => `${r.address}: ${r.result}`).join("; ");
|
|
16030
|
-
const detail = summary ? `no reachable peer with valid reset boundary. Tried: ${summary}` : "peer unreachable or missing reset boundary";
|
|
16031
|
-
if (opts.json) console.log(JSON.stringify({
|
|
16032
|
-
ok: false,
|
|
16033
|
-
error: detail,
|
|
16034
|
-
addresses: addressResults
|
|
16035
|
-
}));
|
|
16036
|
-
else p.log.error(detail);
|
|
16037
|
-
process.exitCode = 1;
|
|
16038
|
-
return;
|
|
16039
|
-
}
|
|
16040
|
-
if (!opts.json) {
|
|
16041
|
-
p.intro("codemem sync bootstrap");
|
|
16042
|
-
p.log.step(`Bootstrapping from ${peer.name || peerDeviceId}...`);
|
|
16043
|
-
}
|
|
16044
|
-
const resetInfo = {
|
|
16045
|
-
generation: boundary.generation,
|
|
16046
|
-
snapshot_id: boundary.snapshot_id,
|
|
16047
|
-
baseline_cursor: boundary.baseline_cursor,
|
|
16048
|
-
retained_floor_cursor: null,
|
|
16049
|
-
reset_required: true,
|
|
16050
|
-
reason: "initial_bootstrap"
|
|
16051
|
-
};
|
|
16052
|
-
const { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, {
|
|
16053
|
-
keysDir,
|
|
16054
|
-
dbPath: store.dbPath,
|
|
16055
|
-
bootstrapGrantId: opts.bootstrapGrant,
|
|
16056
|
-
recipientId: peerDeviceId,
|
|
16057
|
-
pageSize
|
|
16058
|
-
});
|
|
16059
|
-
const result = applyBootstrapSnapshot(store.db, peerDeviceId, items, resetInfo, store.scanner);
|
|
16060
|
-
if (opts.json) console.log(JSON.stringify({
|
|
16061
|
-
ok: result.ok,
|
|
16062
|
-
applied: result.applied,
|
|
16063
|
-
deleted: result.deleted,
|
|
16064
|
-
error: result.error ?? null
|
|
16065
|
-
}));
|
|
16066
|
-
else {
|
|
16067
|
-
if (result.ok) p.log.success(`Applied ${result.applied} memories (removed ${result.deleted} stale).`);
|
|
16068
|
-
else p.log.error(result.error || "Bootstrap apply failed.");
|
|
16069
|
-
p.outro(result.ok ? "Bootstrap complete" : "Bootstrap failed");
|
|
16070
|
-
}
|
|
16071
|
-
if (!result.ok) process.exitCode = 1;
|
|
16072
|
-
} catch (error) {
|
|
16073
|
-
const code = error instanceof DeviceIdentityError ? error.code : "bootstrap_failed";
|
|
16074
|
-
const message = error instanceof Error ? error.message : "Bootstrap failed";
|
|
16075
|
-
if (opts.json) {
|
|
16076
|
-
emitJsonError(code, message);
|
|
16077
|
-
return;
|
|
16078
|
-
}
|
|
16079
|
-
p.log.error(message);
|
|
16080
|
-
process.exitCode = 1;
|
|
16081
|
-
} finally {
|
|
16082
|
-
store.close();
|
|
16083
|
-
}
|
|
16084
|
-
});
|
|
16085
|
-
syncCommand.addCommand(bootstrapCmd);
|
|
16571
|
+
syncCommand.addCommand(buildSyncBootstrapCommand());
|
|
16086
16572
|
function targetsRuntimeConfig(path) {
|
|
16087
16573
|
if (!path) return true;
|
|
16088
16574
|
const runtime = getCodememConfigPath();
|
|
@@ -16124,6 +16610,7 @@ connectCmd.action((url, opts) => {
|
|
|
16124
16610
|
});
|
|
16125
16611
|
syncCommand.addCommand(connectCmd);
|
|
16126
16612
|
syncCommand.addCommand(buildSyncRejoinCommand());
|
|
16613
|
+
syncCommand.addCommand(buildSyncMigrationCommand());
|
|
16127
16614
|
var syncCoordinatorAlias = buildCoordinatorCommand();
|
|
16128
16615
|
syncCoordinatorAlias.hook("preAction", (_thisCmd, actionCmd) => {
|
|
16129
16616
|
if (actionCmd.optsWithGlobals().json) return;
|