@codemem/server 0.49.0-beta.1 → 0.49.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/device-connection.d.ts +7 -0
- package/dist/account/device-connection.d.ts.map +1 -0
- package/dist/account/rebind.d.ts +2 -0
- package/dist/account/rebind.d.ts.map +1 -1
- package/dist/account/status.d.ts +4 -1
- package/dist/account/status.d.ts.map +1 -1
- package/dist/application/coordinator-enrollment-context.d.ts +21 -0
- package/dist/application/coordinator-enrollment-context.d.ts.map +1 -0
- package/dist/index.js +284 -209
- package/dist/index.js.map +1 -1
- package/dist/routes/diagnostics.d.ts.map +1 -1
- package/dist/routes/memory.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +6 -4
- package/dist/routes/sync.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +34 -34
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +13 -2
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, LegacyTeamSetupRosterCapacityError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, 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, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, 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, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
|
|
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, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, 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, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, 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, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceSetup, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, 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";
|
|
@@ -592,6 +592,55 @@ function createAccountLinkRegistry(options) {
|
|
|
592
592
|
return new InProcessAccountLinkRegistry(options);
|
|
593
593
|
}
|
|
594
594
|
//#endregion
|
|
595
|
+
//#region src/account/device-connection.ts
|
|
596
|
+
/** Eligibility is a signed read. Only an explicit sign-in starts the existing ceremony. */
|
|
597
|
+
async function attachDeviceConnection(options, context, view, signal) {
|
|
598
|
+
if (!options.registry?.supportsSignIn?.() || view.ownerProjection || view.remote.kind !== "status" || view.remote.state !== "linked" || !view.remote.identityMatches) return;
|
|
599
|
+
const read = options.readRemoteDeviceSetup ?? (options.readRemoteStatus ? null : readCoordinatorDeviceSetup);
|
|
600
|
+
if (!read) return;
|
|
601
|
+
const before = options.readContext(context.groupId);
|
|
602
|
+
if ("error" in before || before.setup !== "ready" || !before.context || !sameAuthority(context, before.context)) {
|
|
603
|
+
contextChanged(view);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
let connectRequired = false;
|
|
607
|
+
try {
|
|
608
|
+
const { dbPath, keysDir, coordinatorUrl, groupId, identityId } = context;
|
|
609
|
+
connectRequired = (await read({
|
|
610
|
+
dbPath,
|
|
611
|
+
keysDir,
|
|
612
|
+
coordinatorUrl,
|
|
613
|
+
groupId,
|
|
614
|
+
currentIdentityId: identityId,
|
|
615
|
+
signal
|
|
616
|
+
})).kind === "connect_required";
|
|
617
|
+
} catch {}
|
|
618
|
+
try {
|
|
619
|
+
const after = options.readContext(context.groupId);
|
|
620
|
+
if (signal.aborted || JSON.stringify(before) !== JSON.stringify(after)) {
|
|
621
|
+
contextChanged(view);
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
} catch {
|
|
625
|
+
contextChanged(view);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
if (!connectRequired) return;
|
|
629
|
+
view.canConnectDevice = true;
|
|
630
|
+
view.canSignIn = true;
|
|
631
|
+
view.blockedReason = null;
|
|
632
|
+
}
|
|
633
|
+
function contextChanged(view) {
|
|
634
|
+
view.remote = {
|
|
635
|
+
kind: "unavailable",
|
|
636
|
+
code: "context_changed"
|
|
637
|
+
};
|
|
638
|
+
view.blockedReason = "status_unavailable";
|
|
639
|
+
view.canLink = false;
|
|
640
|
+
view.canSignIn = false;
|
|
641
|
+
view.canConnectDevice = false;
|
|
642
|
+
}
|
|
643
|
+
//#endregion
|
|
595
644
|
//#region src/account/owner-status.ts
|
|
596
645
|
/** The coordinator ID comes from the first signed actor-status read, never the origin. */
|
|
597
646
|
function readOwnerAssociation(context, coordinatorId) {
|
|
@@ -771,7 +820,7 @@ function withOwnerSignIn(owner, own, context, remote) {
|
|
|
771
820
|
};
|
|
772
821
|
}
|
|
773
822
|
function attachOperation(input, registry, operationContextId = input.contextId) {
|
|
774
|
-
const { canSignIn, signIn, ...rest } = input;
|
|
823
|
+
const { canSignIn, canConnectDevice, signIn, ...rest } = input;
|
|
775
824
|
const view = registry?.supportsSignIn?.() ? input : rest;
|
|
776
825
|
const operation = operationContextId ? registry?.forContext(operationContextId) ?? null : null;
|
|
777
826
|
const operationContext = operation && operationContextId && operationContextId !== view.contextId ? { operationContextId } : {};
|
|
@@ -781,6 +830,7 @@ function attachOperation(input, registry, operationContextId = input.contextId)
|
|
|
781
830
|
operation,
|
|
782
831
|
canLink: false,
|
|
783
832
|
..."canSignIn" in view ? { canSignIn: false } : {},
|
|
833
|
+
..."canConnectDevice" in view ? { canConnectDevice: false } : {},
|
|
784
834
|
blockedReason: "operation_active"
|
|
785
835
|
};
|
|
786
836
|
return {
|
|
@@ -981,6 +1031,7 @@ async function finishAccountStatus(options, context, fresh, remote, read) {
|
|
|
981
1031
|
return attachOperation(owner, options.registry, context.contextId);
|
|
982
1032
|
}
|
|
983
1033
|
}
|
|
1034
|
+
await attachDeviceConnection(options, context, currentView, signal);
|
|
984
1035
|
await attachManagementActions(options, context, currentView, signal);
|
|
985
1036
|
if (remote.kind === "status") try {
|
|
986
1037
|
if (readOwnerAssociation(context, remote.status.coordinatorId)) return attachOperation(ownerUnavailable(accountLocalView(fresh), "context_changed"), options.registry);
|
|
@@ -1053,6 +1104,8 @@ async function attachManagementActions(options, context, view, signal) {
|
|
|
1053
1104
|
code: "context_changed"
|
|
1054
1105
|
};
|
|
1055
1106
|
view.blockedReason = "status_unavailable";
|
|
1107
|
+
view.canSignIn = false;
|
|
1108
|
+
view.canConnectDevice = false;
|
|
1056
1109
|
return;
|
|
1057
1110
|
}
|
|
1058
1111
|
if (capabilities?.kind !== "capabilities" || capabilities.coordinatorId !== view.remote.coordinatorId) return;
|
|
@@ -2246,12 +2299,16 @@ function observerSelect(options) {
|
|
|
2246
2299
|
updated_at AS occurred_at, status, attempt_count AS metric_a,
|
|
2247
2300
|
NULL AS metric_b,
|
|
2248
2301
|
CASE
|
|
2302
|
+
WHEN error_type = 'RawEventObserverOutputError:no_processable_input' THEN 'input preparation'
|
|
2303
|
+
WHEN error_type = 'RawEventObserverOutputError:lossy_repair' THEN 'structural repair'
|
|
2304
|
+
WHEN error_type = 'RawEventObserverOutputError:unstorable_observer_output' THEN 'output validation and filtering'
|
|
2249
2305
|
WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%auth%' THEN 'authentication'
|
|
2250
2306
|
WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%rate%'
|
|
2251
2307
|
OR lower(COALESCE(observer_error_code, error_type)) LIKE '%limit%' THEN 'rate limit'
|
|
2252
2308
|
WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%timeout%' THEN 'timeout'
|
|
2253
2309
|
WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%schema%'
|
|
2254
2310
|
OR lower(COALESCE(observer_error_code, error_type)) LIKE '%parse%' THEN 'response format'
|
|
2311
|
+
WHEN error_type = 'RawEventObserverOutputError:empty_observer_output' THEN 'empty response'
|
|
2255
2312
|
ELSE 'unspecified'
|
|
2256
2313
|
END AS category,
|
|
2257
2314
|
NULL AS stored_category
|
|
@@ -3298,12 +3355,13 @@ function memoryRoutes(getStore) {
|
|
|
3298
3355
|
const clauses = [
|
|
3299
3356
|
"memory_items.session_id = sessions.id",
|
|
3300
3357
|
"memory_items.active = 1",
|
|
3301
|
-
"sessions.project IS NOT NULL",
|
|
3302
3358
|
...filterResult.clauses
|
|
3303
3359
|
];
|
|
3304
|
-
const rows = store.db.prepare(`SELECT
|
|
3305
|
-
|
|
3306
|
-
WHERE
|
|
3360
|
+
const rows = store.db.prepare(`SELECT candidates.project AS project
|
|
3361
|
+
FROM (SELECT DISTINCT project FROM sessions WHERE project IS NOT NULL) candidates
|
|
3362
|
+
WHERE EXISTS (SELECT 1 FROM sessions
|
|
3363
|
+
WHERE sessions.project = candidates.project
|
|
3364
|
+
AND EXISTS (SELECT 1 FROM memory_items WHERE ${clauses.join(" AND ")}))`).all(...filterResult.params);
|
|
3307
3365
|
const projects = [...new Set(rows.map((r) => String(r.project ?? "").trim()).filter((p) => p && !p.toLowerCase().startsWith("fatal:")).map((p) => projectBasename(p)).filter(Boolean))].sort();
|
|
3308
3366
|
return c.json({ projects });
|
|
3309
3367
|
}
|
|
@@ -5771,6 +5829,85 @@ function healthStats(store) {
|
|
|
5771
5829
|
};
|
|
5772
5830
|
}
|
|
5773
5831
|
//#endregion
|
|
5832
|
+
//#region src/application/coordinator-enrollment-context.ts
|
|
5833
|
+
function readLocalDevice$1(store, keysDir) {
|
|
5834
|
+
try {
|
|
5835
|
+
const before = statSync(store.dbPath, { bigint: true });
|
|
5836
|
+
const device = readAccountLinkDevice(store.dbPath);
|
|
5837
|
+
const key = loadRuntimeSigningPublicKey(store.db, {
|
|
5838
|
+
deviceId: store.deviceId,
|
|
5839
|
+
keysDir
|
|
5840
|
+
});
|
|
5841
|
+
const after = statSync(store.dbPath, { bigint: true });
|
|
5842
|
+
if (!before.isFile() || before.dev !== after.dev || before.ino !== after.ino || device.deviceId !== store.deviceId || !key || fingerprintPublicKey(key) !== device.fingerprint) throw new Error("device_unavailable");
|
|
5843
|
+
return {
|
|
5844
|
+
device,
|
|
5845
|
+
fileIdentity: `${after.dev}:${after.ino}`
|
|
5846
|
+
};
|
|
5847
|
+
} catch {
|
|
5848
|
+
throw new Error("device_unavailable");
|
|
5849
|
+
}
|
|
5850
|
+
}
|
|
5851
|
+
function identityGeneration(store) {
|
|
5852
|
+
try {
|
|
5853
|
+
return store.db.prepare("SELECT generation, actor_id FROM local_identity_generation WHERE id = 1").get() ?? null;
|
|
5854
|
+
} catch (error) {
|
|
5855
|
+
if (error instanceof Error && error.message.includes("no such table")) return null;
|
|
5856
|
+
throw error;
|
|
5857
|
+
}
|
|
5858
|
+
}
|
|
5859
|
+
function currentOperationConfig(store, options) {
|
|
5860
|
+
store.assertLocalIdentityCurrent();
|
|
5861
|
+
const config = options.readConfig();
|
|
5862
|
+
if (!store.hasCurrentConfiguredIdentity() || config.syncEnabled !== options.config.syncEnabled || config.syncCoordinatorAdminSecret !== options.config.syncCoordinatorAdminSecret || config.syncCoordinatorUrl !== options.config.syncCoordinatorUrl || JSON.stringify(config.syncCoordinatorGroups) !== JSON.stringify(options.config.syncCoordinatorGroups)) throw new Error("device_setup_context_changed");
|
|
5863
|
+
return config;
|
|
5864
|
+
}
|
|
5865
|
+
function captureCoordinatorEnrollmentContext(store, options) {
|
|
5866
|
+
const capture = () => {
|
|
5867
|
+
const config = currentOperationConfig(store, options);
|
|
5868
|
+
const { dbPath, deviceId, actorId } = store;
|
|
5869
|
+
const keysDir = options.keysDir();
|
|
5870
|
+
const { device, fileIdentity } = readLocalDevice$1(store, keysDir);
|
|
5871
|
+
return {
|
|
5872
|
+
dbPath,
|
|
5873
|
+
deviceId,
|
|
5874
|
+
identityId: actorId,
|
|
5875
|
+
keysDir,
|
|
5876
|
+
groupId: options.groupId,
|
|
5877
|
+
coordinatorUrl: config.syncCoordinatorUrl,
|
|
5878
|
+
fingerprint: device.fingerprint,
|
|
5879
|
+
pin: JSON.stringify([
|
|
5880
|
+
dbPath,
|
|
5881
|
+
device,
|
|
5882
|
+
actorId,
|
|
5883
|
+
keysDir,
|
|
5884
|
+
fileIdentity,
|
|
5885
|
+
identityGeneration(store),
|
|
5886
|
+
readCodememConfigFile().actor_id,
|
|
5887
|
+
process.env.CODEMEM_DB,
|
|
5888
|
+
process.env.CODEMEM_CONFIG,
|
|
5889
|
+
process.env.HOME,
|
|
5890
|
+
process.env.CODEMEM_SYNC_KEY_STORE,
|
|
5891
|
+
process.env.CODEMEM_ACTOR_ID,
|
|
5892
|
+
process.env.CODEMEM_DEVICE_ID
|
|
5893
|
+
])
|
|
5894
|
+
};
|
|
5895
|
+
};
|
|
5896
|
+
const initial = capture();
|
|
5897
|
+
const assertCurrent = () => {
|
|
5898
|
+
try {
|
|
5899
|
+
if (capture().pin === initial.pin) return;
|
|
5900
|
+
} catch (error) {
|
|
5901
|
+
if (error instanceof LocalIdentitySupersededError) throw error;
|
|
5902
|
+
}
|
|
5903
|
+
throw new Error("device_setup_context_changed");
|
|
5904
|
+
};
|
|
5905
|
+
return {
|
|
5906
|
+
...initial,
|
|
5907
|
+
assertCurrent
|
|
5908
|
+
};
|
|
5909
|
+
}
|
|
5910
|
+
//#endregion
|
|
5774
5911
|
//#region src/application/coordinator-maintenance.ts
|
|
5775
5912
|
var AUTOMATIC_SHARE_OPERATION_STATES = [
|
|
5776
5913
|
"waiting_for_acceptance",
|
|
@@ -9719,10 +9856,27 @@ async function advancePendingProjectShares(store, options = {}) {
|
|
|
9719
9856
|
});
|
|
9720
9857
|
}
|
|
9721
9858
|
function coordinatorEnrollmentFailureCode(error) {
|
|
9859
|
+
if (error instanceof LocalIdentitySupersededError) return error.code;
|
|
9722
9860
|
const message = (error instanceof Error ? error.message : String(error)).trim();
|
|
9723
9861
|
const httpStatus = message.match(/\((\d{3})(?::|\))/u)?.[1];
|
|
9724
9862
|
if (httpStatus) return `http_${httpStatus}`;
|
|
9725
9863
|
if ((/* @__PURE__ */ new Set([
|
|
9864
|
+
"coordinator_upgrade_required",
|
|
9865
|
+
"completion_outcome_unknown",
|
|
9866
|
+
"device_unavailable",
|
|
9867
|
+
"invalid_input",
|
|
9868
|
+
"coordinator_unreachable",
|
|
9869
|
+
"invalid_response",
|
|
9870
|
+
"coordinator_rejected",
|
|
9871
|
+
"rate_limited",
|
|
9872
|
+
"coordinator_auth_schema_upgrade_required",
|
|
9873
|
+
"coordinator_unavailable",
|
|
9874
|
+
"device_setup_requires_review",
|
|
9875
|
+
"device_setup_connect_required",
|
|
9876
|
+
"device_setup_ready",
|
|
9877
|
+
"device_setup_enrollment_incomplete",
|
|
9878
|
+
"device_setup_context_changed",
|
|
9879
|
+
"local_identity_superseded",
|
|
9726
9880
|
"coordinator_consumed_team_invite_invalid",
|
|
9727
9881
|
"coordinator_device_list_malformed",
|
|
9728
9882
|
"coordinator_group_id_invalid",
|
|
@@ -9742,8 +9896,106 @@ function coordinatorEnrollmentFailure(groupId, stage, error) {
|
|
|
9742
9896
|
code: coordinatorEnrollmentFailureCode(error)
|
|
9743
9897
|
};
|
|
9744
9898
|
}
|
|
9899
|
+
function matchesOwnCoordinatorKey(context, row) {
|
|
9900
|
+
return row.enabled === 1 && row.group_id === context.groupId && row.device_id === context.deviceId && fingerprintPublicKey(row.public_key) === context.fingerprint && row.fingerprint === context.fingerprint;
|
|
9901
|
+
}
|
|
9902
|
+
function hasCanonicalOwnEnrollment(context, rows) {
|
|
9903
|
+
return rows.some((row) => matchesOwnCoordinatorKey(context, row) && row.identity_id === context.identityId && row.ownership_identity_id === context.identityId);
|
|
9904
|
+
}
|
|
9905
|
+
function compatibleOwnCoordinatorEnrollment(context, own) {
|
|
9906
|
+
if (!matchesOwnCoordinatorKey(context, own)) return false;
|
|
9907
|
+
if (own.identity_id !== null && own.identity_id !== context.identityId) return false;
|
|
9908
|
+
return own.ownership_identity_id === void 0 || own.ownership_identity_id === context.identityId;
|
|
9909
|
+
}
|
|
9910
|
+
function hasLegacyOwnIdentity(context, own) {
|
|
9911
|
+
return own.identity_id === context.identityId && own.ownership_identity_id === void 0;
|
|
9912
|
+
}
|
|
9913
|
+
/**
|
|
9914
|
+
* True when the coordinator state cannot have changed: the client sent no request
|
|
9915
|
+
* for this URL, or an older coordinator has no completion route.
|
|
9916
|
+
*/
|
|
9917
|
+
function completionNotAttempted(setup) {
|
|
9918
|
+
if (setup.kind === "unavailable") return setup.cause === "invalid_input";
|
|
9919
|
+
return setup.kind === "unsupported";
|
|
9920
|
+
}
|
|
9921
|
+
async function completeCoordinatorEnrollment(context, initial, completeDeviceSetup, readDevices) {
|
|
9922
|
+
const own = initial.find((row) => row.group_id === context.groupId && row.device_id === context.deviceId);
|
|
9923
|
+
if (!own) return initial;
|
|
9924
|
+
if (hasCanonicalOwnEnrollment(context, initial)) return initial;
|
|
9925
|
+
if (!compatibleOwnCoordinatorEnrollment(context, own)) throw new Error("device_setup_enrollment_incomplete");
|
|
9926
|
+
const setup = await completeDeviceSetup({
|
|
9927
|
+
dbPath: context.dbPath,
|
|
9928
|
+
keysDir: context.keysDir,
|
|
9929
|
+
coordinatorUrl: context.coordinatorUrl,
|
|
9930
|
+
groupId: context.groupId,
|
|
9931
|
+
currentIdentityId: context.identityId,
|
|
9932
|
+
fetch: (input, init) => {
|
|
9933
|
+
context.assertCurrent();
|
|
9934
|
+
return globalThis.fetch(input, init);
|
|
9935
|
+
}
|
|
9936
|
+
});
|
|
9937
|
+
context.assertCurrent();
|
|
9938
|
+
if (completionNotAttempted(setup)) return initial;
|
|
9939
|
+
if (setup.kind === "requires_review" && hasLegacyOwnIdentity(context, own)) return initial;
|
|
9940
|
+
if (setup.kind !== "complete" && setup.kind !== "unknown") throw new Error("cause" in setup ? setup.cause : `device_setup_${setup.kind}`);
|
|
9941
|
+
const enrollments = await readDevices();
|
|
9942
|
+
if (!hasCanonicalOwnEnrollment(context, enrollments)) throw new Error(setup.kind === "unknown" ? "completion_outcome_unknown" : "device_setup_enrollment_incomplete");
|
|
9943
|
+
return enrollments;
|
|
9944
|
+
}
|
|
9945
|
+
async function reconcileConfiguredCoordinatorGroup(store, groupId, config, options) {
|
|
9946
|
+
const remoteUrl = config.syncCoordinatorUrl.trim();
|
|
9947
|
+
const adminSecret = config.syncCoordinatorAdminSecret.trim();
|
|
9948
|
+
const listDevices = options.listDevices ?? coordinatorListDevicesAction;
|
|
9949
|
+
const listInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
|
|
9950
|
+
const reconcile = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
|
|
9951
|
+
let stage = "complete_device_setup";
|
|
9952
|
+
try {
|
|
9953
|
+
const context = captureCoordinatorEnrollmentContext(store, {
|
|
9954
|
+
config,
|
|
9955
|
+
readConfig: () => options.config ?? readCoordinatorSyncConfig(),
|
|
9956
|
+
keysDir: syncKeysDir,
|
|
9957
|
+
groupId
|
|
9958
|
+
});
|
|
9959
|
+
const readDevices = async () => {
|
|
9960
|
+
stage = "list_devices";
|
|
9961
|
+
const rows = await listDevices({
|
|
9962
|
+
groupId,
|
|
9963
|
+
remoteUrl,
|
|
9964
|
+
adminSecret
|
|
9965
|
+
});
|
|
9966
|
+
stage = "complete_device_setup";
|
|
9967
|
+
context.assertCurrent();
|
|
9968
|
+
return rows;
|
|
9969
|
+
};
|
|
9970
|
+
const enrollments = await completeCoordinatorEnrollment(context, await readDevices(), options.completeDeviceSetup ?? completeCoordinatorDeviceSetup, readDevices);
|
|
9971
|
+
stage = "list_consumed_team_invites";
|
|
9972
|
+
const invites = await listInvites({
|
|
9973
|
+
groupId,
|
|
9974
|
+
remoteUrl,
|
|
9975
|
+
adminSecret
|
|
9976
|
+
});
|
|
9977
|
+
stage = "complete_device_setup";
|
|
9978
|
+
context.assertCurrent();
|
|
9979
|
+
stage = "reconcile_snapshot";
|
|
9980
|
+
return { result: await reconcile({
|
|
9981
|
+
coordinatorId: buildBaseUrl(remoteUrl),
|
|
9982
|
+
groupId,
|
|
9983
|
+
enrollments,
|
|
9984
|
+
consumedTeamInvites: invites,
|
|
9985
|
+
localDeviceId: store.deviceId
|
|
9986
|
+
}) };
|
|
9987
|
+
} catch (error) {
|
|
9988
|
+
return { failures: [coordinatorEnrollmentFailure(groupId, stage, error)] };
|
|
9989
|
+
}
|
|
9990
|
+
}
|
|
9745
9991
|
async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
|
|
9746
|
-
const
|
|
9992
|
+
const source = options.config ?? readCoordinatorSyncConfig();
|
|
9993
|
+
const config = {
|
|
9994
|
+
syncEnabled: source.syncEnabled,
|
|
9995
|
+
syncCoordinatorUrl: source.syncCoordinatorUrl,
|
|
9996
|
+
syncCoordinatorGroups: [...source.syncCoordinatorGroups],
|
|
9997
|
+
syncCoordinatorAdminSecret: source.syncCoordinatorAdminSecret
|
|
9998
|
+
};
|
|
9747
9999
|
const remoteUrl = config.syncCoordinatorUrl.trim();
|
|
9748
10000
|
const adminSecret = config.syncCoordinatorAdminSecret.trim();
|
|
9749
10001
|
if (!remoteUrl || !adminSecret || config.syncCoordinatorGroups.length === 0) return {
|
|
@@ -9757,9 +10009,6 @@ async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
|
|
|
9757
10009
|
unchanged: 0,
|
|
9758
10010
|
issues: 0
|
|
9759
10011
|
};
|
|
9760
|
-
const listDevices = options.listDevices ?? coordinatorListDevicesAction;
|
|
9761
|
-
const listConsumedTeamInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
|
|
9762
|
-
const reconcileSnapshot = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
|
|
9763
10012
|
const total = {
|
|
9764
10013
|
skipped: false,
|
|
9765
10014
|
groupsProcessed: 0,
|
|
@@ -9772,39 +10021,19 @@ async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
|
|
|
9772
10021
|
issues: 0
|
|
9773
10022
|
};
|
|
9774
10023
|
for (const groupId of config.syncCoordinatorGroups) {
|
|
9775
|
-
const
|
|
9776
|
-
|
|
9777
|
-
remoteUrl,
|
|
9778
|
-
adminSecret
|
|
9779
|
-
}), listConsumedTeamInvites({
|
|
9780
|
-
groupId,
|
|
9781
|
-
remoteUrl,
|
|
9782
|
-
adminSecret
|
|
9783
|
-
})]);
|
|
9784
|
-
if (enrollmentsResult.status === "rejected") total.failures.push(coordinatorEnrollmentFailure(groupId, "list_devices", enrollmentsResult.reason));
|
|
9785
|
-
if (consumedTeamInvitesResult.status === "rejected") total.failures.push(coordinatorEnrollmentFailure(groupId, "list_consumed_team_invites", consumedTeamInvitesResult.reason));
|
|
9786
|
-
if (enrollmentsResult.status === "rejected" || consumedTeamInvitesResult.status === "rejected") {
|
|
10024
|
+
const outcome = await reconcileConfiguredCoordinatorGroup(store, groupId, config, options);
|
|
10025
|
+
if ("failures" in outcome) {
|
|
9787
10026
|
total.failedGroups += 1;
|
|
10027
|
+
total.failures.push(...outcome.failures);
|
|
9788
10028
|
continue;
|
|
9789
10029
|
}
|
|
9790
|
-
|
|
9791
|
-
|
|
9792
|
-
|
|
9793
|
-
|
|
9794
|
-
|
|
9795
|
-
|
|
9796
|
-
|
|
9797
|
-
});
|
|
9798
|
-
total.groupsProcessed += 1;
|
|
9799
|
-
total.devicesAdded += result.devicesAdded;
|
|
9800
|
-
total.membershipsAdded += result.membershipsAdded;
|
|
9801
|
-
total.identitiesAdded += result.identitiesAdded;
|
|
9802
|
-
total.unchanged += result.unchanged;
|
|
9803
|
-
total.issues += result.issues.length;
|
|
9804
|
-
} catch (error) {
|
|
9805
|
-
total.failedGroups += 1;
|
|
9806
|
-
total.failures.push(coordinatorEnrollmentFailure(groupId, "reconcile_snapshot", error));
|
|
9807
|
-
}
|
|
10030
|
+
const { result } = outcome;
|
|
10031
|
+
total.groupsProcessed += 1;
|
|
10032
|
+
total.devicesAdded += result.devicesAdded;
|
|
10033
|
+
total.membershipsAdded += result.membershipsAdded;
|
|
10034
|
+
total.identitiesAdded += result.identitiesAdded;
|
|
10035
|
+
total.unchanged += result.unchanged;
|
|
10036
|
+
total.issues += result.issues.length;
|
|
9808
10037
|
}
|
|
9809
10038
|
return total;
|
|
9810
10039
|
}
|
|
@@ -9932,9 +10161,17 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
|
|
|
9932
10161
|
remoteUrl: targetOptions.remoteUrl,
|
|
9933
10162
|
adminSecret: targetOptions.adminSecret
|
|
9934
10163
|
})).catch((error) => recipientPolicySnapshotUnavailable("device_enrollments", error));
|
|
9935
|
-
const
|
|
10164
|
+
const presenceExpiries = recipientPolicyPresenceCapabilityExpiries(enrollments, observedAt);
|
|
10165
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
9936
10166
|
const mapped = enrollments.map((enrollment) => {
|
|
9937
10167
|
if (enrollment.group_id !== targetOptions.groupId || !recipientPolicyEnrollmentValueIsValid(enrollment.device_id) || !recipientPolicyEnrollmentValueIsValid(enrollment.public_key) || !recipientPolicyEnrollmentValueIsValid(enrollment.fingerprint) || fingerprintPublicKey(enrollment.public_key) !== enrollment.fingerprint || enrollment.enabled !== 0 && enrollment.enabled !== 1 || enrollment.identity_id !== null && !recipientPolicyEnrollmentValueIsValid(enrollment.identity_id)) throw new Error("recipient_policy_snapshot_invalid");
|
|
10168
|
+
if (enrollment.enabled === 1 && enrollment.identity_id !== null) bindings.set(enrollment.device_id, {
|
|
10169
|
+
identityId: enrollment.identity_id,
|
|
10170
|
+
ownershipIdentityId: enrollment.ownership_identity_id,
|
|
10171
|
+
publicKey: enrollment.public_key,
|
|
10172
|
+
fingerprint: enrollment.fingerprint,
|
|
10173
|
+
presenceCapabilityExpiresAtMs: presenceExpiries.get(enrollment.device_id) ?? null
|
|
10174
|
+
});
|
|
9938
10175
|
return {
|
|
9939
10176
|
deviceId: enrollment.device_id,
|
|
9940
10177
|
identityId: enrollment.identity_id,
|
|
@@ -9943,12 +10180,7 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
|
|
|
9943
10180
|
enabled: enrollment.enabled === 1
|
|
9944
10181
|
};
|
|
9945
10182
|
});
|
|
9946
|
-
boundaryEnrollments.set(scopeId,
|
|
9947
|
-
identityId: enrollment.identityId,
|
|
9948
|
-
publicKey: enrollment.publicKey,
|
|
9949
|
-
fingerprint: enrollment.fingerprint,
|
|
9950
|
-
presenceCapabilityExpiresAtMs: presenceCapabilityExpiries.get(enrollment.deviceId) ?? null
|
|
9951
|
-
}]] : [])));
|
|
10183
|
+
boundaryEnrollments.set(scopeId, bindings);
|
|
9952
10184
|
return mapped;
|
|
9953
10185
|
},
|
|
9954
10186
|
probeCapability: async ({ deviceId, scopeId }) => {
|
|
@@ -9957,11 +10189,9 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
|
|
|
9957
10189
|
const enrollment = boundaryEnrollments.get(scopeId)?.get(deviceId);
|
|
9958
10190
|
if (!enrollment) return "undetermined";
|
|
9959
10191
|
const peer = store.db.prepare("SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
|
|
9960
|
-
|
|
9961
|
-
|
|
9962
|
-
|
|
9963
|
-
if ((peerFingerprint || peerPublicKey) && (peerFingerprint !== enrollment.fingerprint || peerPublicKey && peerPublicKey !== enrollment.publicKey)) return "undetermined";
|
|
9964
|
-
}
|
|
10192
|
+
const peerPublicKey = String(peer?.public_key ?? "").trim();
|
|
10193
|
+
const peerFingerprint = String(peer?.pinned_fingerprint ?? "").trim() || (peerPublicKey ? fingerprintPublicKey(peerPublicKey) : "");
|
|
10194
|
+
if ((peerFingerprint || peerPublicKey) && (peerFingerprint !== enrollment.fingerprint || peerPublicKey && peerPublicKey !== enrollment.publicKey)) return "undetermined";
|
|
9965
10195
|
const observed = await peerSupportsSyncRequirements(store, deviceId, {
|
|
9966
10196
|
scoped: true,
|
|
9967
10197
|
reassignScope: true
|
|
@@ -9969,6 +10199,7 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
|
|
|
9969
10199
|
if (observed !== "undetermined") return observed;
|
|
9970
10200
|
const observedAtMs = Date.parse(now());
|
|
9971
10201
|
if (enrollment.presenceCapabilityExpiresAtMs == null || !Number.isFinite(observedAtMs) || enrollment.presenceCapabilityExpiresAtMs <= observedAtMs) return "undetermined";
|
|
10202
|
+
if (enrollment.ownershipIdentityId === enrollment.identityId) return "supported";
|
|
9972
10203
|
return (await loadReviewedRecipientInviteEvidence(targetOptions.groupId).catch(() => [])).some((invite) => invite.group_id === targetOptions.groupId && invite.bound_device_id === deviceId && invite.recipient_actor_id === enrollment.identityId && invite.bound_public_key === enrollment.publicKey && invite.bound_fingerprint === enrollment.fingerprint) ? "supported" : "undetermined";
|
|
9973
10204
|
},
|
|
9974
10205
|
revoke: async (input) => {
|
|
@@ -15463,173 +15694,17 @@ var CONTROLLER_HISTORY_CTE = `history_input AS MATERIALIZED (
|
|
|
15463
15694
|
`${CONTROLLER_HISTORY_CTE}`;
|
|
15464
15695
|
`${CONTROLLER_HISTORY_CTE}`;
|
|
15465
15696
|
`${CONTROLLER_HISTORY_CTE}${MAX_BYTES}`;
|
|
15466
|
-
var CONTROLLER_HISTORY_GUARD = `AND (
|
|
15467
|
-
(SELECT value FROM history_input) IS NULL OR (
|
|
15468
|
-
json_extract((SELECT value FROM history_input), '$.deviceId') = e.device_id
|
|
15469
|
-
AND json_extract((SELECT value FROM history_input), '$.publicKey') = e.public_key
|
|
15470
|
-
AND json_extract((SELECT value FROM history_input), '$.fingerprint') = e.fingerprint
|
|
15471
|
-
AND (SELECT count(*) FROM live_history) = (SELECT count(*) FROM snapshot_history)
|
|
15472
|
-
AND NOT EXISTS (SELECT * FROM live_history EXCEPT SELECT * FROM snapshot_history)
|
|
15473
|
-
AND NOT EXISTS (SELECT * FROM live_history_keys EXCEPT SELECT * FROM snapshot_history_keys)
|
|
15474
|
-
AND NOT EXISTS (SELECT * FROM snapshot_history_keys EXCEPT SELECT * FROM live_history_keys)
|
|
15475
|
-
AND NOT EXISTS (SELECT * FROM live_discovery_keys EXCEPT SELECT * FROM snapshot_discovery_keys)
|
|
15476
|
-
AND NOT EXISTS (SELECT * FROM snapshot_discovery_keys EXCEPT SELECT * FROM live_discovery_keys)
|
|
15477
|
-
))`;
|
|
15478
|
-
//#endregion
|
|
15479
|
-
//#region ../core/src/coordinator-account-connection-storage.ts
|
|
15480
|
-
/**
|
|
15481
|
-
* Storage constraints, not an unlink/relink authorization API.
|
|
15482
|
-
* The explicit account-schema migration installs this DDL. Management writers
|
|
15483
|
-
* compose the winning proof, archive move and successor CAS in one backend.batch;
|
|
15484
|
-
* an Identity identifier alone never authorizes these effects.
|
|
15485
|
-
*/
|
|
15486
|
-
var CONNECTION_BIRTH_COLUMNS = [
|
|
15487
|
-
"coordinator_id",
|
|
15488
|
-
"link_id",
|
|
15489
|
-
"issuer",
|
|
15490
|
-
"subject",
|
|
15491
|
-
"identity_id",
|
|
15492
|
-
"attempt_id",
|
|
15493
|
-
"controller_attestation_id",
|
|
15494
|
-
"auth_config_revision",
|
|
15495
|
-
"created_at_ms",
|
|
15496
|
-
"revoked_at_ms",
|
|
15497
|
-
"authority_kind",
|
|
15498
|
-
"device_claim_id"
|
|
15499
|
-
];
|
|
15500
|
-
var current = "coordinator_auth_account_links";
|
|
15501
|
-
var history = "coordinator_auth_account_connection_history";
|
|
15502
|
-
var orders = "coordinator_auth_account_connection_orders";
|
|
15503
|
-
var birthEqual = CONNECTION_BIRTH_COLUMNS.map((c) => `c.${c} IS NEW.${c}`).join(" AND ");
|
|
15504
|
-
var immutableBirth = CONNECTION_BIRTH_COLUMNS.filter((c) => c !== "revoked_at_ms").map((c) => `NEW.${c} IS NOT OLD.${c}`).join(" OR ");
|
|
15505
|
-
`${CONNECTION_BIRTH_COLUMNS.map((column) => `h.${column} IS c.${column}`).join(" AND ")}`;
|
|
15506
|
-
`${current}${history}`;
|
|
15507
|
-
/** Alias l must be the pinned current target, never a caller-selected Identity. */
|
|
15508
|
-
var CONNECTION_NOT_REVOKED_SQL = `l.revoked_at_ms IS NULL AND NOT EXISTS (
|
|
15509
|
-
SELECT 1 FROM ${history} h WHERE h.coordinator_id = l.coordinator_id
|
|
15510
|
-
AND h.identity_id = l.identity_id AND h.revoked_at_ms IS NOT NULL)`;
|
|
15511
|
-
`${history}${current}${history}`;
|
|
15512
|
-
`${orders}`;
|
|
15513
|
-
`${orders}`;
|
|
15514
|
-
`${history}`, `${history}${history}${history}${history}${current}${birthEqual}`, `${history}`, `${history}${immutableBirth}${history}${current}${history}`, `${history}`, `${current}${history}`, `${history}`, `${orders}`, `${orders}${orders}`, `${orders}`, `${orders}`;
|
|
15515
|
-
`${CONNECTION_BIRTH_COLUMNS.join(",")}${CONNECTION_BIRTH_COLUMNS.join(",")}`;
|
|
15516
|
-
function rootBirths(coordinator, link) {
|
|
15517
|
-
return `SELECT ${CONNECTION_BIRTH_COLUMNS.join(",")} FROM coordinator_auth_account_links WHERE coordinator_id = ${coordinator} AND link_id = ${link}
|
|
15518
|
-
UNION ALL SELECT ${CONNECTION_BIRTH_COLUMNS.join(",")} FROM coordinator_auth_account_connection_history WHERE coordinator_id = ${coordinator} AND link_id = ${link}`;
|
|
15519
|
-
}
|
|
15520
|
-
/** Trusted SQL aliases only. Historical ownership is independent of current enrollment.
|
|
15521
|
-
* The immutable proof's key ID was derived at commit. Signed-device receipts also
|
|
15522
|
-
* pass a freshly derived canonical key ID; account sessions need no current key.
|
|
15523
|
-
* Link revocation is deliberately checked by the caller, including post-revoke audit.
|
|
15524
|
-
*/
|
|
15525
|
-
function authDeviceClaimProvenanceSql(options) {
|
|
15526
|
-
if (options.connections) return connectionClaimProvenance(options);
|
|
15527
|
-
return genesisClaimProvenance(options.link, "coordinator_auth_account_links", options.canonicalKeyId);
|
|
15528
|
-
}
|
|
15529
|
-
function genesisClaimProvenance(link, births, canonicalKeyId) {
|
|
15530
|
-
const l = "pl";
|
|
15531
|
-
return `EXISTS (WITH committed_claim AS MATERIALIZED (
|
|
15532
|
-
SELECT ct.coordinator_id, ct.link_id, cd.key_id FROM coordinator_auth_link_attempts ct
|
|
15533
|
-
JOIN ${births} pl ON pl.coordinator_id = ct.coordinator_id AND pl.link_id = ct.link_id
|
|
15534
|
-
JOIN coordinator_auth_device_claims cd ON cd.coordinator_id = ct.coordinator_id AND cd.claim_id = ${l}.device_claim_id
|
|
15535
|
-
JOIN coordinator_auth_link_audit_log ca ON ca.coordinator_id = ct.coordinator_id AND ca.link_id = ct.link_id AND ca.action = 'link_created'
|
|
15536
|
-
WHERE ct.coordinator_id = ${link}.coordinator_id AND ct.link_id = ${link}.link_id
|
|
15537
|
-
AND ct.attempt_id = ${l}.attempt_id
|
|
15538
|
-
AND ct.authority_kind = 'device_claim' AND ct.controller_attestation_id IS NULL
|
|
15539
|
-
AND ct.controller_review_receipt_id IS NULL AND ct.controller_revision IS NULL AND ct.state IN ('finalized','session_redeemed')
|
|
15540
|
-
AND ${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL
|
|
15541
|
-
AND ct.identity_id = ${l}.identity_id AND ct.issuer = ${l}.issuer AND ct.account_subject = ${l}.subject
|
|
15542
|
-
AND ct.auth_config_revision = ${l}.auth_config_revision AND ct.finalized_at_ms = ${l}.created_at_ms
|
|
15543
|
-
AND ct.browser_transaction_hash IS NOT NULL AND ct.browser_start_hash IS NOT NULL
|
|
15544
|
-
AND ct.runtime_verifier_hash IS NOT NULL AND ct.completion_secret_hash IS NOT NULL
|
|
15545
|
-
AND ct.created_at_ms <= ct.claimed_at_ms AND ct.claimed_at_ms <= ct.oidc_verified_at_ms
|
|
15546
|
-
AND ct.oidc_verified_at_ms <= ct.confirmed_at_ms AND ct.confirmed_at_ms <= ct.finalized_at_ms AND ct.finalized_at_ms < ct.expires_at_ms
|
|
15547
|
-
AND cd.attempt_id = ct.attempt_id AND cd.identity_id = ct.identity_id AND cd.group_id = ct.group_id AND cd.device_id = ct.device_id
|
|
15548
|
-
AND cd.public_key = ct.public_key AND cd.fingerprint = ct.fingerprint
|
|
15549
|
-
AND cd.issuer = ct.issuer AND cd.auth_config_revision = ct.auth_config_revision AND cd.created_at_ms = ct.finalized_at_ms
|
|
15550
|
-
AND ca.authority_kind = 'device_claim' AND ca.controller_attestation_id IS NULL AND ca.device_claim_id IS ${l}.device_claim_id
|
|
15551
|
-
AND ca.attempt_id = ct.attempt_id AND ca.identity_id = ct.identity_id AND ca.group_id = ct.group_id AND ca.device_id = ct.device_id
|
|
15552
|
-
AND ca.fingerprint = ct.fingerprint AND ca.auth_config_revision = ct.auth_config_revision AND ca.created_at_ms = ct.finalized_at_ms)
|
|
15553
|
-
SELECT 1 FROM committed_claim cp WHERE cp.coordinator_id = ${link}.coordinator_id AND cp.link_id = ${link}.link_id
|
|
15554
|
-
${canonicalKeyId ? `AND cp.key_id = ${canonicalKeyId}` : ""})`;
|
|
15555
|
-
}
|
|
15556
|
-
function connectionClaimProvenance(options) {
|
|
15557
|
-
const l = options.link;
|
|
15558
|
-
return `EXISTS (WITH connection_births AS MATERIALIZED (${rootBirths(`${l}.coordinator_id`, `${l}.device_claim_id`)}), continuation AS MATERIALIZED (
|
|
15559
|
-
SELECT t.coordinator_id,t.link_id,d.key_id FROM coordinator_auth_link_attempts t
|
|
15560
|
-
JOIN coordinator_auth_link_audit_log a ON a.coordinator_id = t.coordinator_id AND a.link_id = t.link_id AND a.action = 'link_created'
|
|
15561
|
-
JOIN coordinator_auth_device_claims d ON d.coordinator_id = t.coordinator_id AND d.claim_id = ${l}.device_claim_id
|
|
15562
|
-
WHERE t.coordinator_id = ${l}.coordinator_id AND t.link_id = ${l}.link_id AND t.attempt_id = ${l}.attempt_id
|
|
15563
|
-
AND (${l}.authority_kind = 'device_claim' AND ${l}.controller_attestation_id IS NULL AND t.authority_kind = 'device_claim' AND t.controller_attestation_id IS NULL AND t.controller_review_receipt_id IS NULL AND t.controller_revision IS NULL)
|
|
15564
|
-
AND (t.state IN ('finalized','session_redeemed') AND t.identity_id = ${l}.identity_id AND t.issuer = ${l}.issuer AND t.account_subject = ${l}.subject AND t.auth_config_revision = ${l}.auth_config_revision AND t.finalized_at_ms = ${l}.created_at_ms)
|
|
15565
|
-
AND (t.browser_start_hash IS NOT NULL AND t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms <= t.claimed_at_ms AND t.claimed_at_ms <= t.oidc_verified_at_ms AND t.oidc_verified_at_ms <= t.confirmed_at_ms AND t.confirmed_at_ms <= t.finalized_at_ms AND t.finalized_at_ms < t.expires_at_ms)
|
|
15566
|
-
AND (d.identity_id = t.identity_id AND d.issuer = t.issuer AND d.group_id = t.group_id AND d.device_id = t.device_id AND d.public_key = t.public_key AND d.fingerprint = t.fingerprint)
|
|
15567
|
-
AND (a.attempt_id = t.attempt_id AND a.identity_id = t.identity_id AND a.group_id = t.group_id AND a.device_id = t.device_id AND a.fingerprint = t.fingerprint AND a.auth_config_revision = t.auth_config_revision AND a.created_at_ms = t.finalized_at_ms AND a.authority_kind = 'device_claim' AND a.controller_attestation_id IS NULL AND a.device_claim_id = d.claim_id)
|
|
15568
|
-
AND ((t.prior_link_id IS NULL AND t.link_id = d.claim_id) OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id = t.coordinator_id AND h.link_id = t.prior_link_id AND h.identity_id = t.identity_id AND h.successor_link_id = t.link_id))
|
|
15569
|
-
AND EXISTS (SELECT 1 FROM connection_births gl WHERE gl.coordinator_id = d.coordinator_id AND gl.link_id = d.claim_id AND ${genesisClaimProvenance("gl", "connection_births")}))
|
|
15570
|
-
SELECT 1 FROM continuation cp ${options.canonicalKeyId ? "WHERE cp.key_id = ?" : ""})`;
|
|
15571
|
-
}
|
|
15572
|
-
/** Account management only; privileged enrollment/grant proofs remain attested-only. */
|
|
15573
|
-
function controllerBirthProvenance(link) {
|
|
15574
|
-
return `EXISTS (WITH controller_receipt AS MATERIALIZED (SELECT t.coordinator_id,t.link_id FROM coordinator_auth_link_attempts t
|
|
15575
|
-
JOIN coordinator_auth_controller_attestations origin ON origin.coordinator_id=t.coordinator_id AND origin.attestation_id=t.controller_attestation_id
|
|
15576
|
-
JOIN coordinator_auth_link_audit_log a ON a.coordinator_id=t.coordinator_id AND a.link_id=t.link_id AND a.action='link_created'
|
|
15577
|
-
WHERE (t.coordinator_id=${link}.coordinator_id AND t.link_id=${link}.link_id AND t.attempt_id=${link}.attempt_id AND t.authority_kind='controller_attestation' AND t.controller_attestation_id=${link}.controller_attestation_id)
|
|
15578
|
-
AND (t.identity_id=${link}.identity_id AND t.issuer=${link}.issuer AND t.account_subject=${link}.subject AND t.auth_config_revision=${link}.auth_config_revision AND t.finalized_at_ms=${link}.created_at_ms AND t.state IN ('finalized','session_redeemed'))
|
|
15579
|
-
AND (t.browser_transaction_hash IS NOT NULL AND t.runtime_verifier_hash IS NOT NULL AND t.completion_secret_hash IS NOT NULL AND t.created_at_ms<=t.claimed_at_ms AND t.claimed_at_ms<=t.oidc_verified_at_ms AND t.oidc_verified_at_ms<=t.confirmed_at_ms AND t.confirmed_at_ms<=t.finalized_at_ms AND t.finalized_at_ms<t.expires_at_ms)
|
|
15580
|
-
AND (origin.identity_id=t.identity_id AND origin.group_id=t.group_id AND origin.device_id=t.device_id AND origin.public_key=t.public_key AND origin.fingerprint=t.fingerprint AND origin.review_receipt_id=t.controller_review_receipt_id AND origin.revision=t.controller_revision)
|
|
15581
|
-
AND (t.prior_link_id IS NULL OR EXISTS (SELECT 1 FROM coordinator_auth_account_connection_history h WHERE h.coordinator_id=t.coordinator_id AND h.identity_id=t.identity_id AND h.link_id=t.prior_link_id AND h.successor_link_id=t.link_id))
|
|
15582
|
-
AND (a.attempt_id=t.attempt_id AND a.identity_id=t.identity_id AND a.group_id=t.group_id AND a.device_id=t.device_id AND a.fingerprint=t.fingerprint AND a.controller_attestation_id=t.controller_attestation_id AND a.authority_kind=t.authority_kind AND a.device_claim_id IS NULL AND a.auth_config_revision=t.auth_config_revision AND a.created_at_ms=t.finalized_at_ms)) SELECT 1 FROM controller_receipt)`;
|
|
15583
|
-
}
|
|
15584
|
-
function authAccountLinkProvenanceSql(link, options = {}) {
|
|
15585
|
-
return `((${link}.authority_kind = 'controller_attestation' AND ${link}.controller_attestation_id IS NOT NULL AND ${link}.device_claim_id IS NULL${options.connections ? ` AND ${controllerBirthProvenance(link)}` : ""})
|
|
15586
|
-
OR (${authDeviceClaimProvenanceSql({
|
|
15587
|
-
link,
|
|
15588
|
-
connections: options.connections
|
|
15589
|
-
})}))`;
|
|
15590
|
-
}
|
|
15591
|
-
`${CONNECTION_NOT_REVOKED_SQL}${authAccountLinkProvenanceSql("l", { connections: true })}`;
|
|
15592
15697
|
//#endregion
|
|
15593
15698
|
//#region ../core/src/coordinator-auth-controller.ts
|
|
15594
15699
|
function isAuthControllerId(value) {
|
|
15595
15700
|
return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value && !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(value);
|
|
15596
15701
|
}
|
|
15597
|
-
var AUTH_CONTROLLER_SNAPSHOT_CTE = `
|
|
15598
|
-
WITH snapshot(value) AS (SELECT ?), snapshot_invites AS MATERIALIZED (
|
|
15599
|
-
SELECT json_extract(j.value, '$.inviteId') AS invite_id,
|
|
15600
|
-
json_extract(j.value, '$.kind') AS invite_kind,
|
|
15601
|
-
json_extract(j.value, '$.actorId') AS recipient_actor_id,
|
|
15602
|
-
json_extract(j.value, '$.assignedIdentityId') AS assigned_identity_id,
|
|
15603
|
-
json_extract(j.value, '$.targetIdentityId') AS target_identity_id,
|
|
15604
|
-
json_extract(j.value, '$.digest') AS reviewed_preview_digest
|
|
15605
|
-
FROM json_each((SELECT value FROM snapshot), '$.invites') j
|
|
15606
|
-
), live_invites AS MATERIALIZED (
|
|
15607
|
-
SELECT i.invite_id, i.invite_kind, i.recipient_actor_id, i.assigned_identity_id,
|
|
15608
|
-
i.target_identity_id, i.reviewed_preview_digest FROM coordinator_invites i
|
|
15609
|
-
WHERE i.group_id = ? AND i.bound_device_id = ? AND i.bound_public_key = ?
|
|
15610
|
-
AND i.bound_fingerprint = ? AND i.revoked_at IS NULL
|
|
15611
|
-
AND i.consumed_at IS NOT NULL AND i.consumed_at != ''
|
|
15612
|
-
AND i.invite_kind IN ('team_member', 'add_device')
|
|
15613
|
-
), ${CONTROLLER_HISTORY_CTE}`;
|
|
15614
|
-
var AUTH_CONTROLLER_SNAPSHOT_GUARD = `
|
|
15615
|
-
AND ((SELECT value FROM snapshot) IS NULL OR (
|
|
15616
|
-
e.identity_id IS json_extract((SELECT value FROM snapshot), '$.enrollmentIdentityId')
|
|
15617
|
-
AND (SELECT count(*) FROM live_invites) =
|
|
15618
|
-
(SELECT count(*) FROM snapshot_invites)
|
|
15619
|
-
AND NOT EXISTS (
|
|
15620
|
-
SELECT * FROM live_invites
|
|
15621
|
-
EXCEPT
|
|
15622
|
-
SELECT * FROM snapshot_invites
|
|
15623
|
-
)
|
|
15624
|
-
)) ${CONTROLLER_HISTORY_GUARD}`;
|
|
15625
15702
|
var AUTH_CONTROLLER_AUTHORITY_GUARD = `
|
|
15626
15703
|
AND e.group_id = ? AND e.device_id = ? AND e.public_key = ?
|
|
15627
15704
|
AND e.fingerprint = ? AND e.identity_id IS ?
|
|
15628
15705
|
AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations WHERE
|
|
15629
15706
|
(subject_kind = 'device_id' AND subject_value = ?) OR
|
|
15630
15707
|
(subject_kind = 'ed25519_key' AND subject_value = ?))`;
|
|
15631
|
-
`${AUTH_CONTROLLER_SNAPSHOT_CTE}${AUTH_CONTROLLER_SNAPSHOT_GUARD}${AUTH_CONTROLLER_AUTHORITY_GUARD}`;
|
|
15632
|
-
`${AUTH_CONTROLLER_SNAPSHOT_CTE}${AUTH_CONTROLLER_SNAPSHOT_GUARD}${AUTH_CONTROLLER_AUTHORITY_GUARD}`;
|
|
15633
15708
|
var AUTH_CONTROLLER_CURRENT_SQL = `
|
|
15634
15709
|
SELECT a.* FROM coordinator_auth_controller_attestations a
|
|
15635
15710
|
JOIN enrolled_devices e ON e.group_id = a.group_id AND e.device_id = a.device_id
|
|
@@ -15639,7 +15714,7 @@ var AUTH_CONTROLLER_CURRENT_SQL = `
|
|
|
15639
15714
|
AND e.fingerprint = a.fingerprint
|
|
15640
15715
|
AND (e.identity_id IS NULL OR e.identity_id = a.identity_id)`;
|
|
15641
15716
|
AUTH_CONTROLLER_CURRENT_SQL.replace("SELECT a.*", "SELECT e.*");
|
|
15642
|
-
`${
|
|
15717
|
+
`${AUTH_CONTROLLER_CURRENT_SQL}${AUTH_CONTROLLER_AUTHORITY_GUARD}`;
|
|
15643
15718
|
function ownerProfileConflict() {
|
|
15644
15719
|
throw new Error("Owner enrollment stopped for review. Keep the profile and saved request unchanged; no identity or access repair is automatic.");
|
|
15645
15720
|
}
|