@codemem/server 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.
Files changed (38) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1754 -616
  4. package/dist/index.js.map +1 -1
  5. package/dist/request-rate-limit.d.ts +17 -1
  6. package/dist/request-rate-limit.d.ts.map +1 -1
  7. package/dist/response-byte-budget.d.ts +18 -0
  8. package/dist/response-byte-budget.d.ts.map +1 -0
  9. package/dist/routes/config.d.ts.map +1 -1
  10. package/dist/routes/device-removal-local.d.ts.map +1 -1
  11. package/dist/routes/device-removal-lookup.d.ts.map +1 -1
  12. package/dist/routes/sync.d.ts +30 -5
  13. package/dist/routes/sync.d.ts.map +1 -1
  14. package/dist/routes/team-recovery.d.ts +12 -0
  15. package/dist/routes/team-recovery.d.ts.map +1 -0
  16. package/dist/routes/team-setup-view.d.ts +6 -0
  17. package/dist/routes/team-setup-view.d.ts.map +1 -1
  18. package/dist/routes/team-setup.d.ts +18 -3
  19. package/dist/routes/team-setup.d.ts.map +1 -1
  20. package/dist/sync-app.d.ts +3 -1
  21. package/dist/sync-app.d.ts.map +1 -1
  22. package/dist/sync-channel-dispatch.d.ts +9 -0
  23. package/dist/sync-channel-dispatch.d.ts.map +1 -1
  24. package/dist/sync-channel-pass-test-fixtures.d.ts +3 -2
  25. package/dist/sync-channel-pass-test-fixtures.d.ts.map +1 -1
  26. package/dist/sync-listener-guard.d.ts +67 -0
  27. package/dist/sync-listener-guard.d.ts.map +1 -0
  28. package/dist/sync-noise-gate.d.ts +37 -0
  29. package/dist/sync-noise-gate.d.ts.map +1 -0
  30. package/dist/sync-server-mode.d.ts +58 -0
  31. package/dist/sync-server-mode.d.ts.map +1 -0
  32. package/package.json +2 -2
  33. package/static/app.js +50 -50
  34. package/static/app.js.br +0 -0
  35. package/static/app.js.gz +0 -0
  36. package/static/index.html +72 -43
  37. package/dist/routes/device-retire.d.ts +0 -206
  38. package/dist/routes/device-retire.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3
- import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, applyTeamMemberRemovals, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitTeamMemberRemoval, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, completeMaintenanceJob, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnabled, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorReadTeamGroupBindingsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusCacheIdentity, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, isStrictRecipientPolicyId, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, localRemovedDeviceIds, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, previewTeamMemberRemoval, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, readViewerPidFile, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, revokePendingTeamInvitations, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, startMaintenanceJob, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, teamCoordinatorLinkConflicts, teamIdsForBindingRead, teamInvitationGroup, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
3
+ import { ACCESS_CLEANUP_OP_TYPE, CHANNEL_MAX_ENTRY_BYTES, COORDINATOR_FREE_BINDING_UNVERIFIED, COORDINATOR_FREE_WITNESS_UNAVAILABLE, COORDINATOR_JOIN_CONFIRMATION_REQUIRED, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, SyncEntryTooLargeError, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, applyTeamMemberRemovals, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPairingPayload, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitTeamMemberRemoval, commitTeamRecovery, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, completeMaintenanceJob, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnabled, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorReadTeamGroupBindingsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusCacheIdentity, coordinatorStatusSnapshot, coordinatorTeamRecoveryEvidenceActions, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, entriesWithinLimit, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, isStrictRecipientPolicyId, isTeamRecoveryEvidenceStale, isTeamRecoveryHoldAbandoned, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, localRemovedDeviceIds, lookupCoordinatorPeers, markCoordinatorManaged, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, normalizedCoordinatorId, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, peerTransportExecutor, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, previewTeamMemberRemoval, previewTeamRecovery, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readPeerTransportPolicy, readRepositoryIdentitySnapshot, readTeamRecoveryEvidence, readUnpairedPeerPin, readViewerPidFile, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordDeviceCoordinatorHistory, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPairingTransportEvidence, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, revokePendingTeamInvitations, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, startMaintenanceJob, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, teamCoordinatorLinkConflicts, teamIdsForBindingRead, teamInvitationGroup, teamRecoveryTarget, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
4
4
  import { serveStatic } from "@hono/node-server/serve-static";
5
5
  import { Hono } from "hono";
6
6
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -13,12 +13,15 @@ import { Buffer as Buffer$1 } from "node:buffer";
13
13
  import { homedir, hostname, networkInterfaces } from "node:os";
14
14
  import * as z from "zod";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
16
+ import { DIRECT_NOISE_ACTIVE, DIRECT_NOISE_LOGICAL_ORIGIN, DIRECT_NOISE_TRANSPORT_LABEL, DIRECT_NOISE_UPGRADE_PROTOCOL, PEER_HTTP_LIMITS, RELAY_LOGICAL_ORIGIN, RELAY_NOISE_LIMITS, acceptRelayNoiseResponder, createRelayCoordinatorClient, createRelayPeerClient, createRelayPeerReachability, parseDirectNoiseUpgradeTarget, readRelayClientSettings, readRelayServicePin, relayCoordinatorEndpoint, resolveRelayGroup, servePeerHttpConnection } from "@codemem/core/internal/relay-runtime";
16
17
  import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
17
18
  import { BlockList, isIP } from "node:net";
18
- import "better-sqlite3";
19
19
  import "sqlite-vec";
20
+ import "better-sqlite3";
20
21
  import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
21
- import { RELAY_LOGICAL_ORIGIN, createRelayCoordinatorClient, createRelayPeerClient, createRelayPeerReachability, readRelayClientSettings, readRelayServicePin, relayCoordinatorEndpoint, resolveRelayGroup } from "@codemem/core/internal/relay-runtime";
22
+ import { createServer } from "node:http";
23
+ import { performance as performance$1 } from "node:perf_hooks";
24
+ import { finished } from "node:stream/promises";
22
25
  //#region src/routes/account.ts
23
26
  /** Mounted only alongside the account request middleware. */
24
27
  function accountRoutes(getSession) {
@@ -1640,48 +1643,81 @@ function accountStatusRoutes(options) {
1640
1643
  });
1641
1644
  return app;
1642
1645
  }
1643
- //#endregion
1644
- //#region src/request-rate-limit.ts
1645
- function createInMemoryRequestRateLimiter(windowMs = 6e4) {
1646
+ /**
1647
+ * A token bucket per key, at most maxBuckets of them.
1648
+ *
1649
+ * A full map never evicts a bucket that may still be depleted, because a key
1650
+ * could then refill its budget by churning other keys through the map. Only a
1651
+ * bucket unused for a whole window, which has refilled anyway, can make room.
1652
+ * When none can, a new key draws from one overflow budget per limit that
1653
+ * every such key shares, so churn spends that budget instead of minting fresh
1654
+ * ones.
1655
+ */
1656
+ function createInMemoryRequestRateLimiter(windowMs = 6e4, options = {}) {
1646
1657
  const safeWindowMs = Math.max(1e3, Math.trunc(windowMs));
1658
+ const maxBuckets = Math.max(1, Math.trunc(options.maxBuckets ?? 1e4));
1647
1659
  const buckets = /* @__PURE__ */ new Map();
1660
+ const overflow = /* @__PURE__ */ new Map();
1648
1661
  let checks = 0;
1662
+ const newBucket = (limit, now) => ({
1663
+ limiter: new RateLimiter({
1664
+ tokensPerInterval: limit,
1665
+ interval: safeWindowMs,
1666
+ fireImmediately: true
1667
+ }),
1668
+ lastUsedAt: now
1669
+ });
1649
1670
  function estimatedRetryAfterS(limit) {
1650
1671
  return Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1e3));
1651
1672
  }
1652
- function cleanupExpiredBuckets(currentNow) {
1673
+ function cleanupExpiredBuckets(now) {
1653
1674
  if (buckets.size < 64 || checks % 64 !== 0) return;
1654
- const staleBefore = currentNow - safeWindowMs * 10;
1675
+ const staleBefore = now - safeWindowMs * 10;
1655
1676
  for (const [key, bucket] of buckets) if (bucket.lastUsedAt < staleBefore) buckets.delete(key);
1656
1677
  }
1657
- return { check(key, limit) {
1658
- checks += 1;
1659
- const currentNow = Date.now();
1660
- cleanupExpiredBuckets(currentNow);
1661
- const safeLimit = Math.max(1, Math.trunc(limit));
1662
- const bucketKey = `${safeLimit}:${key}`;
1663
- let bucket = buckets.get(bucketKey);
1664
- if (!bucket) {
1665
- bucket = {
1666
- limiter: new RateLimiter({
1667
- tokensPerInterval: safeLimit,
1668
- interval: safeWindowMs,
1669
- fireImmediately: true
1670
- }),
1671
- lastUsedAt: currentNow
1672
- };
1673
- buckets.set(bucketKey, bucket);
1678
+ /** Frees the stalest slot only if that bucket sat unused for a full window. */
1679
+ function makeRoom(now) {
1680
+ if (buckets.size < maxBuckets) return true;
1681
+ const [stalestKey, stalest] = buckets.entries().next().value ?? [];
1682
+ if (stalestKey === void 0 || !stalest || now - stalest.lastUsedAt < safeWindowMs) return false;
1683
+ buckets.delete(stalestKey);
1684
+ return true;
1685
+ }
1686
+ function bucketFor(bucketKey, limit, now) {
1687
+ const existing = buckets.get(bucketKey);
1688
+ if (existing) {
1689
+ buckets.delete(bucketKey);
1690
+ buckets.set(bucketKey, existing);
1691
+ return existing;
1674
1692
  }
1675
- bucket.lastUsedAt = currentNow;
1676
- if (bucket.limiter.tryRemoveTokens(1)) return {
1677
- allowed: true,
1678
- retryAfterS: 0
1679
- };
1680
- return {
1681
- allowed: false,
1682
- retryAfterS: estimatedRetryAfterS(safeLimit)
1683
- };
1684
- } };
1693
+ if (makeRoom(now)) {
1694
+ const created = newBucket(limit, now);
1695
+ buckets.set(bucketKey, created);
1696
+ return created;
1697
+ }
1698
+ const shared = overflow.get(limit) ?? newBucket(limit, now);
1699
+ overflow.set(limit, shared);
1700
+ return shared;
1701
+ }
1702
+ return {
1703
+ check(key, limit) {
1704
+ checks += 1;
1705
+ const now = performance.now();
1706
+ cleanupExpiredBuckets(now);
1707
+ const safeLimit = Math.max(1, Math.trunc(limit));
1708
+ const bucket = bucketFor(`${safeLimit}:${key}`, safeLimit, now);
1709
+ bucket.lastUsedAt = now;
1710
+ if (bucket.limiter.tryRemoveTokens(1)) return {
1711
+ allowed: true,
1712
+ retryAfterS: 0
1713
+ };
1714
+ return {
1715
+ allowed: false,
1716
+ retryAfterS: estimatedRetryAfterS(safeLimit)
1717
+ };
1718
+ },
1719
+ bucketCount: () => buckets.size
1720
+ };
1685
1721
  }
1686
1722
  //#endregion
1687
1723
  //#region src/routes/config.ts
@@ -1741,13 +1777,17 @@ var PROTECTED_WRITE_KEYS = /* @__PURE__ */ new Set([
1741
1777
  "observer_auth_file",
1742
1778
  "observer_auth_command",
1743
1779
  "observer_headers",
1744
- "sync_coordinator_url"
1780
+ "sync_coordinator_url",
1781
+ "sync_coordinator_invite_token_key",
1782
+ "sync_coordinator_invite_token_key_previous"
1745
1783
  ]);
1746
1784
  var SECRET_CONFIG_KEYS = /* @__PURE__ */ new Set([
1747
1785
  "observer_auth_file",
1748
1786
  "observer_auth_command",
1749
1787
  "observer_headers",
1750
- "sync_coordinator_admin_secret"
1788
+ "sync_coordinator_admin_secret",
1789
+ "sync_coordinator_invite_token_key",
1790
+ "sync_coordinator_invite_token_key_previous"
1751
1791
  ]);
1752
1792
  var REMOVED_CONFIG_KEYS = /* @__PURE__ */ new Set(["observer_rich_openai_use_responses"]);
1753
1793
  var ALLOWED_KEYS = [
@@ -2455,6 +2495,24 @@ async function commitViewerDeviceBlock(confirmed, deps) {
2455
2495
  }
2456
2496
  //#endregion
2457
2497
  //#region src/routes/device-removal-lookup.ts
2498
+ /**
2499
+ * The pairing's pin, or the last verified pin kept when this device unpaired the device. The
2500
+ * coordinator is asked about the key either way, so a key-only revocation filed under another
2501
+ * device ID is found. The kept pin never authorizes sync.
2502
+ */
2503
+ function readPin$1(store, deviceId) {
2504
+ const live = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
2505
+ if (live) return live;
2506
+ const kept = readUnpairedPeerPin(store.db, {
2507
+ localDeviceId: store.deviceId,
2508
+ peerDeviceId: deviceId
2509
+ });
2510
+ return kept ? {
2511
+ public_key: kept.publicKey,
2512
+ pinned_fingerprint: kept.pinnedFingerprint,
2513
+ created_at: kept.recordedAt
2514
+ } : void 0;
2515
+ }
2458
2516
  function readSubject(store, deviceId) {
2459
2517
  const configKey = verifiedLocalKeyId(store.db, store.deviceId);
2460
2518
  if (deviceId === store.deviceId) return {
@@ -2465,7 +2523,7 @@ function readSubject(store, deviceId) {
2465
2523
  error: "local_identity_unverified",
2466
2524
  status: 409
2467
2525
  };
2468
- const pin = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
2526
+ const pin = readPin$1(store, deviceId);
2469
2527
  const key = pin?.public_key;
2470
2528
  if (key && canonicalKeyId(key) === configKey) return {
2471
2529
  error: "cannot_remove_this_device",
@@ -2561,6 +2619,24 @@ function hasNoRemovalCoordinator(readConfig) {
2561
2619
  if (url !== void 0 && typeof url !== "string") return false;
2562
2620
  return !readCoordinatorSyncConfig(data).syncCoordinatorUrl;
2563
2621
  }
2622
+ /**
2623
+ * The pairing's pin, or the last verified pin kept when this device unpaired the device, so
2624
+ * Remove still works after Unpair. The kept pin only identifies the key to remove. It never
2625
+ * authorizes sync.
2626
+ */
2627
+ function readPin(store, deviceId) {
2628
+ const live = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
2629
+ if (live) return live;
2630
+ const kept = readUnpairedPeerPin(store.db, {
2631
+ localDeviceId: store.deviceId,
2632
+ peerDeviceId: deviceId
2633
+ });
2634
+ return kept ? {
2635
+ public_key: kept.publicKey,
2636
+ pinned_fingerprint: kept.pinnedFingerprint,
2637
+ created_at: kept.recordedAt
2638
+ } : void 0;
2639
+ }
2564
2640
  function readLocalRemoval(store, deviceId) {
2565
2641
  if (deviceId === store.deviceId) return {
2566
2642
  error: "cannot_remove_this_device",
@@ -2571,7 +2647,7 @@ function readLocalRemoval(store, deviceId) {
2571
2647
  error: "local_identity_unverified",
2572
2648
  status: 409
2573
2649
  };
2574
- const pin = store.db.prepare("SELECT public_key, pinned_fingerprint, created_at FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
2650
+ const pin = readPin(store, deviceId);
2575
2651
  if (!pin) return {
2576
2652
  error: "removal_target_not_enrolled",
2577
2653
  status: 404
@@ -3068,7 +3144,7 @@ function removedDeviceBlockRoutes(options) {
3068
3144
  //#endregion
3069
3145
  //#region src/routes/device-rejoin-events.ts
3070
3146
  var PATH = "/api/sync/devices/rejoin-events";
3071
- var HASH$1 = /^[a-f0-9]{64}$/u;
3147
+ var HASH = /^[a-f0-9]{64}$/u;
3072
3148
  function captureTarget(options) {
3073
3149
  const config = (options.readConfig ?? readCoordinatorSyncConfig)();
3074
3150
  const origin = normalizeCoordinatorAccountLinkOrigin(config.syncCoordinatorUrl);
@@ -3101,7 +3177,7 @@ function isCurrentTarget(options, target) {
3101
3177
  function input(query) {
3102
3178
  const [scope] = query.getAll("scope");
3103
3179
  const [after] = query.getAll("after");
3104
- if ([...query.keys()].some((key) => key !== "scope" && key !== "after") || query.getAll("scope").length > 1 || query.getAll("after").length > 1 || scope !== void 0 && !HASH$1.test(scope) || after !== void 0 && (!scope || !after.trim() || after.length > 256)) return null;
3180
+ if ([...query.keys()].some((key) => key !== "scope" && key !== "after") || query.getAll("scope").length > 1 || query.getAll("after").length > 1 || scope !== void 0 && !HASH.test(scope) || after !== void 0 && (!scope || !after.trim() || after.length > 256)) return null;
3105
3181
  return {
3106
3182
  scope,
3107
3183
  after
@@ -3151,7 +3227,7 @@ function deviceRejoinEventRoutes(options) {
3151
3227
  }
3152
3228
  //#endregion
3153
3229
  //#region src/routes/device-removal-commit.ts
3154
- var REFUSAL_STATUS = {
3230
+ var REFUSAL_STATUS$1 = {
3155
3231
  invalid_input: 400,
3156
3232
  cannot_remove_this_device: 400,
3157
3233
  coordinator_admin_required: 409,
@@ -3197,7 +3273,7 @@ async function commitRemove(c, options) {
3197
3273
  },
3198
3274
  ...options.createDeviceRemovalRefreshHooks()
3199
3275
  });
3200
- if (result.kind === "rejected") return c.json({ error: result.error }, REFUSAL_STATUS[result.error]);
3276
+ if (result.kind === "rejected") return c.json({ error: result.error }, REFUSAL_STATUS$1[result.error]);
3201
3277
  if (result.kind === "unknown") return c.json({ error: result.error }, 502);
3202
3278
  return c.json({
3203
3279
  state: "removed",
@@ -7010,6 +7086,60 @@ function snapshotPageRequest(query, localDeviceId) {
7010
7086
  };
7011
7087
  }
7012
7088
  //#endregion
7089
+ //#region src/sync-server-mode.ts
7090
+ var PLAIN_DIRECT_MODE = Object.freeze({ kind: "plain-direct" });
7091
+ function canonicalPin(publicKey) {
7092
+ const [algorithm, blob] = publicKey.split(/\s+/);
7093
+ return algorithm === "ssh-ed25519" && blob ? `${algorithm} ${blob}` : null;
7094
+ }
7095
+ function bindsKey(pin, publicKey) {
7096
+ const expected = canonicalPin(publicKey);
7097
+ return !!pin && !!expected && pin === expected;
7098
+ }
7099
+ function channelBinding(mode) {
7100
+ if (mode.kind === "plain-direct") return void 0;
7101
+ return (request, deviceId, publicKey) => {
7102
+ if (!request || request.signal.aborted) return false;
7103
+ try {
7104
+ if (mode.kind === "relay") return bindsKey(mode.peerPin(request), publicKey);
7105
+ const peer = mode.peer(request);
7106
+ return !!peer && peer.deviceId === deviceId && bindsKey(peer.pin, publicKey);
7107
+ } catch {
7108
+ return false;
7109
+ }
7110
+ };
7111
+ }
7112
+ /** Relay requests must name a scope. The default stream is never served there. */
7113
+ function requiresScope(mode) {
7114
+ return mode.kind === "relay";
7115
+ }
7116
+ /**
7117
+ * Largest single pull entry a channel response can carry. Undefined for the
7118
+ * plain listener, which has no response ceiling and keeps sending any size.
7119
+ */
7120
+ function entryByteLimit(mode) {
7121
+ if (mode.kind === "plain-direct") return void 0;
7122
+ return mode.maxEntryBytes ?? CHANNEL_MAX_ENTRY_BYTES;
7123
+ }
7124
+ var CHANNEL_ROUTES = /* @__PURE__ */ new Set([
7125
+ "GET /v1/status",
7126
+ "GET /v1/snapshot",
7127
+ "GET /v1/ops",
7128
+ "POST /v1/ops"
7129
+ ]);
7130
+ /** Channels serve the peer protocol only. The plain listener keeps its own 404 for the rest. */
7131
+ function channelRouteAllowed(mode, method, path) {
7132
+ return mode.kind === "plain-direct" || CHANNEL_ROUTES.has(`${method} ${path}`);
7133
+ }
7134
+ /**
7135
+ * Whether the plain listener runs with direct Noise on. Then a bootstrap grant
7136
+ * authorizes only status, and an unmarked grant status from a worker known to
7137
+ * speak Noise is refused. Channels never accept grants at all.
7138
+ */
7139
+ function noiseActive(mode) {
7140
+ return mode.kind === "plain-direct" && (mode.noiseActive ?? DIRECT_NOISE_ACTIVE);
7141
+ }
7142
+ //#endregion
7013
7143
  //#region src/routes/device-rejoin-evidence.ts
7014
7144
  function localPins(store) {
7015
7145
  const rows = store.db.prepare(`SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers
@@ -7065,212 +7195,6 @@ async function readInventoryWithRejoinEvidence(store, input, readConfig = readCo
7065
7195
  return inventory();
7066
7196
  }
7067
7197
  }
7068
- //#endregion
7069
- //#region src/routes/device-retire.ts
7070
- var HASH = /^[a-f0-9]{64}$/;
7071
- function coordinatorCredentials(config) {
7072
- const remoteUrl = config.syncCoordinatorUrl.trim();
7073
- const adminSecret = config.syncCoordinatorAdminSecret.trim();
7074
- return remoteUrl && adminSecret ? {
7075
- remoteUrl,
7076
- adminSecret
7077
- } : null;
7078
- }
7079
- /** Maps revocation client failures to messages Devices can act on. */
7080
- function revocationFailure(error) {
7081
- let code = error instanceof Error ? error.message : "";
7082
- if (error instanceof RemoteCoordinatorRequestError) code = error.code;
7083
- if (code === "revocation_preview_stale") return {
7084
- error: "retire_preview_stale",
7085
- status: 409
7086
- };
7087
- if (code === "revocation_target_unavailable") return {
7088
- error: "retire_target_unavailable",
7089
- status: 409
7090
- };
7091
- if (code === "revocation_outcome_unknown") return {
7092
- error: "retire_outcome_unknown",
7093
- status: 502
7094
- };
7095
- return {
7096
- error: "retire_unavailable",
7097
- status: 503
7098
- };
7099
- }
7100
- function fail(c, failure) {
7101
- return c.json({ error: failure.error }, failure.status);
7102
- }
7103
- var TARGET_FAILURES = {
7104
- device_not_enrolled: {
7105
- error: "device_not_enrolled",
7106
- status: 404
7107
- },
7108
- cannot_retire_this_device: {
7109
- error: "cannot_retire_this_device",
7110
- status: 400
7111
- },
7112
- device_already_retired: {
7113
- error: "device_already_retired",
7114
- status: 409
7115
- },
7116
- device_enrollment_conflict: {
7117
- error: "device_enrollment_conflict",
7118
- status: 409
7119
- },
7120
- device_evidence_incomplete: {
7121
- error: "coordinator_evidence_too_large",
7122
- status: 503
7123
- },
7124
- device_key_unrecognized: {
7125
- error: "device_key_unrecognized",
7126
- status: 409
7127
- },
7128
- local_identity_unverified: {
7129
- error: "local_identity_unverified",
7130
- status: 409
7131
- }
7132
- };
7133
- /** The device's whole alias group and its revocation evidence, read fresh from the coordinator. */
7134
- async function resolveTarget(config, store, deviceId) {
7135
- let enrollments;
7136
- try {
7137
- enrollments = await listAllEnrollments(config, { includeArchived: true });
7138
- } catch (error) {
7139
- const code = error instanceof Error ? error.message : "";
7140
- if (code === "coordinator_evidence_too_large") return {
7141
- error: code,
7142
- status: 503
7143
- };
7144
- return {
7145
- error: "retire_unavailable",
7146
- status: 503
7147
- };
7148
- }
7149
- const target = resolveRetireTarget(store.db, {
7150
- localDeviceId: store.deviceId,
7151
- enrollments,
7152
- deviceId
7153
- });
7154
- return typeof target === "string" ? TARGET_FAILURES[target] : target;
7155
- }
7156
- function retireTarget(c) {
7157
- const deviceId = String(c.req.param("device_id") ?? "").trim();
7158
- if (!deviceId) return {
7159
- error: "device_id_required",
7160
- status: 400
7161
- };
7162
- return deviceId;
7163
- }
7164
- async function previewRetire(c, store) {
7165
- const deviceId = retireTarget(c);
7166
- if (typeof deviceId !== "string") return fail(c, deviceId);
7167
- const config = readCoordinatorSyncConfig();
7168
- const credentials = coordinatorCredentials(config);
7169
- if (!credentials) return fail(c, {
7170
- error: "coordinator_admin_required",
7171
- status: 409
7172
- });
7173
- const target = await resolveTarget(config, store, deviceId);
7174
- if ("error" in target) return fail(c, target);
7175
- try {
7176
- const preview = await coordinatorRevokeDeviceAction({
7177
- ...credentials,
7178
- groupId: target.groupId,
7179
- deviceId: target.enrollmentDeviceId
7180
- });
7181
- if (preview.state !== "ready") return fail(c, {
7182
- error: "retire_unavailable",
7183
- status: 503
7184
- });
7185
- if (preview.key_id !== target.keyId) return fail(c, {
7186
- error: "device_enrollment_conflict",
7187
- status: 409
7188
- });
7189
- return c.json({
7190
- device_id: deviceId,
7191
- display_name: target.displayName,
7192
- enrollment_device_id: target.enrollmentDeviceId,
7193
- alias_device_ids: target.aliasDeviceIds,
7194
- group_id: target.groupId,
7195
- coordinator_id: preview.coordinator_id,
7196
- key_id: preview.key_id,
7197
- expected_digest: preview.expected_digest
7198
- });
7199
- } catch (error) {
7200
- return fail(c, revocationFailure(error));
7201
- }
7202
- }
7203
- function confirmedPreview(body) {
7204
- const groupId = typeof body.group_id === "string" ? body.group_id : "";
7205
- const enrollmentDeviceId = typeof body.enrollment_device_id === "string" ? body.enrollment_device_id : "";
7206
- const digest = typeof body.expected_digest === "string" ? body.expected_digest : "";
7207
- const coordinatorId = typeof body.coordinator_id === "string" ? body.coordinator_id : "";
7208
- const keyId = typeof body.key_id === "string" ? body.key_id : "";
7209
- if (!groupId || !enrollmentDeviceId || !coordinatorId || !HASH.test(digest) || !HASH.test(keyId)) return null;
7210
- return {
7211
- enrollmentDeviceId,
7212
- revocation: {
7213
- groupId,
7214
- expectedDigest: digest,
7215
- expectedContext: {
7216
- coordinatorId,
7217
- keyId
7218
- }
7219
- }
7220
- };
7221
- }
7222
- async function commitRetire(c, store) {
7223
- const deviceId = retireTarget(c);
7224
- if (typeof deviceId !== "string") return fail(c, deviceId);
7225
- const body = await c.req.json().catch(() => null);
7226
- const confirmed = body ? confirmedPreview(body) : null;
7227
- if (!confirmed) return fail(c, {
7228
- error: "retire_preview_required",
7229
- status: 400
7230
- });
7231
- const config = readCoordinatorSyncConfig();
7232
- const credentials = coordinatorCredentials(config);
7233
- if (!credentials) return fail(c, {
7234
- error: "coordinator_admin_required",
7235
- status: 409
7236
- });
7237
- const target = await resolveTarget(config, store, deviceId);
7238
- if ("error" in target) return fail(c, target);
7239
- if (target.groupId !== confirmed.revocation.groupId || target.enrollmentDeviceId !== confirmed.enrollmentDeviceId || target.keyId !== confirmed.revocation.expectedContext.keyId) return fail(c, {
7240
- error: "retire_preview_stale",
7241
- status: 409
7242
- });
7243
- try {
7244
- if ((await coordinatorRevokeDeviceAction({
7245
- ...credentials,
7246
- ...confirmed.revocation,
7247
- deviceId: target.enrollmentDeviceId
7248
- })).state !== "revoked") return fail(c, {
7249
- error: "retire_outcome_unknown",
7250
- status: 502
7251
- });
7252
- } catch (error) {
7253
- return fail(c, revocationFailure(error));
7254
- }
7255
- const unpaired = retireDeviceLocally(store.db, store.deviceId, target) > 0;
7256
- return c.json({
7257
- state: "retired",
7258
- device_id: deviceId,
7259
- unpaired_here: unpaired
7260
- });
7261
- }
7262
- /**
7263
- * Retires another device: revokes its enrollment's device ID and its key across the
7264
- * coordinator, after a preview the caller confirms by digest, then unpairs every
7265
- * local ID that carries the key.
7266
- */
7267
- function deviceRetireRoutes(getStore) {
7268
- return new Hono().post("/api/sync/devices/:device_id/retire/preview", (c) => previewRetire(c, getStore())).post("/api/sync/devices/:device_id/retire", (c) => commitRetire(c, getStore()));
7269
- }
7270
- /** Rename and retirement routes for one device, mounted together by the sync app. */
7271
- function deviceRoutes(getStore) {
7272
- return new Hono().route("/", deviceRenameRoutes(getStore)).route("/", deviceRetireRoutes(getStore));
7273
- }
7274
7198
  var NOTHING_FAILED = {
7275
7199
  failedGroups: 0,
7276
7200
  skippedGroups: 0,
@@ -7535,6 +7459,25 @@ var FINISH_DIGEST_PATTERN = /^legacy-team-activation-finish-v1:[0-9a-f]{64}$/u;
7535
7459
  var ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-access-delta:[0-9a-f]{64}$/u;
7536
7460
  var VIEWER_ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-viewer-access-delta-v1:[0-9a-f]{64}$/u;
7537
7461
  var activeCandidateMutations = /* @__PURE__ */ new WeakMap();
7462
+ /**
7463
+ * How many operations on each candidate have finished and released its claim. A
7464
+ * background pass compares it with the count it began with, to tell whether
7465
+ * another operation ran on the candidate since.
7466
+ */
7467
+ var candidateMutationRevisions = /* @__PURE__ */ new WeakMap();
7468
+ function candidateMutationRevision(db, candidateRef) {
7469
+ return candidateMutationRevisions.get(db)?.get(candidateRef) ?? 0;
7470
+ }
7471
+ function advanceCandidateMutationRevision(db, candidateRef) {
7472
+ const revisions = candidateMutationRevisions.get(db) ?? /* @__PURE__ */ new Map();
7473
+ candidateMutationRevisions.set(db, revisions);
7474
+ revisions.set(candidateRef, (revisions.get(candidateRef) ?? 0) + 1);
7475
+ }
7476
+ /**
7477
+ * Claims the candidate for one access-changing operation, or returns null when
7478
+ * another holds it. Draft and finish routes, Team recovery and each background
7479
+ * reconciliation pass take it, so none of them runs across another.
7480
+ */
7538
7481
  function claimCandidateMutation(db, candidateRef) {
7539
7482
  let active = activeCandidateMutations.get(db);
7540
7483
  if (!active) {
@@ -7552,6 +7495,7 @@ function claimCandidateMutation(db, candidateRef) {
7552
7495
  if (released) return;
7553
7496
  released = true;
7554
7497
  active?.delete(candidateRef);
7498
+ advanceCandidateMutationRevision(db, candidateRef);
7555
7499
  settle();
7556
7500
  };
7557
7501
  }
@@ -7559,15 +7503,42 @@ function claimCandidateMutation(db, candidateRef) {
7559
7503
  function candidateMutationSettled(db, candidateRef) {
7560
7504
  return activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();
7561
7505
  }
7506
+ var candidatePass = new AsyncLocalStorage();
7507
+ function beginCandidatePass(db) {
7508
+ return {
7509
+ skipped: /* @__PURE__ */ new Set(),
7510
+ revisions: new Map(candidateMutationRevisions.get(db))
7511
+ };
7512
+ }
7513
+ /** Whether no other operation holds the candidate or has run on it since the pass began. */
7514
+ function isUntouchedSince(db, pass, candidateRef) {
7515
+ return !activeCandidateMutations.get(db)?.has(candidateRef) && candidateMutationRevision(db, candidateRef) === (pass.revisions.get(candidateRef) ?? 0);
7516
+ }
7562
7517
  /**
7563
- * Candidates whose mutation a background pass skipped because a draft or finish
7564
- * route held the claim. The pass retries them instead of reporting a failure.
7518
+ * Claims the candidate for a write of a background pass, or returns null when
7519
+ * another operation holds it or has run on it since the pass began. What the
7520
+ * pass read from the coordinator may be older than that operation, for example
7521
+ * a list of completions taken while a setup was finishing, so the pass must not
7522
+ * act on it once the setup lets go.
7565
7523
  */
7566
- var skippedCandidateMutations = new AsyncLocalStorage();
7567
- async function runCandidateMutation(db, candidateRef, operation) {
7524
+ function claimForCandidatePass(db, pass, candidateRef) {
7525
+ const untouched = isUntouchedSince(db, pass, candidateRef);
7568
7526
  const release = claimCandidateMutation(db, candidateRef);
7527
+ if (!release) return null;
7528
+ if (!untouched) {
7529
+ release();
7530
+ return null;
7531
+ }
7532
+ return () => {
7533
+ release();
7534
+ pass.revisions.set(candidateRef, candidateMutationRevision(db, candidateRef));
7535
+ };
7536
+ }
7537
+ async function runCandidateMutation(db, candidateRef, operation) {
7538
+ const pass = candidatePass.getStore();
7539
+ const release = pass ? claimForCandidatePass(db, pass, candidateRef) : claimCandidateMutation(db, candidateRef);
7569
7540
  if (!release) {
7570
- skippedCandidateMutations.getStore()?.add(candidateRef);
7541
+ pass?.skipped.add(candidateRef);
7571
7542
  return false;
7572
7543
  }
7573
7544
  try {
@@ -7664,17 +7635,29 @@ function summaryReconciliationOptions(blockingErrors) {
7664
7635
  * the lookup is reported unavailable, which keeps every pairing.
7665
7636
  */
7666
7637
  async function lookupPeerRemovalsAsDaemon(store, config) {
7638
+ const identity = daemonSigningIdentity(store);
7639
+ if (!identity) return unavailablePeerRemovalLookup();
7640
+ return fetchPeerRemovalLookup(store, config, identity);
7641
+ }
7642
+ /**
7643
+ * The identity the sync daemon signs coordinator requests with: this store's
7644
+ * one device, and its keys in the directory `CODEMEM_KEYS_DIR` names or the
7645
+ * default one. Null when the store has no single device or its key is not
7646
+ * usable. Nothing here creates or repairs a key.
7647
+ */
7648
+ function daemonSigningIdentity(store) {
7667
7649
  const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
7668
7650
  const rows = store.db.prepare("SELECT device_id FROM sync_device LIMIT 2").pluck().all();
7669
7651
  const localDeviceId = rows.length === 1 && typeof rows[0] === "string" ? rows[0] : null;
7670
- if (!localDeviceId || !loadRuntimeSigningPublicKey(store.db, {
7652
+ if (!localDeviceId) return null;
7653
+ if (!loadRuntimeSigningPublicKey(store.db, {
7671
7654
  deviceId: localDeviceId,
7672
7655
  keysDir
7673
- })) return unavailablePeerRemovalLookup();
7674
- return fetchPeerRemovalLookup(store, config, {
7656
+ })) return null;
7657
+ return {
7675
7658
  localDeviceId,
7676
7659
  keysDir
7677
- });
7660
+ };
7678
7661
  }
7679
7662
  function unavailablePeerRemovalLookup() {
7680
7663
  return {
@@ -7821,18 +7804,6 @@ function configuredGroupIds$1(groups) {
7821
7804
  if (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();
7822
7805
  return unique;
7823
7806
  }
7824
- function normalizedCoordinatorId(value) {
7825
- try {
7826
- const normalized = buildBaseUrl(value);
7827
- if (!normalized) return null;
7828
- const parsed = new URL(normalized);
7829
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !parsed.host || parsed.username || parsed.password) return null;
7830
- const path = parsed.pathname === "/" ? "" : parsed.pathname;
7831
- return `${parsed.protocol}//${parsed.host}${path}${parsed.search}`;
7832
- } catch {
7833
- return null;
7834
- }
7835
- }
7836
7807
  function legacyTeamCandidateGroupDescriptors(store, coordinatorUrl, groups) {
7837
7808
  const configuredIds = configuredGroupIds$1(groups);
7838
7809
  const configuredCoordinatorId = buildBaseUrl(coordinatorUrl);
@@ -8073,13 +8044,17 @@ var TEAM_SETUP_RECONCILIATION_JOB = "team_setup_reconciliation";
8073
8044
  * under the candidate claim, and none runs on a cached roster or after a failed
8074
8045
  * removal read.
8075
8046
  */
8076
- async function runSummaryReconciliation(store, dependencies, previous) {
8047
+ function runSummaryReconciliation(store, dependencies, previous) {
8048
+ const pass = beginCandidatePass(store.db);
8049
+ return candidatePass.run(pass, () => reconcileSummaryGroups(store, dependencies, previous, pass));
8050
+ }
8051
+ async function reconcileSummaryGroups(store, dependencies, previous, pass) {
8052
+ const { skipped } = pass;
8077
8053
  dependencies.loadSnapshots.invalidate();
8078
- const groups = await dependencies.loadSnapshots();
8079
- requireBoundedSnapshots(groups);
8080
- await Promise.all(groups.map((group) => candidateMutationSettled(store.db, summaryCandidateRef(group))));
8054
+ const configured = await dependencies.loadSnapshots();
8055
+ requireBoundedSnapshots(configured);
8056
+ const groups = openSummaryGroups(store, configured, pass);
8081
8057
  const blockers = /* @__PURE__ */ new Map();
8082
- const skipped = /* @__PURE__ */ new Set();
8083
8058
  const views = /* @__PURE__ */ new Map();
8084
8059
  for (const group of groups) {
8085
8060
  if (!hasNoLocalSetup(store, summaryCandidateRef(group))) continue;
@@ -8088,7 +8063,7 @@ async function runSummaryReconciliation(store, dependencies, previous) {
8088
8063
  skipped
8089
8064
  });
8090
8065
  }
8091
- await skippedCandidateMutations.run(skipped, () => dependencies.reconcile(store, groups, summaryReconciliationOptions(blockers)));
8066
+ await dependencies.reconcile(store, groups, summaryReconciliationOptions(blockers));
8092
8067
  for (const group of groups) {
8093
8068
  const candidateRef = summaryCandidateRef(group);
8094
8069
  if (blockers.has(candidateRef) || skipped.has(candidateRef) || views.has(candidateRef)) continue;
@@ -8105,12 +8080,21 @@ async function runSummaryReconciliation(store, dependencies, previous) {
8105
8080
  }, () => removals ? applyRemovalsBeforeRepair(store, group, removals) : true);
8106
8081
  }
8107
8082
  return carrySkippedGroups({
8108
- groups,
8083
+ groups: configured,
8109
8084
  views,
8110
8085
  blockers,
8111
8086
  skipped
8112
8087
  }, previous);
8113
8088
  }
8089
+ /** The groups a pass goes on with. One another operation holds or ran on is marked skipped. */
8090
+ function openSummaryGroups(store, groups, pass) {
8091
+ return groups.filter((group) => {
8092
+ const candidateRef = summaryCandidateRef(group);
8093
+ if (isUntouchedSince(store.db, pass, candidateRef)) return true;
8094
+ pass.skipped.add(candidateRef);
8095
+ return false;
8096
+ });
8097
+ }
8114
8098
  /**
8115
8099
  * Whether rediscovering this candidate can restore setup recipients: core repairs
8116
8100
  * them only for the setup's Team while it is active, so this is the same check.
@@ -8257,6 +8241,57 @@ function summaryResponse(store, read) {
8257
8241
  reconciliation: read.status
8258
8242
  };
8259
8243
  }
8244
+ /** The summary, with what only an admin device is told. */
8245
+ function summaryForDevice(options, read) {
8246
+ const store = options.getStore();
8247
+ const summary = summaryResponse(store, read);
8248
+ if ("error" in summary) return summary;
8249
+ return withRecoverableTeams(store, summary, currentCompletionAuthorization(options));
8250
+ }
8251
+ /** What this device's configuration lets it read as a coordinator admin now, or null for nothing. */
8252
+ function currentCompletionAuthorization(options) {
8253
+ try {
8254
+ return readCompletionAuthorization(options);
8255
+ } catch {
8256
+ return null;
8257
+ }
8258
+ }
8259
+ /**
8260
+ * Names, for an admin device, the Team each candidate's recovery would restore:
8261
+ * the Team its setup completed, while that Team is disabled or a recovery of it
8262
+ * was saved and never confirmed, and only while the setup's coordinator and
8263
+ * group are the configured ones. Local reads only.
8264
+ */
8265
+ function withRecoverableTeams(store, summary, authorization) {
8266
+ if (!authorization) return summary;
8267
+ const disabled = store.db.prepare(`SELECT 1 FROM policy_teams WHERE team_id = ? AND status = 'inactive'
8268
+ AND migration_state = 'needs_setup' AND provenance = 'reviewed_team_candidate'`).pluck();
8269
+ const candidates = summary.candidates.map((candidate) => {
8270
+ const teamId = deterministicPolicyTeamId(candidate.candidateRef);
8271
+ const target = disabled.get(teamId) || isRecoveryUnconfirmed(store, candidate.candidateRef) ? teamRecoveryTarget(store.db, teamId) : null;
8272
+ return target !== null && authorizesGroup(authorization, target) ? {
8273
+ ...candidate,
8274
+ recoverableTeamId: teamId
8275
+ } : candidate;
8276
+ });
8277
+ return {
8278
+ ...summary,
8279
+ candidates
8280
+ };
8281
+ }
8282
+ var RECOVERY_UNCONFIRMED = {
8283
+ code: "team_setup_completion_unavailable",
8284
+ reason: "team_recovery_unconfirmed"
8285
+ };
8286
+ /**
8287
+ * Whether the candidate's Team is active with a recovery that was saved and
8288
+ * never confirmed. Such a Team is on hold and shares nothing until another
8289
+ * recovery is confirmed. A recovery this process is still confirming does not count.
8290
+ */
8291
+ function isRecoveryUnconfirmed(store, candidateRef) {
8292
+ const teamId = deterministicPolicyTeamId(candidateRef);
8293
+ return hasCompletedLegacyTeamSetup(store, candidateRef) && isTeamRecoveryHoldAbandoned(store.db, teamId, Date.now());
8294
+ }
8260
8295
  /**
8261
8296
  * The candidates the last pass found, with local drafts read again so edits show
8262
8297
  * at once. Reads only: discovery, which can write drafts and access, runs in the pass.
@@ -8266,6 +8301,7 @@ function checkedCandidateSummaries(store, result) {
8266
8301
  const candidateRef = summaryCandidateRef(group);
8267
8302
  const blocker = result.blockers.get(candidateRef);
8268
8303
  if (blocker) return [blockedCandidateSummary(store, group, blocker)];
8304
+ if (isRecoveryUnconfirmed(store, candidateRef)) return [blockedCandidateSummary(store, group, RECOVERY_UNCONFIRMED)];
8269
8305
  if (hasCompletedLegacyTeamSetup(store, candidateRef)) return [];
8270
8306
  const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
8271
8307
  const view = draft && draft.state !== "completed" ? candidateFromDraft(draft) : result.views.get(candidateRef);
@@ -9582,7 +9618,7 @@ function teamSetupRoutes(options) {
9582
9618
  }
9583
9619
  app.get("/api/sync/team-setup/v1", (c) => {
9584
9620
  try {
9585
- const summary = summaryResponse(options.getStore(), reconciliation.read());
9621
+ const summary = summaryForDevice(options, reconciliation.read());
9586
9622
  return "error" in summary ? c.json(summary, errorStatus$1(summary.error)) : c.json(summary);
9587
9623
  } catch (error) {
9588
9624
  const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
@@ -10148,7 +10184,31 @@ function tryParsePairingPayload(value) {
10148
10184
  device_id: deviceId,
10149
10185
  fingerprint,
10150
10186
  public_key: publicKey,
10151
- addresses
10187
+ addresses,
10188
+ payload: parsed
10189
+ };
10190
+ }
10191
+ /** Pins the payload's key and records what the payload says about Noise, together. */
10192
+ function savePairingPayload(store, pairing) {
10193
+ store.db.transaction(() => {
10194
+ updatePeerAddresses(store.db, pairing.device_id, pairing.addresses, {
10195
+ pinnedFingerprint: pairing.fingerprint,
10196
+ publicKey: pairing.public_key,
10197
+ replaceTrust: true
10198
+ });
10199
+ recordPairingTransportEvidence(store.db, pairing.device_id, pairing.payload);
10200
+ })();
10201
+ }
10202
+ /** The shared pairing payload plus the viewer's filter hint. */
10203
+ function pairingPayloadBody(input) {
10204
+ return {
10205
+ ...buildPairingPayload({
10206
+ deviceId: input.deviceId,
10207
+ fingerprint: input.fingerprint,
10208
+ publicKey: input.publicKey ?? "",
10209
+ addresses: pairingAdvertiseAddresses(input.config)
10210
+ }),
10211
+ pairing_filter_hint: PAIRING_FILTER_HINT
10152
10212
  };
10153
10213
  }
10154
10214
  async function inspectPairingInvite(c, next) {
@@ -10698,15 +10758,30 @@ function recipientPolicyCapabilityFromStatus(payload) {
10698
10758
  if (!isScopedSyncCapability(normalizeSyncCapability(payload.sync_capability))) return "unsupported";
10699
10759
  return supportsSyncFeature(payload.sync_features, "reassign_scope") ? "supported" : "unsupported";
10700
10760
  }
10761
+ /** The probe reaches the peer through the shared transport policy, like a sync pass. */
10762
+ function peerStatusExecutor(store, peerDeviceId, localDeviceId) {
10763
+ const execute = peerTransportExecutor({
10764
+ db: store.db,
10765
+ peerDeviceId,
10766
+ localDeviceId,
10767
+ dbPath: store.dbPath,
10768
+ keysDir: syncKeysDir()
10769
+ });
10770
+ return (url, headers) => execute("GET", url, {
10771
+ operation: "status",
10772
+ headers,
10773
+ timeoutS: 5
10774
+ });
10775
+ }
10701
10776
  async function peerSupportsSyncRequirements(store, deviceId, requirements) {
10702
10777
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
10703
10778
  if (deviceId === localDeviceId) return "supported";
10704
10779
  const row = store.db.prepare("SELECT addresses_json, pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
10705
10780
  const expectedFingerprint = String(row?.pinned_fingerprint ?? "").trim() || (row?.public_key ? fingerprintPublicKey(row.public_key) : "");
10706
- const addresses = safeJsonList(row?.addresses_json ?? null);
10707
- for (const address of addresses) try {
10781
+ const execute = peerStatusExecutor(store, deviceId, localDeviceId);
10782
+ for (const address of safeJsonList(row?.addresses_json ?? null)) try {
10708
10783
  const url = `${buildBaseUrl(address)}/v1/status`;
10709
- const headers = {
10784
+ const [status, payload] = await execute(url, {
10710
10785
  ...buildDirectPeerAuthHeaders({
10711
10786
  deviceId: localDeviceId,
10712
10787
  recipientId: deviceId,
@@ -10718,10 +10793,6 @@ async function peerSupportsSyncRequirements(store, deviceId, requirements) {
10718
10793
  }),
10719
10794
  [SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,
10720
10795
  [SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(",")
10721
- };
10722
- const [status, payload] = await requestJson("GET", url, {
10723
- headers,
10724
- timeoutS: 5
10725
10796
  });
10726
10797
  if (status < 200 || status >= 300) continue;
10727
10798
  if (String(payload?.device_id ?? "").trim() !== deviceId) continue;
@@ -11357,6 +11428,22 @@ async function loadAllGroupsDeviceIdentityCoordinatorEvidence(options = {}) {
11357
11428
  return unavailable("coordinator_unavailable");
11358
11429
  }
11359
11430
  }
11431
+ /** Group IDs may hold any text, so lists are compared entry by entry. */
11432
+ function sameGroups(current, fetched) {
11433
+ return current.length === fetched.length && current.every((group, i) => group === fetched[i]);
11434
+ }
11435
+ /**
11436
+ * Whether the coordinator, groups and admin secret are still the ones the evidence
11437
+ * was fetched with. The fetch can outlast a change, so the write checks this.
11438
+ */
11439
+ function sameCoordinatorAuthority(readConfig, fetchedWith) {
11440
+ try {
11441
+ const current = readConfig();
11442
+ return current.syncCoordinatorUrl === fetchedWith.syncCoordinatorUrl && current.syncCoordinatorAdminSecret === fetchedWith.syncCoordinatorAdminSecret && sameGroups(current.syncCoordinatorGroups, fetchedWith.syncCoordinatorGroups);
11443
+ } catch {
11444
+ return false;
11445
+ }
11446
+ }
11360
11447
  /**
11361
11448
  * Runs the one-time conversion of the person assigned on pairings into Identity
11362
11449
  * bindings. It runs after enrollment reconciliation, so a binding the coordinator
@@ -11369,13 +11456,17 @@ async function convertLegacyPairingAssignmentsOperation(store, options = {}) {
11369
11456
  status: "already_converted",
11370
11457
  waitingReason: null
11371
11458
  };
11372
- const coordinator = await (options.loadCoordinatorEvidence ?? loadAllGroupsDeviceIdentityCoordinatorEvidence)();
11459
+ const readConfig = options.readConfig ?? readCoordinatorSyncConfig;
11460
+ const load = options.loadCoordinatorEvidence ?? ((config) => loadAllGroupsDeviceIdentityCoordinatorEvidence({ config }));
11461
+ const fetchedWith = readConfig();
11462
+ const coordinator = await load(fetchedWith);
11373
11463
  try {
11374
11464
  const { status, waitingReason } = convertLegacyPairingAssignments(store.db, {
11375
11465
  localActorId: store.actorId,
11376
11466
  localDeviceId: store.deviceId,
11377
11467
  coordinator,
11378
- ensureLocalIdentity: () => ensureLocalActorRecord(store)
11468
+ ensureLocalIdentity: () => ensureLocalActorRecord(store),
11469
+ authorityStillHolds: () => sameCoordinatorAuthority(readConfig, fetchedWith)
11379
11470
  });
11380
11471
  return {
11381
11472
  status,
@@ -11929,16 +12020,6 @@ function recordDirectPeerSignatureVersion(store, deviceId, version) {
11929
12020
  throw err;
11930
12021
  }
11931
12022
  }
11932
- function matchesSyncChannelPeer(request, publicKey, readPin) {
11933
- if (!request || request.signal.aborted) return false;
11934
- try {
11935
- const [algorithm, blob] = publicKey.split(/\s+/);
11936
- const pin = readPin(request);
11937
- return algorithm === "ssh-ed25519" && !!blob && !!pin && pin === `${algorithm} ${blob}`;
11938
- } catch {
11939
- return false;
11940
- }
11941
- }
11942
12023
  function checkedCurrentPeerKey(store, deviceId) {
11943
12024
  const peerRow = store.db.prepare(`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,
11944
12025
  sync_peer_signature_state.highest_observed_direct_signature_version
@@ -11968,7 +12049,19 @@ function checkedCurrentPeerKey(store, deviceId) {
11968
12049
  highestObservedVersion: peerRow.highest_observed_direct_signature_version
11969
12050
  };
11970
12051
  }
11971
- function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
12052
+ function plaintextTransportGate(mode) {
12053
+ if (!noiseActive(mode)) return void 0;
12054
+ return (store, deviceId, request) => !marksNoiseStatusTarget(request) && readPeerTransportPolicy(store.db, deviceId) === "noise_required";
12055
+ }
12056
+ /**
12057
+ * A status request marked transport=noise1 inside its signed target. A grant
12058
+ * worker needs this one plaintext answer, the pin only, before Noise can admit it.
12059
+ */
12060
+ function marksNoiseStatusTarget(request) {
12061
+ const url = new URL(request.url, "http://sync.invalid");
12062
+ return request.method === "GET" && url.pathname === "/v1/status" && url.searchParams.get("transport") === "noise1";
12063
+ }
12064
+ function authorizeSyncRequest(store, request, body, binding, transportGate) {
11972
12065
  const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
11973
12066
  const signature = request.header("X-Opencode-Signature") ?? "";
11974
12067
  const timestamp = request.header("X-Opencode-Timestamp") ?? "";
@@ -11981,7 +12074,7 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
11981
12074
  const peer = checkedCurrentPeerKey(store, deviceId);
11982
12075
  if (!peer.ok) return peer;
11983
12076
  const { publicKey } = peer;
11984
- if (syncChannelPeerPin !== void 0 && !matchesSyncChannelPeer(request.raw, publicKey, syncChannelPeerPin)) return {
12077
+ if (binding !== void 0 && !binding(request.raw, deviceId, publicKey)) return {
11985
12078
  ok: false,
11986
12079
  reason: "channel_binding_mismatch",
11987
12080
  deviceId
@@ -11994,7 +12087,7 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
11994
12087
  publicKey,
11995
12088
  expectedRecipientId: localDeviceId,
11996
12089
  highestObservedVersion: peer.highestObservedVersion,
11997
- requireDirectSignature: syncChannelPeerPin !== void 0
12090
+ requireDirectSignature: binding !== void 0
11998
12091
  });
11999
12092
  } catch {
12000
12093
  return {
@@ -12008,14 +12101,48 @@ function authorizeSyncRequest(store, request, body, syncChannelPeerPin) {
12008
12101
  reason: verification.reason,
12009
12102
  deviceId
12010
12103
  };
12104
+ if (transportGate?.(store, deviceId, request)) return {
12105
+ ok: false,
12106
+ reason: "transport_downgrade_refused",
12107
+ deviceId
12108
+ };
12011
12109
  const nonceResult = recordSyncAuthNonce(store, deviceId, nonce, (/* @__PURE__ */ new Date()).toISOString());
12012
12110
  if (nonceResult) return nonceResult;
12013
- if (verification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {
12014
- const versionResult = recordDirectPeerSignatureVersion(store, deviceId, verification.version);
12015
- if (versionResult) return versionResult;
12016
- }
12111
+ const versionResult = recordAdoptedSignatureVersion(store, deviceId, verification, binding);
12112
+ if (versionResult) return versionResult;
12017
12113
  return authenticatedSyncPeer(deviceId, publicKey);
12018
12114
  }
12115
+ /** Records that the peer now signs with v3, unless the binding defers that to later traffic. */
12116
+ function recordAdoptedSignatureVersion(store, deviceId, verification, binding) {
12117
+ if (verification.version !== DIRECT_PEER_SIGNATURE_VERSION_NUMBER) return null;
12118
+ if (binding?.deferSignatureAdoption) return null;
12119
+ return recordDirectPeerSignatureVersion(store, deviceId, verification.version);
12120
+ }
12121
+ /**
12122
+ * No channel exists before the upgrade, so the only binding demanded is the v3
12123
+ * signature. Its adoption is recorded later, by the authenticated inner traffic.
12124
+ */
12125
+ var REQUIRE_DIRECT_SIGNATURE = Object.assign(() => true, { deferSignatureAdoption: true });
12126
+ /**
12127
+ * Authorizes a direct Noise upgrade before any Noise byte is sent: a pinned
12128
+ * device, its current key, a fresh nonce, and a recipient-bound v3 signature
12129
+ * over the exact target. Bootstrap grants are never accepted here.
12130
+ */
12131
+ function authorizeDirectNoiseUpgrade(store, request) {
12132
+ const auth = authorizeSyncRequest(store, request, Buffer.alloc(0), REQUIRE_DIRECT_SIGNATURE);
12133
+ if (!auth.ok) {
12134
+ logDirectPeerAuthDiagnostic(auth.reason);
12135
+ return {
12136
+ ok: false,
12137
+ busy: isSyncAuthStoreBusy(auth)
12138
+ };
12139
+ }
12140
+ return {
12141
+ ok: true,
12142
+ deviceId: auth.deviceId,
12143
+ publicKey: auth.authenticatedPeerSigningKey
12144
+ };
12145
+ }
12019
12146
  function bootstrapPayloadRecord(value) {
12020
12147
  return value !== null && typeof value === "object" && !Array.isArray(value);
12021
12148
  }
@@ -12073,6 +12200,34 @@ function bootstrapGrantFailureReason(store, verification, request) {
12073
12200
  if (scopeId !== void 0 && !isBootstrapGrantGroupScope(store, scopeId, grant, request.config.syncCoordinatorUrl)) return "bootstrap_grant_scope_outside_group";
12074
12201
  return null;
12075
12202
  }
12203
+ /** The coordinator's record of a bootstrap grant, or null when no lookup succeeds. */
12204
+ async function lookupBootstrapGrant(store, config, grantId, localDeviceId) {
12205
+ const base = buildBaseUrl(config.syncCoordinatorUrl);
12206
+ const timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);
12207
+ if (config.syncCoordinatorAdminSecret) {
12208
+ const [status, adminPayload] = await requestJson("GET", `${base}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`, {
12209
+ headers: { "X-Codemem-Coordinator-Admin": config.syncCoordinatorAdminSecret },
12210
+ timeoutS
12211
+ });
12212
+ return status === 200 ? adminPayload : null;
12213
+ }
12214
+ for (const groupId of config.syncCoordinatorGroups) {
12215
+ const lookupUrl = `${base}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;
12216
+ const [status, signedPayload] = await requestJson("GET", lookupUrl, {
12217
+ headers: buildAuthHeaders({
12218
+ deviceId: localDeviceId,
12219
+ dbPath: store.dbPath,
12220
+ method: "GET",
12221
+ url: lookupUrl,
12222
+ bodyBytes: Buffer.alloc(0),
12223
+ keysDir: syncKeysDir()
12224
+ }),
12225
+ timeoutS
12226
+ });
12227
+ if (status === 200) return signedPayload;
12228
+ }
12229
+ return null;
12230
+ }
12076
12231
  async function authorizeBootstrapGrantRequest(store, request, body, options = {}) {
12077
12232
  const grantId = (request.header("X-Codemem-Bootstrap-Grant") ?? "").trim();
12078
12233
  const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
@@ -12094,31 +12249,7 @@ async function authorizeBootstrapGrantRequest(store, request, body, options = {}
12094
12249
  let verification;
12095
12250
  try {
12096
12251
  [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
12097
- let payload = null;
12098
- if (config.syncCoordinatorAdminSecret) {
12099
- const [status, adminPayload] = await requestJson("GET", `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`, {
12100
- headers: { "X-Codemem-Coordinator-Admin": config.syncCoordinatorAdminSecret },
12101
- timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
12102
- });
12103
- if (status === 200) payload = adminPayload;
12104
- } else for (const groupId of config.syncCoordinatorGroups) {
12105
- const lookupUrl = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;
12106
- const [status, signedPayload] = await requestJson("GET", lookupUrl, {
12107
- headers: buildAuthHeaders({
12108
- deviceId: localDeviceId,
12109
- dbPath: store.dbPath,
12110
- method: "GET",
12111
- url: lookupUrl,
12112
- bodyBytes: Buffer.alloc(0),
12113
- keysDir: syncKeysDir()
12114
- }),
12115
- timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
12116
- });
12117
- if (status === 200) {
12118
- payload = signedPayload;
12119
- break;
12120
- }
12121
- }
12252
+ const payload = await lookupBootstrapGrant(store, config, grantId, localDeviceId);
12122
12253
  if (!payload) return {
12123
12254
  ok: false,
12124
12255
  reason: "bootstrap_grant_lookup_failed",
@@ -12178,20 +12309,84 @@ async function authorizeBootstrapGrantRequest(store, request, body, options = {}
12178
12309
  reason: "bootstrap_grant_peer_trust_conflict",
12179
12310
  deviceId
12180
12311
  };
12312
+ if (options.transportGate?.(store, deviceId, request)) return {
12313
+ ok: false,
12314
+ reason: "transport_downgrade_refused",
12315
+ deviceId
12316
+ };
12181
12317
  const nonceResult = recordSyncAuthNonce(store, deviceId, nonce, (/* @__PURE__ */ new Date()).toISOString());
12182
12318
  if (nonceResult) return nonceResult;
12183
- updatePeerAddresses(store.db, deviceId, [], {
12184
- name: workerEnrollment.display_name?.trim() || void 0,
12185
- pinnedFingerprint: workerFingerprint,
12186
- publicKey: workerPublicKey,
12187
- replaceTrust: true
12188
- });
12319
+ pinBootstrapGrantPeer(store.db, deviceId, workerEnrollment);
12189
12320
  if (signatureVerification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {
12190
12321
  const versionResult = recordDirectPeerSignatureVersion(store, deviceId, signatureVerification.version);
12191
12322
  if (versionResult) return versionResult;
12192
12323
  }
12193
12324
  return authenticatedSyncPeer(deviceId, workerPublicKey);
12194
12325
  }
12326
+ /**
12327
+ * The pin names no group, so the coordinator history alone records that a coordinator
12328
+ * vouched for this device. Both are written together, or neither is.
12329
+ */
12330
+ var COORDINATOR_JOIN_CONFIRMATION = {
12331
+ error: COORDINATOR_JOIN_CONFIRMATION_REQUIRED,
12332
+ detail: "Joining a coordinator permanently turns off syncing without a coordinator for this device's key, including other codemem profiles that use the same key."
12333
+ };
12334
+ var COORDINATOR_RECORD_UNVERIFIED = {
12335
+ error: COORDINATOR_FREE_BINDING_UNVERIFIED,
12336
+ detail: "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."
12337
+ };
12338
+ var COORDINATOR_RECORD_UNAVAILABLE = {
12339
+ error: COORDINATOR_FREE_WITNESS_UNAVAILABLE,
12340
+ detail: "codemem couldn't save this device's coordinator record. Unlock or repair the keychain, or make the codemem keys folder writable, then try again."
12341
+ };
12342
+ /** The status and body for a failed invitation import. */
12343
+ function inviteImportFailureResponse(error, invite) {
12344
+ const code = error instanceof Error ? error.message : String(error);
12345
+ if (code === COORDINATOR_JOIN_CONFIRMATION_REQUIRED) return {
12346
+ status: 409,
12347
+ body: COORDINATOR_JOIN_CONFIRMATION
12348
+ };
12349
+ if (code === COORDINATOR_FREE_WITNESS_UNAVAILABLE) return {
12350
+ status: 503,
12351
+ body: COORDINATOR_RECORD_UNAVAILABLE
12352
+ };
12353
+ if (code === COORDINATOR_FREE_BINDING_UNVERIFIED) return {
12354
+ status: 503,
12355
+ body: COORDINATOR_RECORD_UNVERIFIED
12356
+ };
12357
+ if (invite.projectInvite) return {
12358
+ status: 400,
12359
+ body: projectInviteAcceptanceFailure(error)
12360
+ };
12361
+ if (invite.recipientInvite) return {
12362
+ status: 400,
12363
+ body: { error: safeRecipientInviteError(error) }
12364
+ };
12365
+ return {
12366
+ status: 400,
12367
+ body: { error: code }
12368
+ };
12369
+ }
12370
+ function inviteImportFailure(c, error, invite) {
12371
+ const { status, body } = inviteImportFailureResponse(error, invite);
12372
+ return c.json(body, status);
12373
+ }
12374
+ function pinBootstrapGrantPeer(db, deviceId, enrollment) {
12375
+ markCoordinatorManaged(db, { keysDir: syncKeysDir() });
12376
+ db.transaction(() => {
12377
+ recordDeviceCoordinatorHistory(db, {
12378
+ deviceId,
12379
+ fingerprint: enrollment.fingerprint,
12380
+ source: "bootstrap_grant"
12381
+ });
12382
+ updatePeerAddresses(db, deviceId, [], {
12383
+ name: enrollment.display_name?.trim() || void 0,
12384
+ pinnedFingerprint: enrollment.fingerprint,
12385
+ publicKey: enrollment.public_key,
12386
+ replaceTrust: true
12387
+ });
12388
+ })();
12389
+ }
12195
12390
  function parseJsonList(value) {
12196
12391
  if (value == null) return [];
12197
12392
  if (typeof value === "string") try {
@@ -12338,6 +12533,41 @@ function ensureStableStoreIdentityForRead(store) {
12338
12533
  ensureLocalActorRecord(store);
12339
12534
  return deviceId;
12340
12535
  }
12536
+ var DEVICE_IDENTITY_UNAVAILABLE = {
12537
+ device_identity_missing: "This device's sync identity isn't set up yet. Nothing changed. Open Devices once to finish setting it up, then try again.",
12538
+ device_identity_ambiguous: "This database has more than one device identity, so codemem can't tell which device the change is for. Nothing changed. Report this as a codemem issue."
12539
+ };
12540
+ var DeviceIdentityUnavailableError = class extends Error {
12541
+ code;
12542
+ constructor(code) {
12543
+ super(code);
12544
+ this.code = code;
12545
+ }
12546
+ };
12547
+ /**
12548
+ * The one device identity this store already has and runs as. Mapping changes
12549
+ * analyze and write for the same device, so they never create or adopt an
12550
+ * identity or pick one of several: each would change which device the confirmed
12551
+ * guardrails were for. A store that still runs as the placeholder device has not
12552
+ * adopted its identity yet; loading Devices does that.
12553
+ */
12554
+ function requireExistingDeviceIdentity(store) {
12555
+ const rows = store.db.prepare("SELECT device_id FROM sync_device LIMIT 2").pluck().all();
12556
+ if (rows.length === 0 || store.deviceId === "local") throw new DeviceIdentityUnavailableError("device_identity_missing");
12557
+ const [only] = rows;
12558
+ if (rows.length > 1 || only !== store.deviceId) throw new DeviceIdentityUnavailableError("device_identity_ambiguous");
12559
+ return store.deviceId;
12560
+ }
12561
+ /** Thrown inside a mapping write when the guardrails no longer match what was confirmed. */
12562
+ var MappingGuardrailsChangedError = class extends Error {
12563
+ warnings;
12564
+ missing;
12565
+ constructor(warnings, missing) {
12566
+ super("guardrail_confirmation_required");
12567
+ this.warnings = warnings;
12568
+ this.missing = missing;
12569
+ }
12570
+ };
12341
12571
  function ensureStableStoreDeviceIdentity(store) {
12342
12572
  const [deviceId] = ensureStableStoreDeviceIdentityWithFingerprint(store);
12343
12573
  return deviceId;
@@ -13090,8 +13320,9 @@ function legacySharedReviewReassignmentPreview(store, input) {
13090
13320
  workspace_identity: input.workspaceIdentity
13091
13321
  };
13092
13322
  }
13093
- function reassignLegacySharedReviewGroup(store, input) {
13323
+ function reassignLegacySharedReviewGroup(store, input, stillAllowed) {
13094
13324
  return store.db.transaction(() => {
13325
+ if (!stillAllowed()) throw new Error("access_change_needs_admin_device");
13095
13326
  const preview = legacySharedReviewReassignmentPreview(store, input);
13096
13327
  if (input.confirmationToken !== preview.confirmation_token) throw new Error("legacy shared review group changed before reassignment; refresh and try again");
13097
13328
  const rows = reassignableLegacySharedReviewRows(store, legacySharedReviewRowsForWorkspace(store, input.workspaceIdentity));
@@ -13342,7 +13573,17 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
13342
13573
  const reason = peerFacingScopeResetReason(failure.reason);
13343
13574
  const scopeId = (/* @__PURE__ */ new Set([options.scopeId, ...ops.map(cleanOpScopeId)])).has(failure.scopeId) ? failure.scopeId : options.scopeId;
13344
13575
  if (reason !== failure.reason || scopeId !== failure.scopeId) logWithheldScopeDenial(failure.reason, failure.scopeId);
13345
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), reason, LOCAL_SYNC_CAPABILITY, scopeId), 409);
13576
+ return c.json(peerFacingScopeReset(reason, scopeId), 409);
13577
+ }
13578
+ /** A scope refusal that tells the peer nothing about this device's default stream. */
13579
+ function peerFacingScopeReset(reason, scopeId) {
13580
+ return {
13581
+ error: "reset_required",
13582
+ reset_required: true,
13583
+ sync_capability: LOCAL_SYNC_CAPABILITY,
13584
+ reason,
13585
+ scope_id: scopeId
13586
+ };
13346
13587
  }
13347
13588
  /** Records locally what a scope denial withheld from the peer's answer. */
13348
13589
  function logWithheldScopeDenial(reason, scopeId) {
@@ -13367,7 +13608,7 @@ function recordInboundScopeFailure(context) {
13367
13608
  });
13368
13609
  }
13369
13610
  function parseInboundScopeRequest(body, context, options) {
13370
- return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.syncChannelPeerPin), {
13611
+ return parseSyncScopeRequest(body.scope_id, syncScopeProvided(Object.hasOwn(body, "scope_id"), options.requireScope), {
13371
13612
  ...context,
13372
13613
  negotiatedCapability: options.negotiated
13373
13614
  });
@@ -13381,14 +13622,15 @@ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
13381
13622
  try {
13382
13623
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
13383
13624
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13384
- const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.syncChannelPeerPin), {
13625
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, options.requireScope), {
13385
13626
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
13386
13627
  negotiatedCapability: negotiatedSyncCapability(c)
13387
13628
  });
13388
- if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, options.syncChannelPeerPin);
13629
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
13389
13630
  const pageRequest = snapshotPageRequest((name) => c.req.query(name), localDeviceId);
13390
13631
  const result = loadMemorySnapshotPageForPeer(store.db, {
13391
13632
  ...pageRequest,
13633
+ maxEntryBytes: options.maxEntryBytes,
13392
13634
  peerDeviceId,
13393
13635
  scopeId: scopeRequest.mode === "scoped" ? scopeRequest.scope_id : void 0
13394
13636
  });
@@ -13405,27 +13647,39 @@ function serveAuthorizedSnapshot(c, store, auth, options = {}) {
13405
13647
  has_more: result.hasMore
13406
13648
  });
13407
13649
  } catch (err) {
13650
+ if (err instanceof SyncEntryTooLargeError) return c.json(err.toResponseBody(), 409);
13408
13651
  const message = err instanceof Error ? err.message : "";
13409
13652
  const status = snapshotErrorStatus(message);
13410
13653
  if (status) return c.json({ error: message }, status);
13411
13654
  return c.json({ error: "internal_error" }, 500);
13412
13655
  }
13413
13656
  }
13657
+ /** Ops a channel can carry, or a typed refusal naming the one it cannot. */
13658
+ function opsWithinLimit(ops, limit) {
13659
+ return entriesWithinLimit("op", ops, (op) => op.op_id, limit);
13660
+ }
13661
+ /** A named 409 for an entry too large for the channel. Other read failures stay generic. */
13662
+ function syncReadFailureResponse(c, err) {
13663
+ if (err instanceof SyncEntryTooLargeError) return c.json(err.toResponseBody(), 409);
13664
+ return c.json({ error: "internal_error" }, 500);
13665
+ }
13666
+ /**
13667
+ * Channel requests never reach the bootstrap-grant fallback in the plain read
13668
+ * handlers: their reads are answered here, after the channel binding check.
13669
+ */
13414
13670
  function registerSyncChannelRestriction(app, options) {
13415
- const { syncChannelPeerPin } = options;
13416
- if (syncChannelPeerPin !== void 0) app.use("*", async (c, next) => {
13417
- const isOps = c.req.path === "/v1/ops" && ["GET", "POST"].includes(c.req.method);
13418
- const isRead = c.req.method === "GET" && ["/v1/status", "/v1/snapshot"].includes(c.req.path);
13419
- if (!isOps && !isRead) return c.json({ error: "not found" }, 404);
13671
+ if (options.mode.kind === "plain-direct") return;
13672
+ app.use("*", async (c, next) => {
13673
+ if (!channelRouteAllowed(options.mode, c.req.method, c.req.path)) return c.json({ error: "not found" }, 404);
13420
13674
  if (c.req.raw.signal.aborted) return c.json(unauthorizedPayload(), 401);
13421
- if (isRead) return serveChannelRead(c, options);
13675
+ if (c.req.method === "GET" && c.req.path !== "/v1/ops") return serveChannelRead(c, options);
13422
13676
  await next();
13423
13677
  });
13424
13678
  }
13425
- function serveChannelRead(c, options) {
13426
- const { syncChannelPeerPin, rateLimitedResponse } = options;
13679
+ async function serveChannelRead(c, options) {
13680
+ const { mode, binding, rateLimitedResponse } = options;
13427
13681
  const store = options.getStore();
13428
- const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
13682
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), binding);
13429
13683
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13430
13684
  if (!auth.ok) {
13431
13685
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -13433,25 +13687,33 @@ function serveChannelRead(c, options) {
13433
13687
  }
13434
13688
  const limited = rateLimitedResponse(c, auth.deviceId, true);
13435
13689
  if (limited) return limited;
13436
- if (c.req.path === "/v1/status") return serveChannelStatus(c, store, auth, syncChannelPeerPin);
13437
- return serveAuthorizedSnapshot(c, store, auth, { syncChannelPeerPin });
13690
+ const requireScope = requiresScope(mode);
13691
+ const maxEntryBytes = entryByteLimit(mode);
13692
+ if (c.req.path !== "/v1/status") return serveAuthorizedSnapshot(c, store, auth, {
13693
+ requireScope,
13694
+ maxEntryBytes
13695
+ });
13696
+ if (requireScope) return serveScopedStatus(c, store, auth);
13697
+ return serveAuthenticatedStatus(c, store, auth);
13438
13698
  }
13439
- function syncScopeProvided(provided, syncChannelPeerPin) {
13440
- return syncChannelPeerPin !== void 0 || provided;
13699
+ function syncScopeProvided(provided, requireScope) {
13700
+ return requireScope === true || provided;
13441
13701
  }
13442
- function syncScopeResetResponse(c, store, preciseReason, syncChannelPeerPin) {
13702
+ /**
13703
+ * Refuses a request whose scope this peer may not use. The answer names no
13704
+ * boundary: the default stream's is not the peer's to see, and a refused scope has
13705
+ * none it may use. Resets after authorization carry their own scope's boundary.
13706
+ */
13707
+ function syncScopeResetResponse(c, preciseReason) {
13443
13708
  const reason = peerFacingScopeResetReason(preciseReason);
13444
13709
  if (reason !== preciseReason) logWithheldScopeDenial(preciseReason, c.req.query(SYNC_SCOPE_QUERY_PARAM) ?? null);
13445
- if (syncChannelPeerPin !== void 0) return c.json({
13446
- error: "reset_required",
13447
- reset_required: true,
13448
- sync_capability: LOCAL_SYNC_CAPABILITY,
13449
- reason,
13450
- scope_id: null
13451
- }, 409);
13452
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
13710
+ return c.json(peerFacingScopeReset(reason, null), 409);
13453
13711
  }
13454
- function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
13712
+ /**
13713
+ * Status for one named scope, from the channel or from a direct request that
13714
+ * names a scope. A scope the peer may not use gets the minimal refusal.
13715
+ */
13716
+ function serveScopedStatus(c, store, auth) {
13455
13717
  try {
13456
13718
  const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13457
13719
  const authorization = syncScopeAuthorizationContext(store, auth, deviceId);
@@ -13459,14 +13721,14 @@ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
13459
13721
  ...authorization,
13460
13722
  negotiatedCapability: negotiatedSyncCapability(c)
13461
13723
  });
13462
- if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
13463
- if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
13724
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
13725
+ if (scopeRequest.mode !== "scoped" || !scopeRequest.scope_id) return syncScopeResetResponse(c, "missing_scope");
13464
13726
  const scopes = listAuthorizedScopesForPeer(store.db, {
13465
13727
  ...authorization,
13466
13728
  scopeId: scopeRequest.scope_id
13467
13729
  });
13468
13730
  const selectedScope = scopes[0];
13469
- if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c, store, "missing_scope", syncChannelPeerPin);
13731
+ if (!selectedScope || scopes.length !== 1) return syncScopeResetResponse(c, "missing_scope");
13470
13732
  return c.json({
13471
13733
  device_id: deviceId,
13472
13734
  protocol_version: SYNC_PROTOCOL_VERSION,
@@ -13481,12 +13743,96 @@ function serveChannelStatus(c, store, auth, syncChannelPeerPin) {
13481
13743
  return c.json({ error: "internal_error" }, 500);
13482
13744
  }
13483
13745
  }
13746
+ /** Status for an authenticated direct request, with or without a named scope. */
13747
+ async function serveAuthenticatedStatus(c, store, auth) {
13748
+ try {
13749
+ if (c.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === "1" && supportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), "reassign_scope")) await refreshConfiguredScopeMembershipCache(store.db, void 0, {
13750
+ keysDir: syncKeysDir(),
13751
+ dbPath: store.dbPath
13752
+ });
13753
+ if (c.req.query(SYNC_SCOPE_QUERY_PARAM) !== void 0) return serveScopedStatus(c, store, auth);
13754
+ return serveDefaultStatus(c, store, auth);
13755
+ } catch {
13756
+ return c.json({ error: "internal_error" }, 500);
13757
+ }
13758
+ }
13759
+ /** Status for a direct request that names no scope: the default stream and every authorized scope. */
13760
+ function serveDefaultStatus(c, store, auth) {
13761
+ const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13762
+ const syncReset = getSyncResetState(store.db);
13763
+ const negotiated = negotiatedSyncCapability(c);
13764
+ const authorizedScopes = isScopedSyncCapability(negotiated) ? listAuthorizedScopesForPeer(store.db, { ...syncScopeAuthorizationContext(store, auth, deviceId) }) : null;
13765
+ const response = {
13766
+ device_id: deviceId,
13767
+ protocol_version: SYNC_PROTOCOL_VERSION,
13768
+ fingerprint,
13769
+ runtime_version: VERSION$1,
13770
+ sync_reset: addSyncScopeToBoundary(syncReset, null),
13771
+ sync_capability: LOCAL_SYNC_CAPABILITY,
13772
+ sync_features: LOCAL_SYNC_FEATURES
13773
+ };
13774
+ if (authorizedScopes !== null) response.authorized_scopes = authorizedScopes;
13775
+ return c.json(response);
13776
+ }
13777
+ /**
13778
+ * Device authentication for the plain status and snapshot reads, with the
13779
+ * bootstrap-grant fallback when allowed. Returns the response to send when
13780
+ * the request is refused or rate limited.
13781
+ */
13782
+ async function authorizePeerRead(c, store, rateLimitedResponse, options) {
13783
+ const { transportGate } = options;
13784
+ const device = authorizeSyncRequest(store, c.req, Buffer.alloc(0), void 0, transportGate);
13785
+ if (isSyncAuthStoreBusy(device)) return syncAuthStoreBusyResponse(c);
13786
+ if (device.ok) return admittedPeerRead(c, rateLimitedResponse, device, false);
13787
+ const limited = rateLimitedResponse(c, c.req.path, false);
13788
+ if (limited) return limited;
13789
+ if (!options.allowGrant) return refusedPeerRead(c, device.reason, device, false);
13790
+ const scope = options.scope ? scopeOf(c) : {};
13791
+ const grant = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), {
13792
+ ...scope,
13793
+ transportGate
13794
+ });
13795
+ if (isSyncAuthStoreBusy(grant)) return syncAuthStoreBusyResponse(c);
13796
+ if (!grant.ok) return refusedPeerRead(c, device.reason, grant, true);
13797
+ return admittedPeerRead(c, rateLimitedResponse, grant, true);
13798
+ }
13799
+ function admittedPeerRead(c, rateLimitedResponse, auth, viaGrant) {
13800
+ return rateLimitedResponse(c, auth.deviceId, true) ?? {
13801
+ auth,
13802
+ viaGrant
13803
+ };
13804
+ }
13805
+ /** Specific reasons stay server-side; wire responses remain generic. */
13806
+ function refusedPeerRead(c, deviceAuthReason, auth, bootstrapAttempted) {
13807
+ const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
13808
+ if (bootstrapAttempted && (grantPresent || deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
13809
+ else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
13810
+ return c.json(unauthorizedPayload(), 401);
13811
+ }
13812
+ /**
13813
+ * The pin-only answer to a marked status, or null to serve the full status.
13814
+ * Only while direct Noise is on, and for either auth path: a worker that the
13815
+ * grant already pinned still gets only the pin when it retries. The rest of
13816
+ * the status, with its reset metadata, comes over Noise.
13817
+ */
13818
+ function grantStatusAnswer(c, store, mode) {
13819
+ if (!noiseActive(mode) || !marksNoiseStatusTarget(c.req)) return null;
13820
+ const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13821
+ return c.json({
13822
+ device_id: deviceId,
13823
+ fingerprint,
13824
+ transport: "noise1"
13825
+ });
13826
+ }
13484
13827
  function syncProtocolRoutes(getStore, opts = {}) {
13485
13828
  const app = new Hono();
13486
13829
  const routeRateLimit = opts.routeRateLimit ?? null;
13487
- const syncChannelPeerPin = opts.syncChannelPeerPin;
13830
+ const mode = opts.mode ?? PLAIN_DIRECT_MODE;
13831
+ const binding = channelBinding(mode);
13832
+ const transportGate = plaintextTransportGate(mode);
13488
13833
  registerSyncChannelRestriction(app, {
13489
- syncChannelPeerPin,
13834
+ mode,
13835
+ binding,
13490
13836
  getStore,
13491
13837
  rateLimitedResponse
13492
13838
  });
@@ -13504,62 +13850,17 @@ function syncProtocolRoutes(getStore, opts = {}) {
13504
13850
  app.get("/v1/status", (c) => {
13505
13851
  const store = getStore();
13506
13852
  return (async () => {
13507
- let auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));
13508
- if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13509
- let preauthChecked = false;
13510
- let bootstrapAttempted = false;
13511
- let deviceAuthReason = null;
13512
- if (!auth.ok) {
13513
- if ((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim()) {
13514
- preauthChecked = true;
13515
- const bootstrapLimited = rateLimitedResponse(c, c.req.path, false);
13516
- if (bootstrapLimited) return bootstrapLimited;
13517
- } else {
13518
- preauthChecked = true;
13519
- const unauthLimited = rateLimitedResponse(c, c.req.path, false);
13520
- if (unauthLimited) return unauthLimited;
13521
- }
13522
- deviceAuthReason = auth.reason;
13523
- auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));
13524
- bootstrapAttempted = true;
13525
- }
13526
- if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13527
- if (!auth.ok) {
13528
- const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
13529
- if (bootstrapAttempted && (grantPresent || deviceAuthReason != null && deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? "none"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
13530
- else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
13531
- return (preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ?? c.json(unauthorizedPayload(), 401);
13532
- }
13533
- const limited = rateLimitedResponse(c, auth.deviceId, true);
13534
- if (limited) return limited;
13535
- try {
13536
- if (c.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === "1" && supportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), "reassign_scope")) await refreshConfiguredScopeMembershipCache(store.db, void 0, {
13537
- keysDir: syncKeysDir(),
13538
- dbPath: store.dbPath
13539
- });
13540
- const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13541
- const syncReset = getSyncResetState(store.db);
13542
- const negotiated = negotiatedSyncCapability(c);
13543
- const authorizedScopes = isScopedSyncCapability(negotiated) ? listAuthorizedScopesForPeer(store.db, { ...syncScopeAuthorizationContext(store, auth, deviceId) }) : null;
13544
- const response = {
13545
- device_id: deviceId,
13546
- protocol_version: SYNC_PROTOCOL_VERSION,
13547
- fingerprint,
13548
- runtime_version: VERSION$1,
13549
- sync_reset: addSyncScopeToBoundary(syncReset, null),
13550
- sync_capability: LOCAL_SYNC_CAPABILITY,
13551
- sync_features: LOCAL_SYNC_FEATURES
13552
- };
13553
- if (authorizedScopes !== null) response.authorized_scopes = authorizedScopes;
13554
- return c.json(response);
13555
- } catch {
13556
- return c.json({ error: "internal_error" }, 500);
13557
- }
13853
+ const read = await authorizePeerRead(c, store, rateLimitedResponse, {
13854
+ allowGrant: true,
13855
+ transportGate
13856
+ });
13857
+ if (read instanceof Response) return read;
13858
+ return grantStatusAnswer(c, store, mode) ?? serveAuthenticatedStatus(c, store, read.auth);
13558
13859
  })();
13559
13860
  });
13560
13861
  app.get("/v1/ops", (c) => {
13561
13862
  const store = getStore();
13562
- const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), syncChannelPeerPin);
13863
+ const auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0), binding, transportGate);
13563
13864
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13564
13865
  if (!auth.ok) {
13565
13866
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -13572,11 +13873,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
13572
13873
  const rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);
13573
13874
  const negotiated = negotiatedSyncCapability(c);
13574
13875
  const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
13575
- const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, syncChannelPeerPin), {
13876
+ const scopeRequest = parseSyncScopeRequest(rawScopeId, syncScopeProvided(rawScopeId !== void 0, requiresScope(mode)), {
13576
13877
  ...syncScopeAuthorizationContext(store, auth, localDeviceId),
13577
13878
  negotiatedCapability: negotiated
13578
13879
  });
13579
- if (!scopeRequest.ok) return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
13880
+ if (!scopeRequest.ok) return syncScopeResetResponse(c, scopeRequest.reason);
13580
13881
  const since = c.req.query("since") ?? null;
13581
13882
  const rawLimit = Number.parseInt(c.req.query("limit") ?? "200", 10);
13582
13883
  const rawGeneration = c.req.query("generation");
@@ -13608,54 +13909,33 @@ function syncProtocolRoutes(getStore, opts = {}) {
13608
13909
  snapshot_id: boundary.snapshot_id,
13609
13910
  baseline_cursor: boundary.baseline_cursor,
13610
13911
  retained_floor_cursor: boundary.retained_floor_cursor,
13611
- ops: filtered.allowed,
13912
+ ops: opsWithinLimit(filtered.allowed, entryByteLimit(mode)),
13612
13913
  next_cursor: nextCursor,
13613
13914
  skipped: filtered.skipped,
13614
13915
  skipped_detail: filtered.skippedDetail
13615
13916
  });
13616
- } catch {
13617
- return c.json({ error: "internal_error" }, 500);
13917
+ } catch (err) {
13918
+ return syncReadFailureResponse(c, err);
13618
13919
  }
13619
13920
  });
13620
13921
  app.get("/v1/snapshot", (c) => {
13621
13922
  const store = getStore();
13622
13923
  return (async () => {
13623
- let auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));
13624
- if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13625
- let preauthChecked = false;
13626
- let bootstrapAttempted = false;
13627
- let deviceAuthReason = null;
13628
- if (!auth.ok) {
13629
- if ((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim()) {
13630
- preauthChecked = true;
13631
- const bootstrapLimited = rateLimitedResponse(c, c.req.path, false);
13632
- if (bootstrapLimited) return bootstrapLimited;
13633
- } else {
13634
- preauthChecked = true;
13635
- const unauthLimited = rateLimitedResponse(c, c.req.path, false);
13636
- if (unauthLimited) return unauthLimited;
13637
- }
13638
- deviceAuthReason = auth.reason;
13639
- auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), scopeOf(c));
13640
- bootstrapAttempted = true;
13641
- }
13642
- if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13643
- if (!auth.ok) {
13644
- const grantPresent = Boolean((c.req.header("X-Codemem-Bootstrap-Grant") ?? "").trim());
13645
- if (bootstrapAttempted && (grantPresent || deviceAuthReason != null && deviceAuthReason !== "missing_headers")) console.warn(`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? "none"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header("X-Opencode-Device"))}`);
13646
- else logDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);
13647
- return (preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ?? c.json(unauthorizedPayload(), 401);
13648
- }
13649
- const limited = rateLimitedResponse(c, auth.deviceId, true);
13650
- if (limited) return limited;
13651
- return serveAuthorizedSnapshot(c, store, auth);
13924
+ const allowGrant = !noiseActive(mode);
13925
+ const read = await authorizePeerRead(c, store, rateLimitedResponse, {
13926
+ allowGrant,
13927
+ scope: true,
13928
+ transportGate
13929
+ });
13930
+ if (read instanceof Response) return read;
13931
+ return serveAuthorizedSnapshot(c, store, read.auth);
13652
13932
  })();
13653
13933
  });
13654
13934
  app.post("/v1/ops", async (c) => {
13655
13935
  const store = getStore();
13656
13936
  const raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);
13657
13937
  if (raw == null) return c.json({ error: "payload_too_large" }, 413);
13658
- const auth = authorizeSyncRequest(store, c.req, raw, syncChannelPeerPin);
13938
+ const auth = authorizeSyncRequest(store, c.req, raw, binding, transportGate);
13659
13939
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
13660
13940
  if (!auth.ok) {
13661
13941
  logDirectPeerAuthDiagnostic(auth.reason);
@@ -13677,11 +13957,11 @@ function syncProtocolRoutes(getStore, opts = {}) {
13677
13957
  const scopeContext = syncScopeAuthorizationContext(store, auth, localDeviceId);
13678
13958
  const scopeRequest = parseInboundScopeRequest(body, scopeContext, {
13679
13959
  negotiated,
13680
- syncChannelPeerPin
13960
+ requireScope: requiresScope(mode)
13681
13961
  });
13682
13962
  if (!scopeRequest.ok) {
13683
13963
  recordInboundScopeFailure(scopeContext);
13684
- return syncScopeResetResponse(c, store, scopeRequest.reason, syncChannelPeerPin);
13964
+ return syncScopeResetResponse(c, scopeRequest.reason);
13685
13965
  }
13686
13966
  if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
13687
13967
  if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
@@ -13834,7 +14114,7 @@ async function deleteProjectScopeMappingRoute(c, store) {
13834
14114
  if (!body) return c.json({ error: "invalid json" }, 400);
13835
14115
  const confirmedGuardrailTokens = optionalViewerStringList(body, "confirmed_guardrail_tokens");
13836
14116
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
13837
- const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
14117
+ const deviceId = requireExistingDeviceIdentity(store);
13838
14118
  const warnings = analyzeProjectScopeMappingDeletionGuardrails(store.db, id, deviceId);
13839
14119
  const missing = missingGuardrailConfirmations(warnings, confirmedGuardrailTokens);
13840
14120
  if (missing.length > 0) return c.json({
@@ -13843,13 +14123,13 @@ async function deleteProjectScopeMappingRoute(c, store) {
13843
14123
  required_guardrail_tokens: missing.map((warning) => warning.confirmation_token),
13844
14124
  guardrail_warnings: warnings
13845
14125
  }, 409);
13846
- const deleted = deleteProjectMappingAndWakePolicies(store, id, deviceId, confirmedGuardrailTokens);
14126
+ const deleted = deleteProjectMappingAndWakePolicies(store, deviceId, id, confirmedGuardrailTokens);
13847
14127
  return c.json({
13848
14128
  ok: true,
13849
14129
  deleted
13850
14130
  });
13851
14131
  } catch (error) {
13852
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
14132
+ return mappingChangeError(c, error);
13853
14133
  } finally {
13854
14134
  releasePublicationMutation?.();
13855
14135
  }
@@ -13933,10 +14213,22 @@ function mappedProjectsInScopes(mappings, scopeIds) {
13933
14213
  function wakeRecipientPolicyProjects(store, projectIdentities, now) {
13934
14214
  wakeRecipientPoliciesForProjectIdentities(store.db, [...new Set(projectIdentities)], now);
13935
14215
  }
13936
- function saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs) {
13937
- store.adoptEnsuredDeviceIdentity(deviceId);
14216
+ /**
14217
+ * The guardrails, computed again inside the write for the device it writes for,
14218
+ * must need no confirmation beyond the ones the request carries.
14219
+ */
14220
+ function requireConfirmedGuardrails(store, deviceId, mappingInputs, confirmedGuardrailTokens) {
14221
+ const warnings = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
14222
+ ...input,
14223
+ deviceId
14224
+ }))).flatMap((analysis) => analysis.warnings);
14225
+ const missing = missingGuardrailConfirmations(warnings, confirmedGuardrailTokens);
14226
+ if (missing.length > 0) throw new MappingGuardrailsChangedError(warnings, missing);
14227
+ }
14228
+ function saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs, confirmedGuardrailTokens) {
13938
14229
  return store.db.transaction(() => {
13939
14230
  requireNarrowingWhenGated(store, mappingInputs);
14231
+ requireConfirmedGuardrails(store, deviceId, mappingInputs, confirmedGuardrailTokens);
13940
14232
  const before = policyWakeMappings(store);
13941
14233
  const previousMappings = existingRequestedMappings(before, mappingInputs);
13942
14234
  const writableScopeIds = new Set(resolveVisibleScopeIds(store.db, store.deviceId, store.scopeResolutionDeviceContext()));
@@ -13950,9 +14242,9 @@ function saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs) {
13950
14242
  return mappings;
13951
14243
  }).immediate();
13952
14244
  }
13953
- function deleteProjectMappingAndWakePolicies(store, mappingId, deviceId, confirmedGuardrailTokens) {
13954
- store.adoptEnsuredDeviceIdentity(deviceId);
14245
+ function deleteProjectMappingAndWakePolicies(store, deviceId, mappingId, confirmedGuardrailTokens) {
13955
14246
  return store.db.transaction(() => {
14247
+ requireAdminWhenGated();
13956
14248
  const before = policyWakeMappings(store);
13957
14249
  const removed = before.find((mapping) => mapping.id === mappingId);
13958
14250
  const deleted = deleteProjectScopeSettingsMapping(store.db, mappingId, {
@@ -14084,6 +14376,117 @@ function persistPeerIdentityMutation(store, body) {
14084
14376
  }).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).run();
14085
14377
  return assignment;
14086
14378
  }
14379
+ /**
14380
+ * Assigns a paired device to a person through the older route. The gate checked on
14381
+ * entry, but reading the body can outlast that, so the write checks again.
14382
+ */
14383
+ function persistPeerIdentityIfAllowed(store, body, readConfig) {
14384
+ return runViewerActorMutation(store, () => canChangeRecipientAccess(readConfig) ? persistPeerIdentityMutation(store, body) : {
14385
+ ...ACCESS_CHANGE_REFUSAL,
14386
+ status: 403
14387
+ });
14388
+ }
14389
+ var BINDING_COMMIT_HTTP_STATUS = {
14390
+ invalid: 400,
14391
+ not_found: 404,
14392
+ stale: 409,
14393
+ conflict: 409
14394
+ };
14395
+ /**
14396
+ * Commits reviewed device bindings, or returns null when this device may no longer
14397
+ * change access. The gate checked on entry, but the publication lock and the
14398
+ * inventory read can outlast that, so the write transaction checks again.
14399
+ */
14400
+ function commitBindingsIfAllowed(store, inventory, request, readConfig) {
14401
+ return store.db.transaction(() => canChangeRecipientAccess(readConfig) ? commitDeviceIdentityBindings(store.db, {
14402
+ localActorId: store.actorId,
14403
+ localDeviceId: store.deviceId
14404
+ }, inventory, request) : null).immediate();
14405
+ }
14406
+ /** Adds a person. People belong to coordinator setups, so this needs the admin device. */
14407
+ async function createActorRoute(c, store, readConfig) {
14408
+ ensureLocalActorRecord(store);
14409
+ let body;
14410
+ try {
14411
+ body = await c.req.json();
14412
+ } catch {
14413
+ return c.json({ error: "invalid json" }, 400);
14414
+ }
14415
+ const rawDisplayName = String(body.display_name ?? "");
14416
+ if (!rawDisplayName.trim()) return c.json({ error: "display_name required" }, 400);
14417
+ let displayName;
14418
+ try {
14419
+ displayName = normalizeHumanPresentationName(rawDisplayName, "display_name");
14420
+ } catch (error) {
14421
+ return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
14422
+ }
14423
+ const now = (/* @__PURE__ */ new Date()).toISOString();
14424
+ const actor = {
14425
+ actor_id: randomUUID(),
14426
+ display_name: displayName,
14427
+ is_local: 0,
14428
+ status: "active",
14429
+ merged_into_actor_id: null,
14430
+ created_at: now,
14431
+ updated_at: now
14432
+ };
14433
+ return store.db.transaction(() => {
14434
+ if (!canChangeRecipientAccess(readConfig)) return false;
14435
+ drizzle(store.db, { schema }).insert(schema.actors).values(actor).run();
14436
+ return true;
14437
+ }).immediate() ? c.json(actor) : c.json(ACCESS_CHANGE_REFUSAL, 403);
14438
+ }
14439
+ /** Renames a person, which needs the admin device like other changes to people. */
14440
+ async function renameActorRoute(c, store, readConfig) {
14441
+ ensureLocalActorRecord(store);
14442
+ let body;
14443
+ try {
14444
+ body = await c.req.json();
14445
+ } catch {
14446
+ return c.json({ error: "invalid json" }, 400);
14447
+ }
14448
+ const actorId = String(body.actor_id ?? "").trim();
14449
+ if (!actorId) return c.json({ error: "actor_id required" }, 400);
14450
+ let displayName;
14451
+ try {
14452
+ displayName = normalizeHumanPresentationName(String(body.display_name ?? ""), "display_name");
14453
+ } catch (error) {
14454
+ return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
14455
+ }
14456
+ const d = drizzle(store.db, { schema });
14457
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
14458
+ const result = store.db.transaction(() => {
14459
+ if (!canChangeRecipientAccess(readConfig)) return "refused";
14460
+ const actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();
14461
+ if (!actor) return null;
14462
+ d.update(schema.actors).set({
14463
+ display_name: displayName,
14464
+ updated_at: updatedAt
14465
+ }).where(eq(schema.actors.actor_id, actorId)).run();
14466
+ return actor;
14467
+ }).immediate();
14468
+ if (result === "refused") return c.json(ACCESS_CHANGE_REFUSAL, 403);
14469
+ if (!result) return c.json({ error: "actor not found" }, 404);
14470
+ return c.json({
14471
+ ...result,
14472
+ display_name: displayName,
14473
+ updated_at: updatedAt
14474
+ });
14475
+ }
14476
+ /**
14477
+ * Runs the recipient-policy migration, or returns null when this device may no
14478
+ * longer change access. A dry run writes nothing, so any device may run one. The
14479
+ * gate checked on entry, but reading the body can outlast that, so a migration
14480
+ * that writes checks again inside its transaction.
14481
+ */
14482
+ function migrateIfAllowed(store, dryRun, readConfig) {
14483
+ const migrate = () => migrateRecipientPolicyIntent(store.db, {
14484
+ localActorId: store.actorId,
14485
+ localDeviceId: store.deviceId
14486
+ }, { dryRun });
14487
+ if (dryRun) return migrate();
14488
+ return store.db.transaction(() => canChangeRecipientAccess(readConfig) ? migrate() : null).immediate();
14489
+ }
14087
14490
  function createActorMutationPreflightRoutes(getStore) {
14088
14491
  const app = new Hono();
14089
14492
  const preflight = async (c, next) => {
@@ -14183,6 +14586,54 @@ async function projectScopeInventoryRoute(c, store) {
14183
14586
  * other devices must not save those changes.
14184
14587
  */
14185
14588
  var ACCESS_CHANGE_REFUSAL = { error: "access_change_needs_admin_device" };
14589
+ function resolveReviewIfAllowed(store, readConfig, request) {
14590
+ const context = {
14591
+ localActorId: store.actorId,
14592
+ localDeviceId: store.deviceId,
14593
+ beforeResolve: () => {
14594
+ if (!canChangeRecipientAccess(readConfig)) throw new Error(ACCESS_CHANGE_REFUSAL.error);
14595
+ requireLocalActorRecord(store);
14596
+ }
14597
+ };
14598
+ try {
14599
+ return Array.isArray(request) ? resolveRecipientPolicyReviewBulk(store.db, context, request) : resolveRecipientPolicyReview(store.db, context, request);
14600
+ } catch (error) {
14601
+ if (error instanceof Error && error.message === ACCESS_CHANGE_REFUSAL.error) return null;
14602
+ throw error;
14603
+ }
14604
+ }
14605
+ /**
14606
+ * Commits recipient edges, refusing inside the write transaction when this device
14607
+ * may no longer change access. The gate checked on entry; the body and the Team
14608
+ * queues can outlast that.
14609
+ */
14610
+ function commitEdgesIfAllowed(store, request, readConfig) {
14611
+ return commitRecipientPolicyEdges(store.db, request, { stillAllowed: () => canChangeRecipientAccess(readConfig) });
14612
+ }
14613
+ var EDGE_COMMIT_HTTP_STATUS = {
14614
+ invalid: 400,
14615
+ not_found: 404,
14616
+ stale: 409,
14617
+ conflict: 409
14618
+ };
14619
+ function edgeCommitResponse(c, result) {
14620
+ if (result.errorCode === ACCESS_CHANGE_REFUSAL.error) return c.json(ACCESS_CHANGE_REFUSAL, 403);
14621
+ return c.json(result, EDGE_COMMIT_HTTP_STATUS[result.status] ?? 200);
14622
+ }
14623
+ /** A write that found this device no longer the admin device answers like the gate. */
14624
+ function accessRefusalOr(c, message, status) {
14625
+ if (message === ACCESS_CHANGE_REFUSAL.error) return c.json(ACCESS_CHANGE_REFUSAL, 403);
14626
+ return c.json({ error: message }, status);
14627
+ }
14628
+ /** A mapping change refused for this device's identity, its guardrails, or its authority. */
14629
+ function mappingChangeError(c, error) {
14630
+ if (error instanceof DeviceIdentityUnavailableError) return c.json({
14631
+ error: error.code,
14632
+ message: DEVICE_IDENTITY_UNAVAILABLE[error.code]
14633
+ }, 409);
14634
+ if (error instanceof MappingGuardrailsChangedError) return c.json(mappingGuardrailChallenge(error.warnings, error.missing), 409);
14635
+ return accessRefusalOr(c, error instanceof Error ? error.message : String(error), 400);
14636
+ }
14186
14637
  function canChangeRecipientAccess(readConfig) {
14187
14638
  try {
14188
14639
  return isCoordinatorAdminDevice(readConfig());
@@ -14418,15 +14869,22 @@ function peerEnrollmentHandler(getStore) {
14418
14869
  };
14419
14870
  }
14420
14871
  /**
14421
- * Set while a request that passed the gate only because it narrows access is
14422
- * handled. Another save can land between the gate and the write, so the write
14423
- * checks again inside its transaction, after the publication lock.
14872
+ * The gate's config reader, set while a mapping save or delete that passed the
14873
+ * gate is handled. The body, the publication lock and another save can all land
14874
+ * between the gate and the write, so the write checks again inside its
14875
+ * transaction: a device that is no longer the admin device may still only narrow.
14424
14876
  */
14425
- var mappingSaveMustOnlyNarrow = new AsyncLocalStorage();
14877
+ var mappingWriteAuthority = new AsyncLocalStorage();
14426
14878
  function requireNarrowingWhenGated(store, inputs) {
14427
- if (!mappingSaveMustOnlyNarrow.getStore()) return;
14879
+ const readConfig = mappingWriteAuthority.getStore();
14880
+ if (!readConfig || canChangeRecipientAccess(readConfig)) return;
14428
14881
  if (!projectScopeMappingSavesOnlyNarrow(store.db, inputs)) throw new Error("access_change_needs_admin_device");
14429
14882
  }
14883
+ /** Removing a mapping can expose a broader one, so only the admin device may. */
14884
+ function requireAdminWhenGated() {
14885
+ const readConfig = mappingWriteAuthority.getStore();
14886
+ if (readConfig && !canChangeRecipientAccess(readConfig)) throw new Error("access_change_needs_admin_device");
14887
+ }
14430
14888
  async function isDryRunMigration(c) {
14431
14889
  return (await parseViewerJsonBody(c, { allowEmpty: true }))?.dryRun === true;
14432
14890
  }
@@ -14457,6 +14915,10 @@ function installRecipientAccessChangeGate(app, getStore, readConfig = readCoordi
14457
14915
  const allowed = () => canChangeRecipientAccess(readConfig);
14458
14916
  for (const path of [
14459
14917
  "/api/sync/recipient-policy/v1/edges/commit",
14918
+ "/api/sync/recipient-policy/v1/device-bindings/commit",
14919
+ "/api/sync/peers/identity",
14920
+ "/api/sync/actors",
14921
+ "/api/sync/actors/rename",
14460
14922
  "/api/sync/actors/merge",
14461
14923
  "/api/sync/actors/deactivate",
14462
14924
  "/api/sync/recipient-policy/v1/review/resolve",
@@ -14466,33 +14928,31 @@ function installRecipientAccessChangeGate(app, getStore, readConfig = readCoordi
14466
14928
  app.post("/api/sync/recipient-policy/v1/migrate", async (c, next) => allowed() || await isDryRunMigration(c) ? next() : refuse(c));
14467
14929
  const mappingRoutes = [["/api/sync/sharing-domains/project-mappings", (body) => [parseViewerProjectMappingInput(body)]], ["/api/sync/sharing-domains/project-mappings/bulk", parseViewerProjectMappingInputs]];
14468
14930
  for (const [path, parse] of mappingRoutes) app.put(path, async (c, next) => {
14469
- if (allowed()) return next();
14470
- if (!await mappingSaveOnlyNarrows(c, getStore(), parse)) return refuse(c);
14471
- return mappingSaveMustOnlyNarrow.run(true, () => next());
14931
+ if (!allowed() && !await mappingSaveOnlyNarrows(c, getStore(), parse)) return refuse(c);
14932
+ return mappingWriteAuthority.run(readConfig, () => next());
14472
14933
  });
14473
- app.delete("/api/sync/sharing-domains/project-mappings/:id", async (c, next) => allowed() ? next() : refuse(c));
14934
+ app.delete("/api/sync/sharing-domains/project-mappings/:id", async (c, next) => allowed() ? mappingWriteAuthority.run(readConfig, () => next()) : refuse(c));
14935
+ }
14936
+ /** With a coordinator, codemem can pair the devices again. Without one, nothing does. */
14937
+ function unpairNotice(coordinatorConfigured) {
14938
+ if (!coordinatorConfigured) return "Only this device's pairing was removed.";
14939
+ return "Only this device's pairing was removed. If both devices share a Team Project, codemem can pair them again automatically. To stop syncing on all your devices, use Remove device.";
14474
14940
  }
14475
- async function removeLocalPeerRoute(c, getStore, options) {
14941
+ function removeLocalPeerRoute(c, getStore, options) {
14476
14942
  const store = getStore();
14477
14943
  const d = drizzle(store.db, { schema });
14478
14944
  const peerDeviceId = c.req.param("peer_device_id")?.trim();
14479
14945
  if (!peerDeviceId) return c.json({ error: "peer_device_id required" }, 400);
14480
14946
  if (!d.select({ peer_device_id: schema.syncPeers.peer_device_id }).from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get()) return c.json({ error: "peer not found" }, 404);
14481
- const { binding } = await removePeerFromThisDevice(store.db, {
14947
+ const { binding } = removePeerFromThisDevice(store.db, {
14482
14948
  localDeviceId: store.deviceId,
14483
- peerDeviceId,
14484
- readConfig: options.readCoordinatorConfig,
14485
- lookupCoordinatorAnswer: options.lookupCoordinatorDeviceAnswer
14486
- });
14487
- if (binding === "ended") return c.json({
14488
- ok: true,
14489
- binding
14949
+ peerDeviceId
14490
14950
  });
14491
14951
  return c.json({
14492
14952
  ok: true,
14493
14953
  binding,
14494
14954
  remove_from_projects: "needs_admin_device",
14495
- notice: "The device stays in Projects. An administrator's device can remove it."
14955
+ notice: unpairNotice(Boolean((options.readCoordinatorConfig ?? readCoordinatorSyncConfig)().syncCoordinatorUrl.trim()))
14496
14956
  });
14497
14957
  }
14498
14958
  function recipientInvitationTarget(store, body, kind) {
@@ -14778,14 +15238,9 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14778
15238
  try {
14779
15239
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
14780
15240
  ensureStableStoreIdentity(store);
14781
- const result = commitDeviceIdentityBindings(store.db, {
14782
- localActorId: store.actorId,
14783
- localDeviceId: store.deviceId
14784
- }, await localInventoryInput(store), body);
14785
- if (result.status === "invalid") return c.json(result, 400);
14786
- if (result.status === "not_found") return c.json(result, 404);
14787
- if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
14788
- return c.json(result);
15241
+ const result = commitBindingsIfAllowed(store, await localInventoryInput(store), body, readCoordinatorConfig);
15242
+ if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
15243
+ return c.json(result, BINDING_COMMIT_HTTP_STATUS[result.status] ?? 200);
14789
15244
  } catch (error) {
14790
15245
  if (isSqliteBusy(error)) {
14791
15246
  c.header("Retry-After", "1");
@@ -14917,13 +15372,12 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14917
15372
  return c.json({ error: "device identity unavailable" }, 500);
14918
15373
  }
14919
15374
  if (!deviceId || !fingerprint) return c.json({ error: "public key missing" }, 500);
14920
- return c.json({
14921
- device_id: deviceId,
15375
+ return c.json(pairingPayloadBody({
15376
+ deviceId,
14922
15377
  fingerprint,
14923
- public_key: publicKey ?? null,
14924
- pairing_filter_hint: PAIRING_FILTER_HINT,
14925
- addresses: pairingAdvertiseAddresses(config)
14926
- });
15378
+ publicKey,
15379
+ config
15380
+ }));
14927
15381
  }
14928
15382
  });
14929
15383
  app.post("/api/sync/peers/rename", async (c) => {
@@ -14978,7 +15432,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14978
15432
  localDeviceId: store.deviceId
14979
15433
  }));
14980
15434
  });
14981
- app.route("/", deviceRoutes(getStore)).get("/api/sync/recipient-policy/v1/intent", (c) => {
15435
+ app.route("/", deviceRenameRoutes(getStore)).get("/api/sync/recipient-policy/v1/intent", (c) => {
14982
15436
  const store = getStore();
14983
15437
  return c.json(listRecipientPolicyIntent(store.db));
14984
15438
  });
@@ -15010,14 +15464,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15010
15464
  const teamIds = request ? [...new Set(request.changes.flatMap((change) => change.recipient.recipientKind === "team" ? [change.recipient.teamId] : []))].toSorted() : [];
15011
15465
  const commit = async (index) => {
15012
15466
  const teamId = teamIds[index];
15013
- if (!teamId) return commitRecipientPolicyEdges(store.db, request ?? body);
15467
+ if (!teamId) return commitEdgesIfAllowed(store, request ?? body, readCoordinatorConfig);
15014
15468
  return serializeRecipientPolicyTeamMutation(store.db, teamId, () => commit(index + 1));
15015
15469
  };
15016
- const result = await commit(0);
15017
- if (result.status === "invalid") return c.json(result, 400);
15018
- if (result.status === "not_found") return c.json(result, 404);
15019
- if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
15020
- return c.json(result);
15470
+ return edgeCommitResponse(c, await commit(0));
15021
15471
  } catch (error) {
15022
15472
  if (isSqliteBusy(error)) {
15023
15473
  c.header("Retry-After", "1");
@@ -15053,10 +15503,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15053
15503
  const body = value;
15054
15504
  if (Object.keys(body).some((key) => key !== "dryRun") || Object.hasOwn(body, "dryRun") && typeof body.dryRun !== "boolean") return c.json({ error: "request_invalid" }, 400);
15055
15505
  try {
15056
- return c.json(migrateRecipientPolicyIntent(store.db, {
15057
- localActorId: store.actorId,
15058
- localDeviceId: store.deviceId
15059
- }, { dryRun: body.dryRun === true }));
15506
+ const result = migrateIfAllowed(store, body.dryRun === true, readCoordinatorConfig);
15507
+ return result ? c.json(result) : c.json(ACCESS_CHANGE_REFUSAL, 403);
15060
15508
  } catch (error) {
15061
15509
  if (isSqliteBusy(error)) {
15062
15510
  c.header("Retry-After", "1");
@@ -15087,11 +15535,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15087
15535
  const body = await parseViewerJsonBody(c);
15088
15536
  const request = parseReviewRequest(body);
15089
15537
  if (!request) return c.json({ error: "request_invalid" }, 400);
15090
- requireLocalActorRecord(store);
15091
- const result = resolveRecipientPolicyReview(store.db, {
15092
- localActorId: store.actorId,
15093
- localDeviceId: store.deviceId
15094
- }, request);
15538
+ const result = resolveReviewIfAllowed(store, readCoordinatorConfig, request);
15539
+ if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
15095
15540
  if (result.status === "stale" || result.status === "conflict") return c.json(result, 409);
15096
15541
  if (result.status === "not_found") return c.json(result, 404);
15097
15542
  if (result.status === "invalid") return c.json(result, 400);
@@ -15103,11 +15548,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15103
15548
  if (!body || !Array.isArray(body.requests) || body.requests.length === 0 || body.requests.length > 100) return c.json({ error: "request_invalid" }, 400);
15104
15549
  const requests = body.requests.map(parseReviewRequest);
15105
15550
  if (requests.some((request) => request == null)) return c.json({ error: "request_invalid" }, 400);
15106
- requireLocalActorRecord(store);
15107
- const result = resolveRecipientPolicyReviewBulk(store.db, {
15108
- localActorId: store.actorId,
15109
- localDeviceId: store.deviceId
15110
- }, requests);
15551
+ const result = resolveReviewIfAllowed(store, readCoordinatorConfig, requests);
15552
+ if (!result) return c.json(ACCESS_CHANGE_REFUSAL, 403);
15111
15553
  return c.json(result, result.results.some((item) => item.status !== "applied") ? 207 : 200);
15112
15554
  });
15113
15555
  app.get("/api/sync/projects", (c) => projectScopeInventoryRoute(c, getStore()));
@@ -15330,10 +15772,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15330
15772
  confirmationToken,
15331
15773
  scopeId,
15332
15774
  workspaceIdentity
15333
- }));
15775
+ }, () => canChangeRecipientAccess(readCoordinatorConfig)));
15334
15776
  } catch (error) {
15335
15777
  const message = error instanceof Error ? error.message : String(error);
15336
- return c.json({ error: message }, message.includes("not found") ? 404 : 400);
15778
+ return accessRefusalOr(c, message, message.includes("not found") ? 404 : 400);
15337
15779
  }
15338
15780
  });
15339
15781
  app.put("/api/sync/sharing-domains/project-mappings", async (c) => {
@@ -15345,7 +15787,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15345
15787
  const confirmedGuardrailTokens = optionalViewerStringList(body, "confirmed_guardrail_tokens");
15346
15788
  const mappingInput = parseViewerProjectMappingInput(body);
15347
15789
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
15348
- const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
15790
+ const deviceId = requireExistingDeviceIdentity(store);
15349
15791
  const analysis = analyzeProjectScopeMappingChangeGuardrails(store.db, {
15350
15792
  ...mappingInput,
15351
15793
  deviceId
@@ -15357,14 +15799,14 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15357
15799
  }, 400);
15358
15800
  const missingConfirmations = missingGuardrailConfirmations(analysis.warnings, confirmedGuardrailTokens);
15359
15801
  if (missingConfirmations.length > 0) return c.json(mappingGuardrailChallenge(analysis.warnings, missingConfirmations), 409);
15360
- const [mapping] = saveProjectMappingsAndWakePolicies(store, deviceId, [mappingInput]);
15802
+ const [mapping] = saveProjectMappingsAndWakePolicies(store, deviceId, [mappingInput], confirmedGuardrailTokens);
15361
15803
  return c.json({
15362
15804
  ok: true,
15363
15805
  mapping,
15364
15806
  guardrail_warnings: analysis.warnings
15365
15807
  });
15366
15808
  } catch (error) {
15367
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
15809
+ return mappingChangeError(c, error);
15368
15810
  } finally {
15369
15811
  releasePublicationMutation?.();
15370
15812
  }
@@ -15377,16 +15819,16 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15377
15819
  try {
15378
15820
  const mappingInputs = parseViewerProjectMappingInputs(body);
15379
15821
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
15380
- const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
15822
+ const deviceId = requireExistingDeviceIdentity(store);
15381
15823
  const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
15382
15824
  if (verdict.refusal) return c.json(verdict.refusal.body, verdict.refusal.status);
15383
15825
  return c.json({
15384
15826
  ok: true,
15385
- mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs),
15827
+ mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs, []),
15386
15828
  guardrail_warnings: verdict.warnings
15387
15829
  });
15388
15830
  } catch (error) {
15389
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
15831
+ return mappingChangeError(c, error);
15390
15832
  } finally {
15391
15833
  releasePublicationMutation?.();
15392
15834
  }
@@ -15396,9 +15838,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15396
15838
  const body = await parseViewerJsonBody(c);
15397
15839
  if (!body) return c.json({ error: "invalid json" }, 400);
15398
15840
  try {
15399
- const mappingInputs = parseViewerProjectMappingInputs(body);
15400
- const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
15401
- const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
15841
+ const verdict = bulkProjectMappingVerdict(store, parseViewerProjectMappingInputs(body), requireExistingDeviceIdentity(store));
15402
15842
  return c.json({
15403
15843
  ok: true,
15404
15844
  accepted: verdict.refusal === null,
@@ -15406,7 +15846,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15406
15846
  guardrail_warnings: verdict.warnings
15407
15847
  });
15408
15848
  } catch (error) {
15409
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
15849
+ return mappingChangeError(c, error);
15410
15850
  }
15411
15851
  });
15412
15852
  app.delete("/api/sync/sharing-domains/project-mappings/:id", (c) => deleteProjectScopeMappingRoute(c, getStore()));
@@ -15418,75 +15858,15 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15418
15858
  } catch {
15419
15859
  return c.json({ error: "invalid json" }, 400);
15420
15860
  }
15421
- const result = runViewerActorMutation(store, () => persistPeerIdentityMutation(store, body));
15861
+ const result = persistPeerIdentityIfAllowed(store, body, readCoordinatorConfig);
15422
15862
  if ("error" in result) return c.json({ error: result.error }, result.status);
15423
15863
  return c.json({
15424
15864
  ok: true,
15425
15865
  ...result
15426
15866
  });
15427
15867
  });
15428
- app.post("/api/sync/actors", async (c) => {
15429
- const store = getStore();
15430
- ensureLocalActorRecord(store);
15431
- let body;
15432
- try {
15433
- body = await c.req.json();
15434
- } catch {
15435
- return c.json({ error: "invalid json" }, 400);
15436
- }
15437
- const rawDisplayName = String(body.display_name ?? "");
15438
- if (!rawDisplayName.trim()) return c.json({ error: "display_name required" }, 400);
15439
- let displayName;
15440
- try {
15441
- displayName = normalizeHumanPresentationName(rawDisplayName, "display_name");
15442
- } catch (error) {
15443
- return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
15444
- }
15445
- const d = drizzle(store.db, { schema });
15446
- const now = (/* @__PURE__ */ new Date()).toISOString();
15447
- const actor = {
15448
- actor_id: randomUUID(),
15449
- display_name: displayName,
15450
- is_local: 0,
15451
- status: "active",
15452
- merged_into_actor_id: null,
15453
- created_at: now,
15454
- updated_at: now
15455
- };
15456
- d.insert(schema.actors).values(actor).run();
15457
- return c.json(actor);
15458
- });
15459
- app.post("/api/sync/actors/rename", async (c) => {
15460
- const store = getStore();
15461
- ensureLocalActorRecord(store);
15462
- let body;
15463
- try {
15464
- body = await c.req.json();
15465
- } catch {
15466
- return c.json({ error: "invalid json" }, 400);
15467
- }
15468
- const actorId = String(body.actor_id ?? "").trim();
15469
- if (!actorId) return c.json({ error: "actor_id required" }, 400);
15470
- let displayName;
15471
- try {
15472
- displayName = normalizeHumanPresentationName(String(body.display_name ?? ""), "display_name");
15473
- } catch (error) {
15474
- return c.json({ error: error instanceof Error ? error.message : "display_name_invalid" }, 400);
15475
- }
15476
- const d = drizzle(store.db, { schema });
15477
- const actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();
15478
- if (!actor) return c.json({ error: "actor not found" }, 404);
15479
- const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
15480
- d.update(schema.actors).set({
15481
- display_name: displayName,
15482
- updated_at: updatedAt
15483
- }).where(eq(schema.actors.actor_id, actorId)).run();
15484
- return c.json({
15485
- ...actor,
15486
- display_name: displayName,
15487
- updated_at: updatedAt
15488
- });
15489
- });
15868
+ app.post("/api/sync/actors", (c) => createActorRoute(c, getStore(), readCoordinatorConfig));
15869
+ app.post("/api/sync/actors/rename", (c) => renameActorRoute(c, getStore(), readCoordinatorConfig));
15490
15870
  app.post("/api/sync/actors/merge", async (c) => {
15491
15871
  const store = getStore();
15492
15872
  let body;
@@ -15796,11 +16176,7 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15796
16176
  error: "peer_conflict",
15797
16177
  detail: "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload."
15798
16178
  }, 409);
15799
- updatePeerAddresses(store.db, pairingResult.device_id, pairingResult.addresses, {
15800
- pinnedFingerprint: pairingResult.fingerprint,
15801
- publicKey: pairingResult.public_key,
15802
- replaceTrust: true
15803
- });
16179
+ savePairingPayload(store, pairingResult);
15804
16180
  return c.json({
15805
16181
  ok: true,
15806
16182
  type: "pair",
@@ -15825,7 +16201,8 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15825
16201
  recipientActorId: recipientInvite ? null : store.actorId,
15826
16202
  recipientDisplayName: decoded.kind === "add_device" ? null : typeof body.recipient_name === "string" ? body.recipient_name : store.actorDisplayName,
15827
16203
  deviceDisplayName: typeof body.device_name === "string" ? body.device_name : null,
15828
- reviewedOnboardingDigest: reviewedOnboardingDigest || null
16204
+ reviewedOnboardingDigest: reviewedOnboardingDigest || null,
16205
+ confirmCoordinatorJoin: body.confirm_coordinator_join === true
15829
16206
  });
15830
16207
  const type = recipientInvite ? "recipient_onboarding" : projectInvite ? "project_share" : "team_join";
15831
16208
  if (recipientInvite) {
@@ -15850,9 +16227,10 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
15850
16227
  type
15851
16228
  });
15852
16229
  } catch (error) {
15853
- if (projectInvite) return c.json(projectInviteAcceptanceFailure(error), 400);
15854
- if (recipientInvite) return c.json({ error: safeRecipientInviteError(error) }, 400);
15855
- return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
16230
+ return inviteImportFailure(c, error, {
16231
+ projectInvite,
16232
+ recipientInvite
16233
+ });
15856
16234
  }
15857
16235
  });
15858
16236
  app.get("/api/coordinator/admin/status", async (c) => {
@@ -18190,7 +18568,7 @@ function teamCreateRoutes(getStore, readCoordinatorConfig = readCoordinatorSyncC
18190
18568
  }
18191
18569
  //#endregion
18192
18570
  //#region src/routes/team-member-removal.ts
18193
- var BASE = "/api/sync/recipient-policy/v1/teams/:teamId/member-removals";
18571
+ var BASE$1 = "/api/sync/recipient-policy/v1/teams/:teamId/member-removals";
18194
18572
  var STATUS = {
18195
18573
  invalid_input: 400,
18196
18574
  team_not_found: 404,
@@ -18214,7 +18592,7 @@ function previewBody(body) {
18214
18592
  if (Object.keys(data).length !== 1 || !isId(data.identityId)) return null;
18215
18593
  return { identityId: data.identityId };
18216
18594
  }
18217
- function commitBody(body) {
18595
+ function commitBody$1(body) {
18218
18596
  const data = body;
18219
18597
  if (!data || typeof data !== "object" || Array.isArray(data)) return null;
18220
18598
  if (Object.keys(data).toSorted().join(",") !== "expectedDigest,identityId,revokeInvitationIds") return null;
@@ -18265,7 +18643,7 @@ function teamMemberRemovalRoutes(getStore, options = {}) {
18265
18643
  return c.json(result);
18266
18644
  };
18267
18645
  app.get("/api/sync/recipient-policy/v1/team-coordinator-link-conflicts", (c) => c.json({ teamIds: teamCoordinatorLinkConflicts(getStore().db) }));
18268
- app.post(`${BASE}/preview`, (c) => handle(c, async (teamId, body, ctx) => {
18646
+ app.post(`${BASE$1}/preview`, (c) => handle(c, async (teamId, body, ctx) => {
18269
18647
  const input = previewBody(body);
18270
18648
  if (!input) return {
18271
18649
  state: "rejected",
@@ -18276,8 +18654,8 @@ function teamMemberRemovalRoutes(getStore, options = {}) {
18276
18654
  ...input
18277
18655
  }, ctx);
18278
18656
  }));
18279
- app.post(`${BASE}/commit`, (c) => handle(c, async (teamId, body, ctx) => {
18280
- const input = commitBody(body);
18657
+ app.post(`${BASE$1}/commit`, (c) => handle(c, async (teamId, body, ctx) => {
18658
+ const input = commitBody$1(body);
18281
18659
  if (!input) return {
18282
18660
  state: "rejected",
18283
18661
  error: "invalid_input"
@@ -18301,6 +18679,183 @@ function teamMemberRemovalRoutes(getStore, options = {}) {
18301
18679
  return app;
18302
18680
  }
18303
18681
  //#endregion
18682
+ //#region src/routes/team-recovery.ts
18683
+ var BASE = "/api/sync/recipient-policy/v1/teams/:teamId/recovery";
18684
+ var REFUSAL_STATUS = {
18685
+ invalid_input: 400,
18686
+ team_not_found: 404,
18687
+ team_not_quarantined: 409,
18688
+ setup_record_missing: 409,
18689
+ roster_unavailable: 503,
18690
+ device_removals_unavailable: 503,
18691
+ device_blocks_unavailable: 503,
18692
+ completion_unavailable: 503,
18693
+ member_removals_unavailable: 503,
18694
+ team_group_unavailable: 503,
18695
+ completion_missing: 409,
18696
+ completion_invalid: 409,
18697
+ setup_differs_from_completion: 409,
18698
+ team_group_conflict: 409,
18699
+ team_group_mismatch: 409,
18700
+ team_policy_blocked: 409,
18701
+ device_blocked: 409,
18702
+ device_evidence_contradictory: 409,
18703
+ device_key_unverified: 409,
18704
+ device_key_changed: 409,
18705
+ device_disabled: 409,
18706
+ device_block_unchecked: 503,
18707
+ device_missing_without_removal: 409,
18708
+ device_decision_changed: 409,
18709
+ evidence_stale: 503,
18710
+ admin_authority_changed: 403,
18711
+ recovery_preview_stale: 409,
18712
+ recovery_state_changed: 409
18713
+ };
18714
+ /** Whether the configuration is for the setup's coordinator and one of its groups. */
18715
+ function configuredFor(config, target) {
18716
+ const configured = normalizedCoordinatorId(config.syncCoordinatorUrl);
18717
+ return configured !== null && configured === normalizedCoordinatorId(target.coordinatorId) && config.syncCoordinatorGroups.includes(target.groupId);
18718
+ }
18719
+ /**
18720
+ * The coordinator reads for this device. The block check is signed with the
18721
+ * identity the sync daemon signs with, keys directory included. Without a
18722
+ * usable one the check fails, and the recovery reads it as unavailable.
18723
+ */
18724
+ function evidenceActions(store, config) {
18725
+ const identity = daemonSigningIdentity(store);
18726
+ const actions = coordinatorTeamRecoveryEvidenceActions(store, config, identity ?? { localDeviceId: "" });
18727
+ if (identity) return actions;
18728
+ const unsigned = () => Promise.reject(/* @__PURE__ */ new Error("signing_identity_unavailable"));
18729
+ return {
18730
+ ...actions,
18731
+ deviceBlocksAndRemovals: unsigned
18732
+ };
18733
+ }
18734
+ /**
18735
+ * What a request acts on, or why it cannot: the device is no admin, the Team
18736
+ * has no completed setup here, or its setup belongs to a coordinator or group
18737
+ * this device is not configured for.
18738
+ */
18739
+ function recoveryRequest(teamId, getStore, options) {
18740
+ const readConfig = options.readCoordinatorConfig ?? readCoordinatorSyncConfig;
18741
+ const config = readConfig();
18742
+ if (!isCoordinatorAdminDevice(config)) return {
18743
+ error: "coordinator_admin_required",
18744
+ status: 403
18745
+ };
18746
+ if (!isStrictRecipientPolicyId(teamId)) return {
18747
+ error: "invalid_input",
18748
+ status: 400
18749
+ };
18750
+ const store = getStore();
18751
+ const target = teamRecoveryTarget(store.db, teamId);
18752
+ if (!target) return {
18753
+ error: "team_not_found",
18754
+ status: 404
18755
+ };
18756
+ if (!configuredFor(config, target)) return {
18757
+ error: "team_coordinator_not_configured",
18758
+ status: 409
18759
+ };
18760
+ const stillAuthorized = () => {
18761
+ const current = readConfig();
18762
+ return isCoordinatorAdminDevice(current) && configuredFor(current, target) && current.syncCoordinatorAdminSecret === config.syncCoordinatorAdminSecret;
18763
+ };
18764
+ const actions = options.actions ?? evidenceActions(store, config);
18765
+ return {
18766
+ db: store.db,
18767
+ target,
18768
+ actions,
18769
+ stillAuthorized
18770
+ };
18771
+ }
18772
+ /** The response for a commit that did not leave the Team recovered. */
18773
+ function commitFailure(result) {
18774
+ if (result.state === "refused") {
18775
+ const { reason, deviceIds } = result;
18776
+ return {
18777
+ body: deviceIds ? {
18778
+ error: reason,
18779
+ deviceIds
18780
+ } : { error: reason },
18781
+ status: REFUSAL_STATUS[reason]
18782
+ };
18783
+ }
18784
+ if (result.state === "superseded") return {
18785
+ body: { error: "recovery_superseded" },
18786
+ status: 409
18787
+ };
18788
+ if (result.state === "unverified") {
18789
+ const status = result.reason === "admin_authority_changed" ? 403 : 503;
18790
+ return {
18791
+ body: {
18792
+ error: "recovery_unverified",
18793
+ reason: result.reason
18794
+ },
18795
+ status
18796
+ };
18797
+ }
18798
+ return {
18799
+ body: {
18800
+ error: "recovery_quarantined_again",
18801
+ reason: result.reason
18802
+ },
18803
+ status: result.reason === "evidence_unavailable" ? 503 : 409
18804
+ };
18805
+ }
18806
+ function isEmptyObject(body) {
18807
+ return Boolean(body) && typeof body === "object" && Object.keys(body).length === 0;
18808
+ }
18809
+ function commitBody(body) {
18810
+ const data = body;
18811
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
18812
+ if (Object.keys(data).length !== 1) return null;
18813
+ const { expectedDigest } = data;
18814
+ if (typeof expectedDigest !== "string" || !expectedDigest || expectedDigest.length > 256) return null;
18815
+ return { expectedDigest };
18816
+ }
18817
+ function teamRecoveryRoutes(getStore, options = {}) {
18818
+ const app = new Hono();
18819
+ const read = (request) => readTeamRecoveryEvidence(request.target, request.actions, options.nowMs);
18820
+ app.post(`${BASE}/preview`, async (c) => {
18821
+ const request = recoveryRequest(c.req.param("teamId") ?? "", getStore, options);
18822
+ if ("error" in request) return c.json({ error: request.error }, request.status);
18823
+ if (!isEmptyObject(await parseViewerJsonBody(c, { allowEmpty: true }))) return c.json({ error: "invalid_input" }, 400);
18824
+ const { evidence, startedAtMs } = await read(request);
18825
+ if (!request.stillAuthorized()) return c.json({ error: "coordinator_admin_required" }, 403);
18826
+ const nowMs = (options.nowMs ?? Date.now)();
18827
+ if (isTeamRecoveryEvidenceStale(startedAtMs, nowMs)) return c.json({ error: "evidence_stale" }, REFUSAL_STATUS.evidence_stale);
18828
+ const preview = previewTeamRecovery(request.db, request.target, evidence, { nowMs });
18829
+ if (preview.state === "ready") return c.json(preview);
18830
+ const failure = commitFailure(preview);
18831
+ return c.json(failure.body, failure.status);
18832
+ });
18833
+ app.post(`${BASE}/commit`, async (c) => {
18834
+ const request = recoveryRequest(c.req.param("teamId") ?? "", getStore, options);
18835
+ if ("error" in request) return c.json({ error: request.error }, request.status);
18836
+ const input = commitBody(await parseViewerJsonBody(c));
18837
+ if (!input) return c.json({ error: "invalid_input" }, 400);
18838
+ const release = claimCandidateMutation(request.db, request.target.candidateRef);
18839
+ if (!release) return c.json({ error: "team_setup_busy" }, 409);
18840
+ try {
18841
+ const result = await commitTeamRecovery(request.db, {
18842
+ ...request.target,
18843
+ ...input
18844
+ }, {
18845
+ readEvidence: () => read(request),
18846
+ nowMs: options.nowMs,
18847
+ stillAuthorized: request.stillAuthorized
18848
+ });
18849
+ if (result.state === "recovered") return c.json(result);
18850
+ const failure = commitFailure(result);
18851
+ return c.json(failure.body, failure.status);
18852
+ } finally {
18853
+ release();
18854
+ }
18855
+ });
18856
+ return app;
18857
+ }
18858
+ //#endregion
18304
18859
  //#region src/routes/update-status.ts
18305
18860
  function updateStatusRoutes(options = {}) {
18306
18861
  const getUpdateStatus$1 = options.getUpdateStatus ?? getUpdateStatus;
@@ -18358,7 +18913,7 @@ function createSyncApp$1(opts) {
18358
18913
  const mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));
18359
18914
  const app = new Hono();
18360
18915
  app.route("/", syncProtocolRoutes(storeFactory, {
18361
- syncChannelPeerPin: opts?.syncChannelPeerPin,
18916
+ mode: opts?.mode,
18362
18917
  routeRateLimit: {
18363
18918
  limiter: rateLimiter,
18364
18919
  readLimit,
@@ -18759,6 +19314,37 @@ AUTH_CONTROLLER_CURRENT_SQL.replace("SELECT a.*", "SELECT e.*");
18759
19314
  function ownerProfileConflict() {
18760
19315
  throw new Error("Owner enrollment stopped for review. Keep the profile and saved request unchanged; no identity or access repair is automatic.");
18761
19316
  }
19317
+ //#endregion
19318
+ //#region ../core/src/coordinator-history.ts
19319
+ var historyRow = (kind, source, deviceId, fingerprint) => `INSERT INTO coordinator_history(subject_kind, device_id, fingerprint, source, recorded_at)
19320
+ SELECT '${kind}', ${deviceId}, ${fingerprint}, '${source}', strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
19321
+ WHERE NOT EXISTS (SELECT 1 FROM coordinator_history
19322
+ WHERE subject_kind = '${kind}' AND device_id = ${deviceId} AND fingerprint = ${fingerprint});`;
19323
+ var STORE_ROW = (source) => historyRow("store", source, "''", "''");
19324
+ var DEVICE_ROW = (source, deviceId, fingerprint) => historyRow("device", source, deviceId, fingerprint);
19325
+ var PEER_COORDINATOR_FIELDS = `(NEW.discovered_via_coordinator_id IS NOT NULL
19326
+ OR NEW.discovered_via_group_id IS NOT NULL
19327
+ OR NEW.pending_bootstrap_grant_id IS NOT NULL
19328
+ OR NEW.trust_provenance = 'coordinator_policy')`;
19329
+ function trigger(name, table, event, when, body) {
19330
+ return {
19331
+ name,
19332
+ table,
19333
+ sql: `CREATE TRIGGER IF NOT EXISTS ${name} AFTER ${event} ON ${table} WHEN ${when}
19334
+ BEGIN ${body} END;`
19335
+ };
19336
+ }
19337
+ [
19338
+ ...["INSERT", "UPDATE OF authority_type, coordinator_id"].map((event, index) => trigger(`coordinator_history_scope_${index ? "update" : "insert"}`, "replication_scopes", event, "NEW.authority_type <> 'local' OR NEW.coordinator_id IS NOT NULL", STORE_ROW("scope"))),
19339
+ ...["INSERT", "UPDATE OF coordinator_id, group_id"].map((event, index) => trigger(`coordinator_history_membership_${index ? "update" : "insert"}`, "scope_memberships", event, "NEW.coordinator_id IS NOT NULL OR NEW.group_id IS NOT NULL", STORE_ROW("scope_membership") + DEVICE_ROW("scope_membership", "NEW.device_id", "''"))),
19340
+ trigger("coordinator_history_membership_cache_insert", "scope_membership_cache_state", "INSERT", "1", STORE_ROW("membership_cache")),
19341
+ ...["INSERT", "UPDATE OF discovered_via_coordinator_id, discovered_via_group_id, pending_bootstrap_grant_id, trust_provenance"].map((event, index) => trigger(`coordinator_history_peer_${index ? "update" : "insert"}`, "sync_peers", event, PEER_COORDINATOR_FIELDS, STORE_ROW("peer_trust") + DEVICE_ROW("peer_trust", "NEW.peer_device_id", "COALESCE(NEW.pinned_fingerprint, '')"))),
19342
+ trigger("coordinator_history_project_projection_insert", "recipient_managed_project_projections", "INSERT", "1", STORE_ROW("invitation")),
19343
+ trigger("coordinator_history_filter_management_insert", "peer_project_filter_management", "INSERT", "1", STORE_ROW("filter_management"))
19344
+ ];
19345
+ /** Evidence written before history existed, by table, as (kind, device_id, fingerprint) rows. */
19346
+ var STORE_EVIDENCE = "SELECT 'store' AS kind, '' AS device_id, '' AS fingerprint";
19347
+ `${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${STORE_EVIDENCE}`, `${PEER_COORDINATOR_FIELDS.replaceAll("NEW.", "")}`;
18762
19348
  [{
18763
19349
  name: "trg_identity_devices_assignment_version",
18764
19350
  create: `CREATE TRIGGER trg_identity_devices_assignment_version
@@ -18777,6 +19363,49 @@ function ownerProfileConflict() {
18777
19363
  DELETE FROM policy_team_device_decisions WHERE device_id = OLD.device_id;
18778
19364
  END`
18779
19365
  }].map(({ name, create }) => `DROP TRIGGER IF EXISTS ${name};\n${create};`).join("\n");
19366
+ //#endregion
19367
+ //#region ../core/src/transitioned-store-names.ts
19368
+ /**
19369
+ * On-disk names of a transitioned device store, and the SQL rewriting that lets
19370
+ * current code keep using the released names.
19371
+ *
19372
+ * Every object that holds memory content, or that can rebuild it, gets a name no
19373
+ * released client knows: memory text and its FTS index, embeddings, captured
19374
+ * transcripts and their flush records, prompts, summaries, artifacts, session
19375
+ * metadata (which keeps the first prompt), creation snapshots, extracted concept
19376
+ * and file references, replication op payloads and the sync identity. The
19377
+ * inventory test in `transitioned-store-inventory.test.ts` fails when a table with
19378
+ * a content-like column is added without either appearing here or being reviewed
19379
+ * as metadata there.
19380
+ *
19381
+ * Never expose a permanent view or trigger under a released name that routes reads
19382
+ * or writes to these objects.
19383
+ */
19384
+ var transitionedNames = {
19385
+ sessions: "project_sessions",
19386
+ memory_items: "project_memory_items",
19387
+ memory_fts: "project_memory_fts",
19388
+ memory_items_ai: "project_memory_items_ai",
19389
+ memory_items_au: "project_memory_items_au",
19390
+ memory_items_ad: "project_memory_items_ad",
19391
+ memory_concept_refs: "project_memory_concept_refs",
19392
+ memory_file_refs: "project_memory_file_refs",
19393
+ memory_local_creation_snapshots: "project_memory_local_creation_snapshots",
19394
+ memory_vectors: "project_memory_vectors",
19395
+ memory_vectors_rowids: "project_memory_vectors_rowids",
19396
+ memory_vectors_v1: "project_memory_vectors_v1",
19397
+ memory_vectors_v1_rowids: "project_memory_vectors_v1_rowids",
19398
+ artifacts: "project_artifacts",
19399
+ user_prompts: "project_user_prompts",
19400
+ session_summaries: "project_session_summaries",
19401
+ raw_events: "project_raw_events",
19402
+ raw_event_flush_batches: "project_raw_event_flush_batches",
19403
+ replication_ops: "project_replication_ops",
19404
+ sync_device: "project_sync_device"
19405
+ };
19406
+ new Map(Object.entries(transitionedNames));
19407
+ new Map(Object.entries(transitionedNames).map(([logical, physical]) => [physical, logical]));
19408
+ `${Object.entries(transitionedNames).flat().map((name) => `'${name}'`).join(",")}`;
18780
19409
  var BUMP = `UPDATE sync_peer_removal_check_state SET generation = generation + 1, applied_removal_seq = 0 WHERE id = 1`;
18781
19410
  [
18782
19411
  [
@@ -18804,6 +19433,15 @@ var BUMP = `UPDATE sync_peer_removal_check_state SET generation = generation + 1
18804
19433
  sql: `CREATE TRIGGER sync_peer_removal_generation_${suffix} ${event} ${condition}
18805
19434
  BEGIN ${BUMP}; END`
18806
19435
  }));
19436
+ //#endregion
19437
+ //#region ../core/src/sync-transport-policy.ts
19438
+ var TABLE$1 = "sync_peer_transport_policy";
19439
+ `${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}${TABLE$1}`;
19440
+ //#endregion
19441
+ //#region ../core/src/unpaired-peer-pin.ts
19442
+ var TABLE = "unpaired_peer_pins";
19443
+ `${TABLE}`;
19444
+ `${TABLE}`;
18807
19445
  [
18808
19446
  [
18809
19447
  "insert",
@@ -19536,6 +20174,26 @@ sqliteTable("policy_team_member_removal_enforcements", {
19536
20174
  identity_id: text("identity_id").notNull(),
19537
20175
  enforced_at: text("enforced_at").notNull()
19538
20176
  }, (table) => [primaryKey({ columns: [table.team_id, table.identity_id] })]);
20177
+ sqliteTable("policy_team_recovery_exclusions", {
20178
+ team_id: text("team_id").notNull(),
20179
+ device_id: text("device_id").notNull(),
20180
+ key_fingerprint: text("key_fingerprint").notNull(),
20181
+ reason: text("reason").notNull(),
20182
+ excluded_at: text("excluded_at").notNull()
20183
+ }, (table) => [primaryKey({ columns: [table.team_id, table.device_id] })]);
20184
+ sqliteTable("policy_team_recovery_holds", {
20185
+ team_id: text("team_id").primaryKey().notNull(),
20186
+ recovery_id: text("recovery_id").notNull(),
20187
+ reason: text("reason").notNull(),
20188
+ held_at: text("held_at").notNull()
20189
+ });
20190
+ sqliteTable("policy_team_recovery_skipped_projects", {
20191
+ team_id: text("team_id").notNull(),
20192
+ project_identity: text("project_identity").notNull(),
20193
+ recovery_id: text("recovery_id").notNull(),
20194
+ reason: text("reason").notNull(),
20195
+ skipped_at: text("skipped_at").notNull()
20196
+ }, (table) => [primaryKey({ columns: [table.team_id, table.project_identity] })]);
19539
20197
  sqliteTable("identity_devices", {
19540
20198
  device_id: text("device_id").primaryKey(),
19541
20199
  identity_id: text("identity_id").notNull(),
@@ -20977,19 +21635,35 @@ function prepareChannelRequest(input) {
20977
21635
  peerPin
20978
21636
  };
20979
21637
  }
21638
+ function channelMode(kind, peers, maxEntryBytes) {
21639
+ if (kind === "relay") return {
21640
+ kind,
21641
+ maxEntryBytes,
21642
+ peerPin: (request) => peers.get(request)?.pin ?? null
21643
+ };
21644
+ return {
21645
+ kind,
21646
+ maxEntryBytes,
21647
+ peer: (request) => peers.get(request) ?? null
21648
+ };
21649
+ }
20980
21650
  function createSyncChannelDispatcher(options) {
20981
21651
  const storeFactory = options.storeFactory.bind(options);
20982
- const pins = /* @__PURE__ */ new WeakMap();
21652
+ const peers = /* @__PURE__ */ new WeakMap();
20983
21653
  const app = createSyncApp$1({
20984
21654
  storeFactory,
20985
- syncChannelPeerPin: (request) => pins.get(request) ?? null
21655
+ mode: channelMode(options.mode ?? "relay", peers, options.maxEntryBytes),
21656
+ syncRequestRateLimit: options.limiter ? { limiter: options.limiter } : void 0
20986
21657
  });
20987
21658
  return async (input) => {
20988
21659
  const prepared = prepareChannelRequest(input);
20989
21660
  if (!("request" in prepared)) return prepared;
20990
21661
  const { request, peerPin } = prepared;
20991
21662
  const signal = request.signal;
20992
- pins.set(request, peerPin);
21663
+ peers.set(request, {
21664
+ pin: peerPin,
21665
+ deviceId: input.peerDeviceId ?? ""
21666
+ });
20993
21667
  try {
20994
21668
  checkCancellation(signal);
20995
21669
  const response = await app.fetch(request);
@@ -21000,7 +21674,7 @@ function createSyncChannelDispatcher(options) {
21000
21674
  bodyBytes
21001
21675
  };
21002
21676
  } finally {
21003
- pins.delete(request);
21677
+ peers.delete(request);
21004
21678
  }
21005
21679
  };
21006
21680
  }
@@ -21323,6 +21997,465 @@ function createViewerRelayReachability(options) {
21323
21997
  };
21324
21998
  }
21325
21999
  //#endregion
22000
+ //#region src/response-byte-budget.ts
22001
+ /**
22002
+ * Bounds the response bytes a listener may hold in memory at once. Each
22003
+ * exchange reserves the largest response it could produce before the response
22004
+ * is collected, and releases the reservation once the response is written.
22005
+ * Waiters are served in arrival order.
22006
+ */
22007
+ var ResponseByteBudget = class {
22008
+ totalBytes;
22009
+ available;
22010
+ waiters = [];
22011
+ constructor(totalBytes) {
22012
+ this.totalBytes = totalBytes;
22013
+ if (!Number.isSafeInteger(totalBytes) || totalBytes <= 0) throw new RangeError("Response byte budget must be a positive integer");
22014
+ this.available = totalBytes;
22015
+ }
22016
+ /** Resolves with a release function once the bytes are reserved. */
22017
+ async acquire(bytes, signal) {
22018
+ if (!Number.isSafeInteger(bytes) || bytes <= 0 || bytes > this.totalBytes) throw new RangeError("Response reservation exceeds the budget");
22019
+ signal?.throwIfAborted();
22020
+ if (this.waiters.length === 0 && this.available >= bytes) {
22021
+ this.available -= bytes;
22022
+ return this.releaser(bytes);
22023
+ }
22024
+ await new Promise((resolve, reject) => {
22025
+ const waiter = {
22026
+ bytes,
22027
+ resolve
22028
+ };
22029
+ this.waiters.push(waiter);
22030
+ signal?.addEventListener("abort", () => {
22031
+ const index = this.waiters.indexOf(waiter);
22032
+ if (index < 0) return;
22033
+ this.waiters.splice(index, 1);
22034
+ reject(signal.reason ?? /* @__PURE__ */ new Error("Response reservation cancelled"));
22035
+ this.drain();
22036
+ }, { once: true });
22037
+ });
22038
+ return this.releaser(bytes);
22039
+ }
22040
+ get availableBytes() {
22041
+ return this.available;
22042
+ }
22043
+ releaser(bytes) {
22044
+ let released = false;
22045
+ return () => {
22046
+ if (released) return;
22047
+ released = true;
22048
+ this.available += bytes;
22049
+ this.drain();
22050
+ };
22051
+ }
22052
+ drain() {
22053
+ while (this.waiters[0] && this.available >= this.waiters[0].bytes) {
22054
+ const next = this.waiters.shift();
22055
+ if (!next) return;
22056
+ this.available -= next.bytes;
22057
+ next.resolve();
22058
+ }
22059
+ }
22060
+ };
22061
+ //#endregion
22062
+ //#region src/sync-noise-gate.ts
22063
+ var DIRECT_NOISE_GATE_LIMITS = Object.freeze({
22064
+ pendingTotal: 32,
22065
+ pendingPerIp: 4,
22066
+ streamsTotal: 256,
22067
+ streamsPerPeer: 8,
22068
+ responseBudgetBytes: 134217728,
22069
+ handshakeMs: RELAY_NOISE_LIMITS.handshakeMs
22070
+ });
22071
+ /** Open slots in total and per key, each released exactly once. */
22072
+ var Counter = class {
22073
+ maxTotal;
22074
+ maxPerKey;
22075
+ total = 0;
22076
+ byKey = /* @__PURE__ */ new Map();
22077
+ constructor(maxTotal, maxPerKey) {
22078
+ this.maxTotal = maxTotal;
22079
+ this.maxPerKey = maxPerKey;
22080
+ }
22081
+ reserve(key) {
22082
+ const count = this.byKey.get(key) ?? 0;
22083
+ if (this.total >= this.maxTotal || count >= this.maxPerKey) return null;
22084
+ this.total += 1;
22085
+ this.byKey.set(key, count + 1);
22086
+ let released = false;
22087
+ return () => {
22088
+ if (released) return;
22089
+ released = true;
22090
+ this.total -= 1;
22091
+ const remaining = (this.byKey.get(key) ?? 1) - 1;
22092
+ if (remaining > 0) this.byKey.set(key, remaining);
22093
+ else this.byKey.delete(key);
22094
+ };
22095
+ }
22096
+ };
22097
+ var GateRefusal = class extends Error {
22098
+ status;
22099
+ body;
22100
+ constructor(status, body) {
22101
+ super(body);
22102
+ this.status = status;
22103
+ this.body = body;
22104
+ }
22105
+ };
22106
+ var STATUS_TEXT = {
22107
+ 400: "Bad Request",
22108
+ 401: "Unauthorized",
22109
+ 429: "Too Many Requests",
22110
+ 503: "Service Unavailable"
22111
+ };
22112
+ /** Time a refused client has to read its refusal before the socket is destroyed anyway. */
22113
+ var REFUSAL_FLUSH_MS = 1e3;
22114
+ /**
22115
+ * Sends a plain HTTP refusal, then destroys the socket. Ending it would wait
22116
+ * for the client to close its side, so a client that kept writing open would
22117
+ * keep holding the socket and its slot.
22118
+ */
22119
+ function refuse(socket, refusal) {
22120
+ const body = JSON.stringify({ error: refusal.body });
22121
+ const timer = setTimeout(() => socket.destroy(), REFUSAL_FLUSH_MS);
22122
+ timer.unref();
22123
+ socket.write(`HTTP/1.1 ${refusal.status} ${STATUS_TEXT[refusal.status]}\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`, () => {
22124
+ clearTimeout(timer);
22125
+ socket.destroy();
22126
+ });
22127
+ }
22128
+ function headerValue(request, name) {
22129
+ const value = request.headers[name.toLowerCase()];
22130
+ return typeof value === "string" ? value : void 0;
22131
+ }
22132
+ /** A canonical upgrade request with nothing sent after its headers, or a refusal. */
22133
+ function parseUpgrade(request, head) {
22134
+ const target = parseDirectNoiseUpgradeTarget(request.url);
22135
+ const protocol = headerValue(request, "upgrade")?.trim().toLowerCase();
22136
+ if (request.method !== "GET" || protocol !== DIRECT_NOISE_UPGRADE_PROTOCOL || !target) throw new GateRefusal(400, "invalid_upgrade");
22137
+ if (head.byteLength !== 0) throw new GateRefusal(400, "invalid_upgrade");
22138
+ return target;
22139
+ }
22140
+ function authorize(store, request) {
22141
+ const auth = authorizeDirectNoiseUpgrade(store, {
22142
+ method: "GET",
22143
+ url: `${DIRECT_NOISE_LOGICAL_ORIGIN}${request.url}`,
22144
+ header: (name) => headerValue(request, name)
22145
+ });
22146
+ if (!auth.ok) throw new GateRefusal(auth.busy ? 503 : 401, auth.busy ? "busy" : "unauthorized");
22147
+ return auth;
22148
+ }
22149
+ function localIdentity(store, keysDir) {
22150
+ const row = store.db.prepare("SELECT device_id, public_key FROM sync_device LIMIT 1").get();
22151
+ const bytes = row ? loadPrivateKey(keysDir, store.dbPath, row.device_id) : null;
22152
+ if (!row?.public_key || !bytes) throw new GateRefusal(503, "unavailable");
22153
+ return {
22154
+ key: createPrivateKey(bytes),
22155
+ expectedPin: row.public_key.trim()
22156
+ };
22157
+ }
22158
+ /** The peer's key as pinned now. A re-pin during the handshake ends the stream. */
22159
+ function currentPin(store, deviceId) {
22160
+ const row = store.db.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
22161
+ const publicKey = row?.public_key?.trim();
22162
+ if (!publicKey || fingerprintPublicKey(publicKey) !== row?.pinned_fingerprint) return null;
22163
+ return publicKey;
22164
+ }
22165
+ function switchProtocols(socket) {
22166
+ return new Promise((resolve, reject) => {
22167
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: ${DIRECT_NOISE_UPGRADE_PROTOCOL}\r\nConnection: Upgrade\r\n\r\n`, (error) => error ? reject(error) : resolve());
22168
+ });
22169
+ }
22170
+ function ownStream(socket, duplex) {
22171
+ const completion = Promise.all([finished(duplex, { cleanup: true }), finished(socket, { cleanup: true })]).then(() => {});
22172
+ completion.catch(() => {});
22173
+ return {
22174
+ duplex,
22175
+ completion,
22176
+ async dispose(error) {
22177
+ duplex.destroy(error);
22178
+ socket.destroy(error);
22179
+ await completion.catch(() => {});
22180
+ }
22181
+ };
22182
+ }
22183
+ /**
22184
+ * Milliseconds left before the gate's one deadline, which starts when the
22185
+ * upgrade arrives. Synchronous work such as signature checks or key loading
22186
+ * cannot run the timer, so each step checks the clock itself.
22187
+ */
22188
+ function remainingMs(deadlineAt) {
22189
+ const remaining = Math.floor(deadlineAt - performance$1.now());
22190
+ if (remaining <= 0) throw new Error("Direct Noise admission deadline passed");
22191
+ return remaining;
22192
+ }
22193
+ async function handshake(context, socket, admission, peer) {
22194
+ const store = context.options.storeFactory();
22195
+ const identity = localIdentity(store, context.options.keysDir);
22196
+ remainingMs(admission.deadlineAt);
22197
+ await switchProtocols(socket);
22198
+ const acceptedAtMs = performance$1.now();
22199
+ const handshakeMs = remainingMs(admission.deadlineAt);
22200
+ const secured = await acceptRelayNoiseResponder({
22201
+ transport: socket,
22202
+ localIdentity: identity,
22203
+ expectedRemotePin: peer.publicKey,
22204
+ context: {
22205
+ transportLabel: DIRECT_NOISE_TRANSPORT_LABEL,
22206
+ sessionId: admission.target.sessionId
22207
+ },
22208
+ verifiedMessageADigest: admission.target.openingDigest,
22209
+ acceptedAtMs,
22210
+ deadlineMs: acceptedAtMs + handshakeMs + PEER_HTTP_LIMITS.exchangeMs,
22211
+ limits: { handshakeMs }
22212
+ });
22213
+ if (currentPin(store, peer.deviceId) !== peer.publicKey) {
22214
+ secured.duplex.destroy();
22215
+ throw new Error("Peer key changed during the handshake");
22216
+ }
22217
+ return secured.duplex;
22218
+ }
22219
+ /** One exchange, holding a response reservation from dispatch until the response is written. */
22220
+ async function serveStream(context, socket, duplex, deviceId) {
22221
+ let release;
22222
+ try {
22223
+ await servePeerHttpConnection(ownStream(socket, duplex), {
22224
+ origin: DIRECT_NOISE_LOGICAL_ORIGIN,
22225
+ dispatch: async (request) => {
22226
+ release = await context.budget.acquire(PEER_HTTP_LIMITS.responseBytes, request.signal);
22227
+ return context.dispatch({
22228
+ ...request,
22229
+ peerDeviceId: deviceId
22230
+ });
22231
+ }
22232
+ });
22233
+ } finally {
22234
+ release?.();
22235
+ }
22236
+ }
22237
+ async function handleUpgrade(context, request, socket, head, upgrade) {
22238
+ const releasePending = context.pending.reserve(upgrade.address);
22239
+ if (!releasePending) throw new GateRefusal(503, "busy");
22240
+ const deadline = setTimeout(() => socket.destroy(), Math.max(1, upgrade.deadlineAt - performance$1.now()));
22241
+ deadline.unref();
22242
+ let releaseStream = null;
22243
+ try {
22244
+ const target = parseUpgrade(request, head);
22245
+ const peer = authorize(context.options.storeFactory(), request);
22246
+ releaseStream = context.streams.reserve(peer.deviceId);
22247
+ if (!releaseStream) throw new GateRefusal(503, "busy");
22248
+ const duplex = await handshake(context, socket, {
22249
+ target,
22250
+ deadlineAt: upgrade.deadlineAt
22251
+ }, peer);
22252
+ clearTimeout(deadline);
22253
+ if (performance$1.now() >= upgrade.deadlineAt) {
22254
+ duplex.destroy();
22255
+ throw new Error("Direct Noise admission deadline passed");
22256
+ }
22257
+ releasePending();
22258
+ await serveStream(context, socket, duplex, peer.deviceId);
22259
+ } finally {
22260
+ clearTimeout(deadline);
22261
+ releasePending();
22262
+ releaseStream?.();
22263
+ }
22264
+ }
22265
+ /**
22266
+ * Accepts direct Noise upgrades on the sync listener. Each address is
22267
+ * throttled with the listener's own budget before any signature check, and
22268
+ * every refusal before 101 is plain HTTP that carries no Noise bytes.
22269
+ */
22270
+ function attachDirectNoiseGate(server, options, admit, addressOf) {
22271
+ const limits = {
22272
+ ...DIRECT_NOISE_GATE_LIMITS,
22273
+ ...options.limits
22274
+ };
22275
+ const context = {
22276
+ options,
22277
+ limits,
22278
+ pending: new Counter(limits.pendingTotal, limits.pendingPerIp),
22279
+ streams: new Counter(limits.streamsTotal, limits.streamsPerPeer),
22280
+ budget: new ResponseByteBudget(limits.responseBudgetBytes),
22281
+ dispatch: createSyncChannelDispatcher({
22282
+ storeFactory: () => options.storeFactory(),
22283
+ mode: "noise-direct",
22284
+ limiter: admit.limiter
22285
+ })
22286
+ };
22287
+ server.on("upgrade", (request, socket, head) => {
22288
+ const deadlineAt = performance$1.now() + limits.handshakeMs;
22289
+ admit.settle(socket);
22290
+ socket.on("error", () => {});
22291
+ const address = addressOf(socket);
22292
+ if (!(admit.perMinute === void 0 ? { allowed: true } : admit.limiter.check(`sync-listener:${address}`, admit.perMinute)).allowed) {
22293
+ refuse(socket, new GateRefusal(429, "rate_limited"));
22294
+ return;
22295
+ }
22296
+ handleUpgrade(context, request, socket, head, {
22297
+ address,
22298
+ deadlineAt
22299
+ }).catch((error) => {
22300
+ if (error instanceof GateRefusal && !socket.destroyed) refuse(socket, error);
22301
+ else socket.destroy();
22302
+ });
22303
+ });
22304
+ }
22305
+ //#endregion
22306
+ //#region src/sync-listener-guard.ts
22307
+ var SYNC_LISTENER_LIMITS = Object.freeze({
22308
+ headerMs: 1e4,
22309
+ requestMs: 3e4,
22310
+ checkIntervalMs: 1e3
22311
+ });
22312
+ /**
22313
+ * Caps from `pnpm run load:sync-listener`
22314
+ * (packages/viewer-server/scripts/sync-listener-load.ts). With them, an
22315
+ * authenticated flood or idle streams from one address left another
22316
+ * address's sync p95 within 10% of idle, at under 16 MiB added memory, and
22317
+ * 128 devices behind one address that start syncing within 10 s all succeed.
22318
+ * They apply only while the listener runs direct Noise, so the plain listener
22319
+ * behaves as before until activation.
22320
+ */
22321
+ var SYNC_LISTENER_CAPS = Object.freeze({
22322
+ maxSockets: 256,
22323
+ maxSocketsPerIp: 16,
22324
+ requestsPerIpPerMinute: 600
22325
+ });
22326
+ /**
22327
+ * Distinct address buckets the listener's limiter keeps. When it is full, new
22328
+ * addresses share one overflow budget until a bucket goes unused for a minute.
22329
+ */
22330
+ var SYNC_LISTENER_MAX_BUCKETS = 4096;
22331
+ /**
22332
+ * The limiter the sync listener, its routes and its Noise streams share. It
22333
+ * holds at most SYNC_LISTENER_MAX_BUCKETS buckets.
22334
+ */
22335
+ function createSyncListenerLimiter() {
22336
+ return createInMemoryRequestRateLimiter(6e4, { maxBuckets: SYNC_LISTENER_MAX_BUCKETS });
22337
+ }
22338
+ /** The eight 16-bit groups of an IPv6 address, or null when it does not parse. */
22339
+ function ipv6Groups(address) {
22340
+ const [head = "", tail, extra] = address.split("::");
22341
+ if (extra !== void 0) return null;
22342
+ const left = head ? head.split(":") : [];
22343
+ const right = tail ? tail.split(":") : [];
22344
+ const missing = 8 - left.length - right.length;
22345
+ if (tail === void 0 && missing !== 0 || tail !== void 0 && missing < 1) return null;
22346
+ const groups = [
22347
+ ...left,
22348
+ ...Array(tail === void 0 ? 0 : missing).fill("0"),
22349
+ ...right
22350
+ ];
22351
+ if (!groups.every((group) => /^[0-9a-f]{1,4}$/i.test(group))) return null;
22352
+ return groups.map((group) => Number.parseInt(group, 16));
22353
+ }
22354
+ /**
22355
+ * One key per client address. IPv4 clients of a dual-stack socket arrive as
22356
+ * ::ffff:a.b.c.d. An IPv6 client usually holds a whole /64, so its addresses
22357
+ * share one key and cannot multiply its share of the caps.
22358
+ */
22359
+ function remoteAddressKey(socket) {
22360
+ const address = (socket.remoteAddress ?? "unknown").split("%")[0] ?? "unknown";
22361
+ if (address.startsWith("::ffff:") && address.includes(".")) return address.slice(7);
22362
+ if (!address.includes(":")) return address;
22363
+ const groups = ipv6Groups(address);
22364
+ if (!groups) return address;
22365
+ return `${groups.slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
22366
+ }
22367
+ function refuseRateLimited(response, retryAfterS) {
22368
+ response.writeHead(429, {
22369
+ "content-type": "application/json",
22370
+ "retry-after": String(retryAfterS),
22371
+ connection: "close"
22372
+ });
22373
+ response.end(JSON.stringify({
22374
+ error: "rate_limited",
22375
+ retry_after_s: retryAfterS
22376
+ }));
22377
+ }
22378
+ /** Counts open sockets per address and closes any over the cap as soon as it connects. */
22379
+ function capSocketsPerAddress(server, maxPerAddress) {
22380
+ const open = /* @__PURE__ */ new Map();
22381
+ server.on("connection", (socket) => {
22382
+ const key = remoteAddressKey(socket);
22383
+ const count = (open.get(key) ?? 0) + 1;
22384
+ open.set(key, count);
22385
+ socket.once("close", () => {
22386
+ const remaining = (open.get(key) ?? 1) - 1;
22387
+ if (remaining > 0) open.set(key, remaining);
22388
+ else open.delete(key);
22389
+ });
22390
+ if (count > maxPerAddress) socket.destroy();
22391
+ });
22392
+ }
22393
+ /**
22394
+ * Closes a socket that has not delivered complete headers in time. Node's own
22395
+ * header timeout also applies, but this timer starts at connect and does not
22396
+ * depend on Node's check interval. Returns the function that stops a socket's
22397
+ * timer. An upgrade handler must call it, because Node applies no timeouts to
22398
+ * an upgraded socket. With no upgrade handler, Node serves an Upgrade request
22399
+ * as an ordinary request, which stops the timer.
22400
+ */
22401
+ function closeSilentSockets(server, limits) {
22402
+ const timers = /* @__PURE__ */ new WeakMap();
22403
+ const settle = (socket) => {
22404
+ clearTimeout(timers.get(socket));
22405
+ timers.delete(socket);
22406
+ };
22407
+ server.on("connection", (socket) => {
22408
+ const timer = setTimeout(() => socket.destroy(), limits.headerMs);
22409
+ timer.unref();
22410
+ timers.set(socket, timer);
22411
+ socket.once("close", () => settle(socket));
22412
+ });
22413
+ server.on("request", (request) => settle(request.socket));
22414
+ return settle;
22415
+ }
22416
+ /** Answers 429 when the address is over its budget. Always allows while the limit is off. */
22417
+ function admitRequest(limiter, perMinute, request, response) {
22418
+ if (perMinute === void 0) return true;
22419
+ const result = limiter.check(`sync-listener:${remoteAddressKey(request.socket)}`, perMinute);
22420
+ if (!result.allowed) refuseRateLimited(response, result.retryAfterS);
22421
+ return result.allowed;
22422
+ }
22423
+ /**
22424
+ * A createServer replacement for the sync listener. It bounds how long headers
22425
+ * and requests may take, and can cap sockets and throttle each address before
22426
+ * the sync routes verify any signature.
22427
+ */
22428
+ function createGuardedSyncServer(options = {}) {
22429
+ const noiseActive = options.directNoise?.active ?? DIRECT_NOISE_ACTIVE;
22430
+ const caps = noiseActive ? SYNC_LISTENER_CAPS : {};
22431
+ const limits = {
22432
+ ...SYNC_LISTENER_LIMITS,
22433
+ ...caps,
22434
+ ...options.limits
22435
+ };
22436
+ const limiter = options.limiter ?? createSyncListenerLimiter();
22437
+ const guarded = (_serverOptions, listener) => {
22438
+ const server = createServer({
22439
+ headersTimeout: limits.headerMs,
22440
+ requestTimeout: limits.requestMs,
22441
+ connectionsCheckingInterval: limits.checkIntervalMs
22442
+ }, (request, response) => {
22443
+ if (admitRequest(limiter, limits.requestsPerIpPerMinute, request, response)) listener?.(request, response);
22444
+ });
22445
+ if (limits.maxSockets !== void 0) server.maxConnections = limits.maxSockets;
22446
+ if (limits.maxSocketsPerIp !== void 0) capSocketsPerAddress(server, limits.maxSocketsPerIp);
22447
+ const settle = closeSilentSockets(server, limits);
22448
+ const directNoise = options.directNoise;
22449
+ if (directNoise && noiseActive) attachDirectNoiseGate(server, directNoise, {
22450
+ limiter,
22451
+ perMinute: limits.requestsPerIpPerMinute,
22452
+ settle
22453
+ }, remoteAddressKey);
22454
+ return server;
22455
+ };
22456
+ return guarded;
22457
+ }
22458
+ //#endregion
21326
22459
  //#region src/index.ts
21327
22460
  /**
21328
22461
  * @codemem/server — HTTP server (viewer, sync, API).
@@ -21408,10 +22541,15 @@ function registerViewerSyncRoutes(app, storeFactory, opts, onRecipientPolicyTeam
21408
22541
  readCoordinatorConfig: opts?.readCoordinatorConfig,
21409
22542
  runManualCoordinatorRefresh: opts?.runManualCoordinatorRefresh,
21410
22543
  renameCoordinatorGroup: opts?.renameCoordinatorGroup,
21411
- lookupCoordinatorDeviceAnswer: opts?.lookupCoordinatorDeviceAnswer,
21412
22544
  deviceLifecycleActions: Boolean(opts?.createDeviceRemovalRefreshHooks)
21413
22545
  }));
21414
22546
  }
22547
+ /** Routes only an admin device may use on a Team: removing a member, and recovering a disabled Team. */
22548
+ function registerTeamAdminRoutes(app, storeFactory, opts) {
22549
+ const options = { readCoordinatorConfig: opts?.readCoordinatorConfig };
22550
+ app.route("/", teamMemberRemovalRoutes(storeFactory, options));
22551
+ app.route("/", teamRecoveryRoutes(storeFactory, options));
22552
+ }
21415
22553
  function registerViewerDeviceRemoval(app, storeFactory, opts) {
21416
22554
  const createDeviceRemovalRefreshHooks = opts?.createDeviceRemovalRefreshHooks;
21417
22555
  app.route("/", deviceRejoinEventRoutes({
@@ -21483,7 +22621,7 @@ function createApp(opts) {
21483
22621
  registerViewerSyncRoutes(app, storeFactory, opts, () => invalidateTeamSetupSummary());
21484
22622
  registerViewerDeviceRemoval(app, storeFactory, opts);
21485
22623
  app.route("/", teamCreateRoutes(storeFactory, opts?.readCoordinatorConfig));
21486
- app.route("/", teamMemberRemovalRoutes(storeFactory, { readCoordinatorConfig: opts?.readCoordinatorConfig }));
22624
+ registerTeamAdminRoutes(app, storeFactory, opts);
21487
22625
  app.route("/", projectWithdrawalRoutes(storeFactory));
21488
22626
  app.route("/", teamSetupRoutes({
21489
22627
  getStore: storeFactory,
@@ -21509,6 +22647,6 @@ function createSyncApp(opts) {
21509
22647
  return createSyncApp$1(opts);
21510
22648
  }
21511
22649
  //#endregion
21512
- export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, convertLegacyPairingAssignmentsOperation, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createRecipientInvitation, createRecipientPolicyReconcilerEffects, createSyncApp, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, previewRecipientInvitation, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
22650
+ export { FileRawEventInbox, MEMORY_TOOL_CALL_CAPABILITY, VERSION, advancePendingProjectShares, advancePendingProjectSharesOperation, advanceProjectShareOperation, closeStore, closeStoreAsync, convertLegacyPairingAssignmentsOperation, createAccountContextReader, createAccountLinkRegistry, createAccountOwnerRecoveryService, createAccountRebindRunner, createApp, createGuardedSyncServer, createRecipientInvitation, createRecipientPolicyReconcilerEffects, createSyncApp, createSyncListenerLimiter, createViewerRawEventInbox, createViewerRelayReachability, getStore, listRecipientPolicyReconciliationStatus, memoryToolCallRoutes, previewRecipientInvitation, recipientPolicyCapabilityFromStatus, reconcileConfiguredCoordinatorEnrollment, reconcileRecipientPolicyProjects, reconcileRecipientPolicyProjectsOperation, resolveRawEventInboxDirectory, resumeAccountRebind };
21513
22651
 
21514
22652
  //# sourceMappingURL=index.js.map