@tearleads/client-sdk 0.1.251 → 0.1.253
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/Tearleads.d.ts +0 -2
- package/Tearleads.js +17 -28
- package/Tearleads.js.map +1 -1
- package/client/containerContents/index.d.ts +2 -0
- package/client/containerContents/index.js +4 -9
- package/client/containerContents/index.js.map +1 -1
- package/client/containerContents/storeRuntime.d.ts +17 -0
- package/client/containerContents/storeRuntime.js +31 -0
- package/client/containerContents/storeRuntime.js.map +1 -0
- package/client/deviceFirst/index.d.ts +2 -3
- package/client/deviceFirst/index.js +44 -22
- package/client/deviceFirst/index.js.map +1 -1
- package/client/organizations/organizationReadModelPresentation.js +7 -4
- package/client/organizations/organizationReadModelPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.js +6 -5
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +4 -0
- package/client/runtime/principalMutationApi.js +9 -5
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +23 -0
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/runtimeSubscription.js +68 -0
- package/client/runtime/runtimeSubscription.js.map +1 -0
- package/client/runtime/workflowRuntime.d.ts +3 -1
- package/client/runtime/workflowRuntime.js +31 -81
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/session/authenticationMachine.js +47 -0
- package/client/session/authenticationMachine.js.map +1 -0
- package/client/session/index.js +75 -93
- package/client/session/index.js.map +1 -1
- package/client/session/sessionBlobStore.js +39 -0
- package/client/session/sessionBlobStore.js.map +1 -0
- package/client/session/sessionContext.js +11 -0
- package/client/session/sessionContext.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +2 -1
- package/client/session/sessionIdentityTrust.js +8 -4
- package/client/session/sessionIdentityTrust.js.map +1 -1
- package/client/session/sessionLifetime.js +87 -0
- package/client/session/sessionLifetime.js.map +1 -0
- package/client/session/sessionLogin.js +114 -0
- package/client/session/sessionLogin.js.map +1 -0
- package/client/session/sessionOrganizationCreation.js +3 -2
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js +11 -3
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionTypes.d.ts +6 -2
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/blobContracts.d.ts +4 -3
- package/data/blobs/blobContracts.js.map +1 -1
- package/data/blobs/createBlobStore.js +1 -8
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobStore.js +17 -12
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.js +8 -5
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobFile.js +36 -0
- package/data/blobs/opfsBlobFile.js.map +1 -0
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +91 -21
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/principals/principalPolicyCoordinator.js +8 -17
- package/data/principals/principalPolicyCoordinator.js.map +1 -1
- package/data/shared/domainScope.d.ts +2 -0
- package/data/shared/domainScope.js +2 -1
- package/data/shared/domainScope.js.map +1 -1
- package/data/shared/keyedQueue.js +15 -0
- package/data/shared/keyedQueue.js.map +1 -0
- package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
- package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
- package/data/sqlite/sqlExec.d.ts +6 -0
- package/data/sqlite/sqlExec.js +64 -13
- package/data/sqlite/sqlExec.js.map +1 -1
- package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
- package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
- package/data/sync/syncCoordinator.js +17 -10
- package/data/sync/syncCoordinator.js.map +1 -1
- package/data/trustedUserIdentity/service.js +2 -1
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/data/trustedUserIdentity/types.d.ts +1 -1
- package/data/trustedUserIdentity/types.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -1
- package/internal/api-client/apiRequestRuntime.d.ts +6 -3
- package/internal/api-client/apiRequestRuntime.js +86 -101
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryRequestOperationTransport.js +2 -1
- package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +6 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -0
- package/internal/api-client/client/blobs.js +12 -3
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/laneListingRequest.js +4 -0
- package/internal/api-client/client/laneListingRequest.js.map +1 -1
- package/internal/api-client/client/session.d.ts +5 -1
- package/internal/api-client/client/session.js +12 -4
- package/internal/api-client/client/session.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +12 -13
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.d.ts +1 -1
- package/internal/api-client/operationResponse.js +10 -23
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/operationTransport.js +2 -1
- package/internal/api-client/operationTransport.js.map +1 -1
- package/internal/api-client/principalHistoryRequest.js +25 -20
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequestContext.js +30 -6
- package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +4 -1
- package/internal/api-client/principalPolicyPages.js +4 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
- package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
- package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
- package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
- package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
- package/internal/api-client/routes/blobs/get.js +9 -67
- package/internal/api-client/routes/blobs/get.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +1 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionRenewal.d.ts +31 -0
- package/internal/api-client/sessionRenewal.js +91 -6
- package/internal/api-client/sessionRenewal.js.map +1 -1
- package/internal/api-client/sessionRequestInit.js +22 -0
- package/internal/api-client/sessionRequestInit.js.map +1 -0
- package/internal/api-client/sessionResponse.js +39 -0
- package/internal/api-client/sessionResponse.js.map +1 -0
- package/internal/api-client/types.d.ts +1 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/webSocketTickets.d.ts +1 -0
- package/internal/api-client/webSocketTickets.js +4 -0
- package/internal/api-client/webSocketTickets.js.map +1 -1
- package/internal/sqlite-worker/client.d.ts +1 -1
- package/internal/sqlite-worker/client.js +6 -1
- package/internal/sqlite-worker/client.js.map +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
- package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
- package/internal/sqlite-worker/types.d.ts +4 -0
- package/internal/sqlite-worker/types.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/stores/container-contents/containerContentsStore.d.ts +3 -9
- package/stores/container-contents/containerContentsStore.js +24 -21
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/containerState/storeScope.js +6 -0
- package/stores/container-contents/containerState/storeScope.js.map +1 -0
- package/stores/container-contents/hydration/backgroundHydration.js +2 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
- package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
- package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
- package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
- package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
- package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
- package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +2 -9
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/hydration/treeResetMachine.js +61 -0
- package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
- package/stores/container-contents/localRefresh.js +28 -12
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
- package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
- package/stores/container-contents/state.d.ts +3 -7
- package/stores/container-contents/state.js +27 -16
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/index.d.ts +7 -2
- package/stores/container-contents/syncAgent/index.js +77 -49
- package/stores/container-contents/syncAgent/index.js.map +1 -1
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/stores/local-projection/localProjectionStore.js +24 -15
- package/stores/local-projection/localProjectionStore.js.map +1 -1
- package/stores/local-projection/registry.js +2 -2
- package/stores/local-projection/registry.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.js +3 -15
- package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +4 -8
- package/workflows/container-contents/containerPersistence.js +22 -12
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/localState.js +3 -0
- package/workflows/container-contents/localState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
- package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
- package/workflows/container-contents/remoteHydration/index.js +17 -66
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/storedContainerState.js +17 -7
- package/workflows/container-contents/storedContainerState.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -0
- package/workflows/container-contents/syncLane.js +9 -1
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
- package/workflows/documents/attachments/blobMutationLock.js +2 -2
- package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
- package/workflows/shared/runtimeInput.d.ts +2 -0
- package/workflows/shared/runtimeInput.js.map +1 -1
- package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
- package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
package/client/session/index.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { createListenerSet } from "../../data/shared/listenerSet.js";
|
|
2
2
|
import { bootstrapRootContainer, registerIdentity as registerIdentityWorkflow, removeNativeSubscriptionRestoreProvisioningAttempt, } from "../../workflows/registration/index.js";
|
|
3
|
-
import { emptySessionSnapshot, mergeSessionContext, registrationSessionResult, sessionSnapshotsEqual, } from "./sessionContext.js";
|
|
4
|
-
import { registrationKeyAlreadyBound, requireRegistrationIdentityPinner, requireSessionTrustDomain,
|
|
3
|
+
import { emptySessionSnapshot, hostSessionUpdate, mergeSessionContext, registrationSessionResult, sessionSnapshotsEqual, } from "./sessionContext.js";
|
|
4
|
+
import { registrationKeyAlreadyBound, requireRegistrationIdentityPinner, requireSessionTrustDomain, SessionIdentityAcknowledgments, } from "./sessionIdentityTrust.js";
|
|
5
|
+
import { sessionBoundary, sessionLifetime, } from "./sessionLifetime.js";
|
|
5
6
|
import { userSessionsFromResponse } from "./sessionListing.js";
|
|
6
|
-
import {
|
|
7
|
+
import { authenticateSession } from "./sessionLogin.js";
|
|
7
8
|
import { createSessionOrganization } from "./sessionOrganizationCreation.js";
|
|
8
9
|
import { clearSessionRemoteSyncState, recoverPurgedSessionOrganization, } from "./sessionPurgeRecovery.js";
|
|
9
10
|
import { acknowledgedSessionRoot, commitSessionRootAcknowledgment, } from "./sessionRootAuthority.js";
|
|
11
|
+
export { sessionLifetime } from "./sessionLifetime.js";
|
|
10
12
|
export function createSession(dependencies) {
|
|
11
13
|
return new SessionService(dependencies);
|
|
12
14
|
}
|
|
@@ -15,10 +17,14 @@ class SessionService {
|
|
|
15
17
|
identityAcknowledgments = new SessionIdentityAcknowledgments();
|
|
16
18
|
listeners = createListenerSet();
|
|
17
19
|
syncEnabledValue = true;
|
|
20
|
+
refusedSignIn = null;
|
|
18
21
|
snapshotValue = emptySessionSnapshot();
|
|
19
22
|
constructor(dependencies) {
|
|
20
23
|
this.dependencies = dependencies;
|
|
21
24
|
}
|
|
25
|
+
captureSignIn(purpose) {
|
|
26
|
+
return sessionLifetime(this).currentSignIn(purpose);
|
|
27
|
+
}
|
|
22
28
|
get authToken() {
|
|
23
29
|
return this.snapshotValue.authToken;
|
|
24
30
|
}
|
|
@@ -50,6 +56,7 @@ class SessionService {
|
|
|
50
56
|
return this.identityAcknowledgments.isAcknowledged(this.snapshotValue.userId, this.dependencies.identity.snapshot.signingFingerprint);
|
|
51
57
|
}
|
|
52
58
|
async bootstrapLocalRootContainer(isCurrent = () => true) {
|
|
59
|
+
const signInCurrent = this.captureSignIn();
|
|
53
60
|
if (!isCurrent())
|
|
54
61
|
throw new Error("Identity change was superseded.");
|
|
55
62
|
// Preserve a logged-in session's acknowledged root during local recovery.
|
|
@@ -57,8 +64,8 @@ class SessionService {
|
|
|
57
64
|
if (this.isAuthenticated && acknowledgedRoot) {
|
|
58
65
|
return { containerId: acknowledgedRoot, created: false };
|
|
59
66
|
}
|
|
60
|
-
const result = await bootstrapRootContainer(this.dependencies.database.requireExecSql("bootstrapLocalRootContainer"));
|
|
61
|
-
if (!isCurrent())
|
|
67
|
+
const result = await bootstrapRootContainer(sessionLifetime(this).bind(this.dependencies.database.requireExecSql("bootstrapLocalRootContainer")));
|
|
68
|
+
if (!signInCurrent() || !isCurrent())
|
|
62
69
|
throw new Error("Identity change was superseded.");
|
|
63
70
|
this.setContainerId(result.containerId);
|
|
64
71
|
if (result.created) {
|
|
@@ -76,86 +83,28 @@ class SessionService {
|
|
|
76
83
|
const response = await this.dependencies.api.destroySession(sessionId);
|
|
77
84
|
return response?.message === "ok";
|
|
78
85
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const fingerprint = (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;
|
|
82
|
-
if (!fingerprint) {
|
|
83
|
-
return false;
|
|
84
|
-
}
|
|
85
|
-
// A refusal below clears the session it is evidence against; a session
|
|
86
|
-
// another login committed meanwhile is not that session and stays.
|
|
87
|
-
const snapshotAtStart = this.snapshotValue;
|
|
88
|
-
const identitySnapshot = this.dependencies.identity.snapshot;
|
|
89
|
-
const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;
|
|
90
|
-
if (!encapsulationKeyPair) {
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
if (identitySnapshot.signingKeyPair !== signingKeyPair) {
|
|
94
|
-
return false;
|
|
95
|
-
}
|
|
96
|
-
const pinLocalUserIdentity = requireUserIdentityAvailable(this.dependencies.onUserIdentityAvailable, "Login");
|
|
97
|
-
this.dependencies.log(challengeHex ? "Authenticating with challenge..." : "Authenticating...");
|
|
98
|
-
const authentication = await authenticateUnlessSuspended(() => challengeHex
|
|
99
|
-
? this.dependencies.api.authenticateWithChallenge(fingerprint, signingKeyPair.signingPrivateKey, challengeHex)
|
|
100
|
-
: this.dependencies.api.authenticate(fingerprint, signingKeyPair.signingPrivateKey), () => {
|
|
101
|
-
if (this.authToken === snapshotAtStart.authToken)
|
|
102
|
-
this.logout();
|
|
103
|
-
});
|
|
104
|
-
if (this.dependencies.identity.snapshot !== identitySnapshot) {
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
if (!authentication) {
|
|
108
|
-
this.logout();
|
|
109
|
-
this.dependencies.log("Authentication failed");
|
|
110
|
-
return false;
|
|
111
|
-
}
|
|
112
|
-
try {
|
|
113
|
-
this.identityAcknowledgments.assertMatches(authentication.userId, fingerprint);
|
|
114
|
-
await pinLocalUserIdentity(authentication.userId, {
|
|
115
|
-
encapsulationPublicKey: encapsulationKeyPair.publicKey,
|
|
116
|
-
signingKeyFingerprint: fingerprint,
|
|
117
|
-
signingPublicKey: signingKeyPair.signingPublicKey,
|
|
118
|
-
});
|
|
119
|
-
if (this.dependencies.identity.snapshot !== identitySnapshot)
|
|
120
|
-
return false;
|
|
121
|
-
this.identityAcknowledgments.remember(authentication.userId, fingerprint);
|
|
122
|
-
}
|
|
123
|
-
catch (error) {
|
|
124
|
-
return refuseSessionLogin(error, authentication.userId, {
|
|
125
|
-
clear: () => this.logout(),
|
|
126
|
-
report: this.dependencies.reportSecurityIncident,
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
// A changed root for this identity+org is refused before the token is
|
|
130
|
-
// usable. Decision and commit are one synchronous step against the live
|
|
131
|
-
// snapshot (no await in between); the refusal clears the prior session in
|
|
132
|
-
// that same step and then reports its own incident.
|
|
133
|
-
await commitSessionRootAcknowledgment({
|
|
134
|
-
context: {
|
|
135
|
-
authToken: authentication.token,
|
|
136
|
-
defaultOrganizationId: authentication.organizationId,
|
|
137
|
-
isAuthenticated: true,
|
|
138
|
-
isRoot: authentication.isRoot,
|
|
139
|
-
organizationId: authentication.organizationId,
|
|
140
|
-
userId: authentication.userId,
|
|
141
|
-
},
|
|
142
|
-
onRefused: () => {
|
|
143
|
-
if (this.snapshotValue === snapshotAtStart)
|
|
144
|
-
this.logout();
|
|
145
|
-
},
|
|
146
|
-
reporter: this.dependencies.reportSecurityIncident,
|
|
147
|
-
root: authentication,
|
|
148
|
-
session: this,
|
|
149
|
-
signingFingerprint: fingerprint,
|
|
150
|
-
});
|
|
151
|
-
this.dependencies.log("Authentication successful");
|
|
152
|
-
return true;
|
|
86
|
+
login(challengeHex) {
|
|
87
|
+
return authenticateSession(this.dependencies, this, this.identityAcknowledgments, challengeHex, false);
|
|
153
88
|
}
|
|
89
|
+
renewExpired = () => {
|
|
90
|
+
if (!this.authToken || !this.dependencies.identity.signingKeyPair) {
|
|
91
|
+
this.clearAuthentication(true);
|
|
92
|
+
return Promise.resolve(false);
|
|
93
|
+
}
|
|
94
|
+
return authenticateSession(this.dependencies, this, this.identityAcknowledgments, undefined, true);
|
|
95
|
+
};
|
|
154
96
|
logout() {
|
|
155
|
-
this.
|
|
97
|
+
this.clearAuthentication(false);
|
|
98
|
+
}
|
|
99
|
+
clearAuthentication(renewal) {
|
|
100
|
+
if (renewal)
|
|
101
|
+
this.refusedSignIn = sessionLifetime(this).signInRevision;
|
|
102
|
+
this.commitContext({ authToken: null, isAuthenticated: false, isRoot: false }, renewal ? "renewal-refused" : "boundary");
|
|
156
103
|
}
|
|
157
|
-
async logoutRemote() {
|
|
104
|
+
async logoutRemote(onLocalLogout) {
|
|
158
105
|
const identitySnapshot = this.dependencies.identity.snapshot;
|
|
106
|
+
const lifetime = sessionLifetime(this);
|
|
107
|
+
const revision = lifetime.signInRevision;
|
|
159
108
|
try {
|
|
160
109
|
if (!this.authToken) {
|
|
161
110
|
return true;
|
|
@@ -164,9 +113,17 @@ class SessionService {
|
|
|
164
113
|
return response?.message === "ok";
|
|
165
114
|
}
|
|
166
115
|
finally {
|
|
167
|
-
|
|
116
|
+
const sameIdentity = () => this.dependencies.identity.snapshot === identitySnapshot;
|
|
117
|
+
const clearedHere = sameIdentity() && revision === lifetime.signInRevision;
|
|
118
|
+
if (clearedHere)
|
|
168
119
|
this.logout();
|
|
169
|
-
|
|
120
|
+
// The same local sign-out may already have happened during a refused
|
|
121
|
+
// renewal. A later explicit logout or sign-in supersedes this cleanup.
|
|
122
|
+
const current = () => sameIdentity() &&
|
|
123
|
+
!this.isAuthenticated &&
|
|
124
|
+
lifetime.signInRevision === revision + 1;
|
|
125
|
+
if (current() && (clearedHere || this.refusedSignIn === revision))
|
|
126
|
+
await onLocalLogout?.(current);
|
|
170
127
|
}
|
|
171
128
|
}
|
|
172
129
|
async registerIdentity(options) {
|
|
@@ -176,6 +133,9 @@ class SessionService {
|
|
|
176
133
|
return null;
|
|
177
134
|
}
|
|
178
135
|
const identitySnapshot = this.dependencies.identity.snapshot;
|
|
136
|
+
const sessionCurrent = this.captureSignIn();
|
|
137
|
+
const isCurrent = () => sessionCurrent() &&
|
|
138
|
+
this.dependencies.identity.snapshot === identitySnapshot;
|
|
179
139
|
const signingKeyPair = identitySnapshot.signingKeyPair;
|
|
180
140
|
if (!signingKeyPair) {
|
|
181
141
|
this.dependencies.log("Registration skipped: signing key is unavailable");
|
|
@@ -194,10 +154,11 @@ class SessionService {
|
|
|
194
154
|
const pinLocalUserIdentity = requireRegistrationIdentityPinner({
|
|
195
155
|
identity: this.dependencies.identity,
|
|
196
156
|
identitySnapshot,
|
|
157
|
+
isCurrent,
|
|
197
158
|
onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,
|
|
198
159
|
});
|
|
199
160
|
const keyBound = await registrationKeyAlreadyBound(this.dependencies, identitySnapshot.signingFingerprint);
|
|
200
|
-
if (
|
|
161
|
+
if (!isCurrent())
|
|
201
162
|
return null;
|
|
202
163
|
if (keyBound)
|
|
203
164
|
return keyBound;
|
|
@@ -210,7 +171,7 @@ class SessionService {
|
|
|
210
171
|
dbClient,
|
|
211
172
|
documentProjectors: this.dependencies.documentProjectors,
|
|
212
173
|
encapsulationKeyPair,
|
|
213
|
-
isIdentityCurrent:
|
|
174
|
+
isIdentityCurrent: isCurrent,
|
|
214
175
|
log: this.dependencies.log,
|
|
215
176
|
logError: this.dependencies.logError,
|
|
216
177
|
organizationProfileName: options?.organizationProfileName,
|
|
@@ -226,7 +187,7 @@ class SessionService {
|
|
|
226
187
|
this.dependencies.logError("Identity registration failed", error);
|
|
227
188
|
throw error;
|
|
228
189
|
}
|
|
229
|
-
if (
|
|
190
|
+
if (!isCurrent())
|
|
230
191
|
return null;
|
|
231
192
|
if (!response) {
|
|
232
193
|
this.dependencies.log("Registration failed");
|
|
@@ -251,13 +212,16 @@ class SessionService {
|
|
|
251
212
|
async createOrganization(options, replacesOrganizationId, nativeSubscriptionRestore) {
|
|
252
213
|
const identitySnapshot = this.dependencies.identity.snapshot;
|
|
253
214
|
const userId = this.userId;
|
|
215
|
+
const isCurrent = sessionLifetime(this).capture();
|
|
254
216
|
const response = await createSessionOrganization(this.dependencies, {
|
|
217
|
+
isCurrent,
|
|
255
218
|
nativeSubscriptionRestore,
|
|
256
219
|
options,
|
|
257
220
|
replacesOrganizationId,
|
|
258
221
|
userId,
|
|
259
222
|
});
|
|
260
223
|
if (!response ||
|
|
224
|
+
!isCurrent() ||
|
|
261
225
|
!userId ||
|
|
262
226
|
this.userId !== userId ||
|
|
263
227
|
this.dependencies.identity.snapshot !== identitySnapshot)
|
|
@@ -283,8 +247,10 @@ class SessionService {
|
|
|
283
247
|
const identitySnapshot = this.dependencies.identity.snapshot;
|
|
284
248
|
if (!userId || !dbClient)
|
|
285
249
|
return false;
|
|
250
|
+
const isCurrent = sessionLifetime(this).capture();
|
|
286
251
|
return removeNativeSubscriptionRestoreProvisioningAttempt({
|
|
287
|
-
canCommit: () =>
|
|
252
|
+
canCommit: () => isCurrent() &&
|
|
253
|
+
this.userId === userId &&
|
|
288
254
|
this.dependencies.identity.snapshot === identitySnapshot,
|
|
289
255
|
dbClient,
|
|
290
256
|
organizationId,
|
|
@@ -295,16 +261,22 @@ class SessionService {
|
|
|
295
261
|
return recoverPurgedSessionOrganization(this.dependencies, this, organizationId, options);
|
|
296
262
|
}
|
|
297
263
|
setAuthToken(authToken) {
|
|
298
|
-
|
|
264
|
+
if (authToken === null)
|
|
265
|
+
this.logout();
|
|
266
|
+
else
|
|
267
|
+
this.setSnapshot({ ...this.snapshotValue, authToken });
|
|
299
268
|
}
|
|
300
269
|
setContainerId(containerId) {
|
|
301
270
|
this.setSnapshot({ ...this.snapshotValue, containerId });
|
|
302
271
|
}
|
|
303
272
|
setContext(context) {
|
|
273
|
+
this.commitContext(...hostSessionUpdate(context));
|
|
274
|
+
}
|
|
275
|
+
commitContext(context, kind, verifiedTicket) {
|
|
304
276
|
const wasAcknowledged = this.userIdAcknowledged;
|
|
305
277
|
this.identityAcknowledgments.remember(context.userId, this.dependencies.identity.snapshot.signingFingerprint);
|
|
306
278
|
const previous = this.snapshotValue;
|
|
307
|
-
this.setSnapshot(mergeSessionContext(previous, context, this.dependencies.identity.snapshot.signingFingerprint));
|
|
279
|
+
this.setSnapshot(mergeSessionContext(previous, context, this.dependencies.identity.snapshot.signingFingerprint), kind, verifiedTicket);
|
|
308
280
|
// Acknowledging an already-held userId changes `userIdAcknowledged` without
|
|
309
281
|
// changing the snapshot; persistence subscribers must still observe it.
|
|
310
282
|
if (this.snapshotValue === previous &&
|
|
@@ -326,15 +298,25 @@ class SessionService {
|
|
|
326
298
|
this.setSnapshot(mergeSessionContext(this.snapshotValue, { userId }, this.dependencies.identity.snapshot.signingFingerprint));
|
|
327
299
|
}
|
|
328
300
|
subscribe = (listener) => this.listeners.subscribe(listener);
|
|
329
|
-
setSnapshot(next) {
|
|
301
|
+
setSnapshot(next, kind, verifiedTicket) {
|
|
330
302
|
const previous = this.snapshotValue;
|
|
331
|
-
|
|
332
|
-
|
|
303
|
+
const lifetime = sessionLifetime(this);
|
|
304
|
+
const boundary = sessionBoundary(previous, next, kind);
|
|
305
|
+
const retired = boundary &&
|
|
306
|
+
lifetime.transition(previous.isAuthenticated || previous.authToken !== null, next.isAuthenticated);
|
|
307
|
+
if (boundary || previous.authToken !== next.authToken) {
|
|
308
|
+
this.dependencies.api.setAuthToken(next.authToken, {
|
|
309
|
+
verifiedTicket,
|
|
310
|
+
boundary,
|
|
311
|
+
});
|
|
333
312
|
}
|
|
334
|
-
|
|
313
|
+
lifetime.lastRenewal = kind === "renewal" ? next : null;
|
|
314
|
+
if (!retired && sessionSnapshotsEqual(previous, next)) {
|
|
335
315
|
return;
|
|
336
316
|
}
|
|
337
317
|
this.snapshotValue = next;
|
|
318
|
+
if (retired)
|
|
319
|
+
lifetime.onBoundary?.();
|
|
338
320
|
this.listeners.notify();
|
|
339
321
|
}
|
|
340
322
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBA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C9D,CAAC;IAED,cAAc,CAAC,OAAgB;QAC7B,IAAI,IAAI,CAAC,gBAAgB,KAAK,OAAO,EAAE,CAAC;YACtC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;QAChC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,MAAqB;QAC7B,IAAI,CAAC,WAAW,CACd,mBAAmB,CACjB,IAAI,CAAC,aAAa,EAClB,EAAE,MAAM,EAAE,EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,kBAAkB,CACvD,CACF,CAAC;IACJ,CAAC;IAED,SAAS,GAAG,CAAC,QAAyB,EAAgB,EAAE,CACtD,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE7B,WAAW,CAAC,IAAqB;QACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IAAI,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;YAC1C,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,qBAAqB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;YAC1C,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n bootstrapRootContainer,\n registerIdentity as registerIdentityWorkflow,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport {\n emptySessionSnapshot,\n mergeSessionContext,\n registrationSessionResult,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireSessionTrustDomain,\n requireUserIdentityAvailable,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport {\n authenticateUnlessSuspended,\n refuseSessionLogin,\n} from \"./sessionLoginRefusal\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport function createSession(dependencies: SessionDependencies): Session {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(\n isCurrent: () => boolean = () => true,\n ): ReturnType<typeof bootstrapRootContainer> {\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n // Preserve a logged-in session's acknowledged root during local recovery.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n this.dependencies.database.requireExecSql(\"bootstrapLocalRootContainer\"),\n );\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n async login(challengeHex?: string | undefined): Promise<boolean> {\n const signingKeyPair =\n this.dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!fingerprint) {\n return false;\n }\n // A refusal below clears the session it is evidence against; a session\n // another login committed meanwhile is not that session and stays.\n const snapshotAtStart = this.snapshotValue;\n const identitySnapshot = this.dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n return false;\n }\n if (identitySnapshot.signingKeyPair !== signingKeyPair) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n this.dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n this.dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = await authenticateUnlessSuspended(\n () =>\n challengeHex\n ? this.dependencies.api.authenticateWithChallenge(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n )\n : this.dependencies.api.authenticate(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n ),\n () => {\n if (this.authToken === snapshotAtStart.authToken) this.logout();\n },\n );\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) {\n return false;\n }\n\n if (!authentication) {\n this.logout();\n this.dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n this.identityAcknowledgments.assertMatches(\n authentication.userId,\n fingerprint,\n );\n await pinLocalUserIdentity(authentication.userId, {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n });\n if (this.dependencies.identity.snapshot !== identitySnapshot)\n return false;\n this.identityAcknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => this.logout(),\n report: this.dependencies.reportSecurityIncident,\n });\n }\n // A changed root for this identity+org is refused before the token is\n // usable. Decision and commit are one synchronous step against the live\n // snapshot (no await in between); the refusal clears the prior session in\n // that same step and then reports its own incident.\n await commitSessionRootAcknowledgment({\n context: {\n authToken: authentication.token,\n defaultOrganizationId: authentication.organizationId,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId: authentication.organizationId,\n userId: authentication.userId,\n },\n onRefused: () => {\n if (this.snapshotValue === snapshotAtStart) this.logout();\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: authentication,\n session: this,\n signingFingerprint: fingerprint,\n });\n this.dependencies.log(\"Authentication successful\");\n return true;\n }\n\n logout(): void {\n this.setContext({ authToken: null, isAuthenticated: false, isRoot: false });\n }\n\n async logoutRemote(): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n if (this.dependencies.identity.snapshot === identitySnapshot) {\n this.logout();\n }\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n identityTrustDomain: requireSessionTrustDomain(this.dependencies),\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n this.dependencies.identity.snapshot === identitySnapshot,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primeProvisionedState: this.dependencies.primeProvisionedState,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return registrationSessionResult(response);\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const response = await createSessionOrganization(this.dependencies, {\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: SessionSnapshot): void {\n const previous = this.snapshotValue;\n if (previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken);\n }\n\n if (sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,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SAAS,KAAK,IAAI,EACvD,IAAI,CAAC,eAAe,CACrB,CAAC;QACJ,IAAI,QAAQ,IAAI,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;YACtD,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE;gBACjD,cAAc;gBACd,QAAQ;aACT,CAAC,CAAC;QACL,CAAC;QACD,QAAQ,CAAC,WAAW,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxD,IAAI,CAAC,OAAO,IAAI,qBAAqB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;YACtD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,OAAO;YAAE,QAAQ,CAAC,UAAU,EAAE,EAAE,CAAC;QACrC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { createListenerSet } from \"../../data/shared/listenerSet\";\nimport {\n bootstrapRootContainer,\n registerIdentity as registerIdentityWorkflow,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport {\n emptySessionSnapshot,\n hostSessionUpdate,\n mergeSessionContext,\n registrationSessionResult,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireSessionTrustDomain,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport {\n type SessionTransition,\n sessionBoundary,\n sessionLifetime,\n} from \"./sessionLifetime\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport { authenticateSession } from \"./sessionLogin\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport { sessionLifetime } from \"./sessionLifetime\";\n\nexport function createSession(\n dependencies: SessionDependencies,\n): Session & { renewExpired(): Promise<boolean> } {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private refusedSignIn: number | null = null;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n captureSignIn(purpose?: \"restore\"): () => boolean {\n return sessionLifetime(this).currentSignIn(purpose);\n }\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(\n isCurrent: () => boolean = () => true,\n ): ReturnType<typeof bootstrapRootContainer> {\n const signInCurrent = this.captureSignIn();\n if (!isCurrent()) throw new Error(\"Identity change was superseded.\");\n // Preserve a logged-in session's acknowledged root during local recovery.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n sessionLifetime(this).bind(\n this.dependencies.database.requireExecSql(\n \"bootstrapLocalRootContainer\",\n ),\n ),\n );\n if (!signInCurrent() || !isCurrent())\n throw new Error(\"Identity change was superseded.\");\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n login(challengeHex?: string): Promise<boolean> {\n return authenticateSession(\n this.dependencies,\n this,\n this.identityAcknowledgments,\n challengeHex,\n false,\n );\n }\n\n renewExpired = (): Promise<boolean> => {\n if (!this.authToken || !this.dependencies.identity.signingKeyPair) {\n this.clearAuthentication(true);\n return Promise.resolve(false);\n }\n return authenticateSession(\n this.dependencies,\n this,\n this.identityAcknowledgments,\n undefined,\n true,\n );\n };\n\n logout(): void {\n this.clearAuthentication(false);\n }\n\n clearAuthentication(renewal: boolean): void {\n if (renewal) this.refusedSignIn = sessionLifetime(this).signInRevision;\n this.commitContext(\n { authToken: null, isAuthenticated: false, isRoot: false },\n renewal ? \"renewal-refused\" : \"boundary\",\n );\n }\n\n async logoutRemote(\n onLocalLogout?: (current: () => boolean) => void | Promise<void>,\n ): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const lifetime = sessionLifetime(this);\n const revision = lifetime.signInRevision;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n const sameIdentity = () =>\n this.dependencies.identity.snapshot === identitySnapshot;\n const clearedHere =\n sameIdentity() && revision === lifetime.signInRevision;\n if (clearedHere) this.logout();\n // The same local sign-out may already have happened during a refused\n // renewal. A later explicit logout or sign-in supersedes this cleanup.\n const current = () =>\n sameIdentity() &&\n !this.isAuthenticated &&\n lifetime.signInRevision === revision + 1;\n if (current() && (clearedHere || this.refusedSignIn === revision))\n await onLocalLogout?.(current);\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const sessionCurrent = this.captureSignIn();\n const isCurrent = () =>\n sessionCurrent() &&\n this.dependencies.identity.snapshot === identitySnapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n isCurrent,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (!isCurrent()) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n identityTrustDomain: requireSessionTrustDomain(this.dependencies),\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: isCurrent,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primeProvisionedState: this.dependencies.primeProvisionedState,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (!isCurrent()) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return registrationSessionResult(response);\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const isCurrent = sessionLifetime(this).capture();\n const response = await createSessionOrganization(this.dependencies, {\n isCurrent,\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !isCurrent() ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n const isCurrent = sessionLifetime(this).capture();\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n isCurrent() &&\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n if (authToken === null) this.logout();\n else this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n this.commitContext(...hostSessionUpdate(context));\n }\n\n commitContext(\n context: SessionContext,\n kind?: SessionTransition,\n verifiedTicket?: string,\n ): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n kind,\n verifiedTicket,\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(\n next: SessionSnapshot,\n kind?: SessionTransition,\n verifiedTicket?: string,\n ): void {\n const previous = this.snapshotValue;\n\n const lifetime = sessionLifetime(this);\n const boundary = sessionBoundary(previous, next, kind);\n const retired =\n boundary &&\n lifetime.transition(\n previous.isAuthenticated || previous.authToken !== null,\n next.isAuthenticated,\n );\n if (boundary || previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken, {\n verifiedTicket,\n boundary,\n });\n }\n lifetime.lastRenewal = kind === \"renewal\" ? next : null;\n if (!retired && sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n if (retired) lifetime.onBoundary?.();\n this.listeners.notify();\n }\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createKeyedQueue } from "../../data/shared/keyedQueue.js";
|
|
2
|
+
const queues = new WeakMap();
|
|
3
|
+
/** Keep already dispatched host writes in order across sign-ins. A retired
|
|
4
|
+
* snapshot cannot begin a new write or supply another chunk for a stream. */
|
|
5
|
+
export function createSessionBlobStore(store, assertCurrent) {
|
|
6
|
+
const queue = queues.get(store) ?? createKeyedQueue();
|
|
7
|
+
queues.set(store, queue);
|
|
8
|
+
async function guarded(work) {
|
|
9
|
+
assertCurrent();
|
|
10
|
+
const result = await work();
|
|
11
|
+
assertCurrent();
|
|
12
|
+
return result;
|
|
13
|
+
}
|
|
14
|
+
function currentSource(source) {
|
|
15
|
+
return {
|
|
16
|
+
byteLength: source.byteLength,
|
|
17
|
+
read: (offset, length) => guarded(() => source.read(offset, length)),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function commitGuard(check) {
|
|
21
|
+
return check
|
|
22
|
+
? () => {
|
|
23
|
+
assertCurrent();
|
|
24
|
+
check();
|
|
25
|
+
}
|
|
26
|
+
: assertCurrent;
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
deleteBytes: (key, check) => queue(key, () => guarded(() => store.deleteBytes(key, commitGuard(check)))),
|
|
30
|
+
openByteSource: (key) => queue(key, async () => {
|
|
31
|
+
const source = await guarded(() => store.openByteSource(key));
|
|
32
|
+
return source && currentSource(source);
|
|
33
|
+
}),
|
|
34
|
+
readBytes: (key) => queue(key, () => guarded(() => store.readBytes(key))),
|
|
35
|
+
writeByteSource: (key, source, check) => queue(key, () => guarded(() => store.writeByteSource(key, currentSource(source), commitGuard(check)))),
|
|
36
|
+
writeBytes: (key, bytes, check) => queue(key, () => guarded(() => store.writeBytes(key, bytes, commitGuard(check)))),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=sessionBlobStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionBlobStore.js","sourceRoot":"","sources":["sessionBlobStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAEhE,MAAM,MAAM,GAAG,IAAI,OAAO,EAAkD,CAAC;AAE7E;6EAC6E;AAC7E,MAAM,UAAU,sBAAsB,CACpC,KAAgB,EAChB,aAAyB;IAEzB,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,gBAAgB,EAAE,CAAC;IACtD,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAEzB,KAAK,UAAU,OAAO,CAAI,IAAsB;QAC9C,aAAa,EAAE,CAAC;QAChB,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;QAC5B,aAAa,EAAE,CAAC;QAChB,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,SAAS,a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e,CAAC,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,CACtE,CACF;QACH,UAAU,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAChC,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,CACd,OAAO,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAChE;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobByteSource, BlobStore } from \"../../data/blobs/blobContracts\";\nimport { createKeyedQueue } from \"../../data/shared/keyedQueue\";\n\nconst queues = new WeakMap<BlobStore, ReturnType<typeof createKeyedQueue>>();\n\n/** Keep already dispatched host writes in order across sign-ins. A retired\n * snapshot cannot begin a new write or supply another chunk for a stream. */\nexport function createSessionBlobStore(\n store: BlobStore,\n assertCurrent: () => void,\n): BlobStore {\n const queue = queues.get(store) ?? createKeyedQueue();\n queues.set(store, queue);\n\n async function guarded<T>(work: () => Promise<T>): Promise<T> {\n assertCurrent();\n const result = await work();\n assertCurrent();\n return result;\n }\n\n function currentSource(source: BlobByteSource): BlobByteSource {\n return {\n byteLength: source.byteLength,\n read: (offset, length) => guarded(() => source.read(offset, length)),\n };\n }\n\n function commitGuard(check?: () => void) {\n return check\n ? () => {\n assertCurrent();\n check();\n }\n : assertCurrent;\n }\n\n return {\n deleteBytes: (key, check) =>\n queue(key, () =>\n guarded(() => store.deleteBytes(key, commitGuard(check))),\n ),\n openByteSource: (key) =>\n queue(key, async () => {\n const source = await guarded(() => store.openByteSource(key));\n return source && currentSource(source);\n }),\n readBytes: (key) => queue(key, () => guarded(() => store.readBytes(key))),\n writeByteSource: (key, source, check) =>\n queue(key, () =>\n guarded(() =>\n store.writeByteSource(key, currentSource(source), commitGuard(check)),\n ),\n ),\n writeBytes: (key, bytes, check) =>\n queue(key, () =>\n guarded(() => store.writeBytes(key, bytes, commitGuard(check))),\n ),\n };\n}\n"]}
|
|
@@ -2,6 +2,17 @@ import { restoreSessionRoots } from "./sessionRootAuthority.js";
|
|
|
2
2
|
function mergedUserId(previous, context) {
|
|
3
3
|
return "userId" in context ? (context.userId ?? null) : previous.userId;
|
|
4
4
|
}
|
|
5
|
+
export function hostSessionUpdate(context) {
|
|
6
|
+
if (("isAuthenticated" in context && !context.isAuthenticated) ||
|
|
7
|
+
("authToken" in context && typeof context.authToken !== "string"))
|
|
8
|
+
return [
|
|
9
|
+
{ ...context, authToken: null, isAuthenticated: false, isRoot: false },
|
|
10
|
+
"boundary",
|
|
11
|
+
];
|
|
12
|
+
if (context.isAuthenticated === true && typeof context.authToken === "string")
|
|
13
|
+
return [context, "boundary"];
|
|
14
|
+
return [context];
|
|
15
|
+
}
|
|
5
16
|
export function mergeSessionContext(previous, context, signingFingerprint) {
|
|
6
17
|
const rootAcknowledgments = restoreSessionRoots(previous.rootAcknowledgments, context.rootAcknowledgments, signingFingerprint, mergedUserId(previous, context));
|
|
7
18
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionContext.js","sourceRoot":"","sources":["sessionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAO7D,SAAS,YAAY,CACnB,QAAyB,EACzB,OAAuB;IAEvB,OAAO,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC1E,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,QAAyB,EACzB,OAAuB,EACvB,kBAAiC;IAEjC,MAAM,mBAAmB,GAAG,mBAAmB,CAC7C,QAAQ,CAAC,mBAAmB,EAC5B,OAAO,CAAC,mBAAmB,EAC3B,kBAAkB,EAClB,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAChC,CAA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I,CAAC,eAAe;QACjD,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM;QAC/B,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,cAAc;QAC/C,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAChC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,mBAAmB,EAAE,EAAE;QACvB,SAAS,EAAE,IAAI;QACf,WAAW,EAAE,IAAI;QACjB,qBAAqB,EAAE,IAAI;QAC3B,eAAe,EAAE,KAAK;QACtB,MAAM,EAAE,KAAK;QACb,cAAc,EAAE,IAAI;QACpB,MAAM,EAAE,IAAI;KACb,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,KAKzC;IACC,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,WAAW,EAAE,KAAK,CAAC,eAAe;QAClC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC;AACJ,CAAC","sourcesContent":["import { restoreSessionRoots } from \"./sessionRootAuthority\";\nimport type {\n SessionContext,\n SessionRegistrationResult,\n SessionSnapshot,\n} from \"./sessionTypes\";\n\nfunction mergedUserId(\n previous: SessionSnapshot,\n context: SessionContext,\n): SessionSnapshot[\"userId\"] {\n return \"userId\" in context ? (context.userId ?? null) : previous.userId;\n}\n\nexport function mergeSessionContext(\n previous: SessionSnapshot,\n context: SessionContext,\n signingFingerprint: string | null,\n): SessionSnapshot {\n const rootAcknowledgments = restoreSessionRoots(\n previous.rootAcknowledgments,\n context.rootAcknowledgments,\n signingFingerprint,\n mergedUserId(previous, context),\n );\n return {\n rootAcknowledgments,\n authToken:\n \"authToken\" in context ? (context.authToken ?? null) : previous.authToken,\n containerId:\n \"containerId\" in context\n ? (context.containerId ?? null)\n : previous.containerId,\n defaultOrganizationId:\n \"defaultOrganizationId\" in context\n ? (context.defaultOrganizationId ?? null)\n : previous.defaultOrganizationId,\n isAuthenticated:\n \"isAuthenticated\" in context\n ? (context.isAuthenticated ?? false)\n : previous.isAuthenticated,\n isRoot: \"isRoot\" in context ? (context.isRoot ?? false) : previous.isRoot,\n organizationId:\n \"organizationId\" in context\n ? (context.organizationId ?? null)\n : previous.organizationId,\n userId: mergedUserId(previous, context),\n };\n}\n\nexport function sessionSnapshotsEqual(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n previous.rootAcknowledgments === next.rootAcknowledgments &&\n previous.authToken === next.authToken &&\n previous.containerId === next.containerId &&\n previous.defaultOrganizationId === next.defaultOrganizationId &&\n previous.isAuthenticated === next.isAuthenticated &&\n previous.isRoot === next.isRoot &&\n previous.organizationId === next.organizationId &&\n previous.userId === next.userId\n );\n}\n\nexport function emptySessionSnapshot(): SessionSnapshot {\n return {\n rootAcknowledgments: [],\n authToken: null,\n containerId: null,\n defaultOrganizationId: null,\n isAuthenticated: false,\n isRoot: false,\n organizationId: null,\n userId: null,\n };\n}\n\nexport function registrationSessionResult(input: {\n readonly challenge: string;\n readonly rootContainerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}): SessionRegistrationResult {\n return {\n challenge: input.challenge,\n containerId: input.rootContainerId,\n organizationId: input.organizationId,\n userId: input.userId,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sessionContext.js","sourceRoot":"","sources":["sessionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAO7D,SAAS,YAAY,CACnB,QAAyB,EACzB,OAAuB;IAEvB,OAAO,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC1E,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,OAAuB;IAEvB,IACE,CAAC,iBAAiB,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,e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AC,cAAc;QACpC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC;AACJ,CAAC","sourcesContent":["import { restoreSessionRoots } from \"./sessionRootAuthority\";\nimport type {\n SessionContext,\n SessionRegistrationResult,\n SessionSnapshot,\n} from \"./sessionTypes\";\n\nfunction mergedUserId(\n previous: SessionSnapshot,\n context: SessionContext,\n): SessionSnapshot[\"userId\"] {\n return \"userId\" in context ? (context.userId ?? null) : previous.userId;\n}\n\nexport function hostSessionUpdate(\n context: SessionContext,\n): [SessionContext, \"boundary\"?] {\n if (\n (\"isAuthenticated\" in context && !context.isAuthenticated) ||\n (\"authToken\" in context && typeof context.authToken !== \"string\")\n )\n return [\n { ...context, authToken: null, isAuthenticated: false, isRoot: false },\n \"boundary\",\n ];\n if (context.isAuthenticated === true && typeof context.authToken === \"string\")\n return [context, \"boundary\"];\n return [context];\n}\n\nexport function mergeSessionContext(\n previous: SessionSnapshot,\n context: SessionContext,\n signingFingerprint: string | null,\n): SessionSnapshot {\n const rootAcknowledgments = restoreSessionRoots(\n previous.rootAcknowledgments,\n context.rootAcknowledgments,\n signingFingerprint,\n mergedUserId(previous, context),\n );\n return {\n rootAcknowledgments,\n authToken:\n \"authToken\" in context ? (context.authToken ?? null) : previous.authToken,\n containerId:\n \"containerId\" in context\n ? (context.containerId ?? null)\n : previous.containerId,\n defaultOrganizationId:\n \"defaultOrganizationId\" in context\n ? (context.defaultOrganizationId ?? null)\n : previous.defaultOrganizationId,\n isAuthenticated:\n \"isAuthenticated\" in context\n ? (context.isAuthenticated ?? false)\n : previous.isAuthenticated,\n isRoot: \"isRoot\" in context ? (context.isRoot ?? false) : previous.isRoot,\n organizationId:\n \"organizationId\" in context\n ? (context.organizationId ?? null)\n : previous.organizationId,\n userId: mergedUserId(previous, context),\n };\n}\n\nexport function sessionSnapshotsEqual(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n previous.rootAcknowledgments === next.rootAcknowledgments &&\n previous.authToken === next.authToken &&\n previous.containerId === next.containerId &&\n previous.defaultOrganizationId === next.defaultOrganizationId &&\n previous.isAuthenticated === next.isAuthenticated &&\n previous.isRoot === next.isRoot &&\n previous.organizationId === next.organizationId &&\n previous.userId === next.userId\n );\n}\n\nexport function emptySessionSnapshot(): SessionSnapshot {\n return {\n rootAcknowledgments: [],\n authToken: null,\n containerId: null,\n defaultOrganizationId: null,\n isAuthenticated: false,\n isRoot: false,\n organizationId: null,\n userId: null,\n };\n}\n\nexport function registrationSessionResult(input: {\n readonly challenge: string;\n readonly rootContainerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}): SessionRegistrationResult {\n return {\n challenge: input.challenge,\n containerId: input.rootContainerId,\n organizationId: input.organizationId,\n userId: input.userId,\n };\n}\n"]}
|
|
@@ -8,7 +8,7 @@ export declare class SessionIdentityAcknowledgments {
|
|
|
8
8
|
isAcknowledged(userId: string | null | undefined, fingerprint: string | null): boolean;
|
|
9
9
|
remember(userId: string | null | undefined, fingerprint: string | null): void;
|
|
10
10
|
}
|
|
11
|
-
export type UserIdentityAvailable = (userId: string, candidate: LocalUserIdentityCandidate) => Promise<void>;
|
|
11
|
+
export type UserIdentityAvailable = (userId: string, candidate: LocalUserIdentityCandidate, assertCurrent?: () => void) => Promise<void>;
|
|
12
12
|
export declare function requireUserIdentityAvailable(onUserIdentityAvailable: UserIdentityAvailable | undefined, operation: string): UserIdentityAvailable;
|
|
13
13
|
export declare function requireSessionTrustDomain(input: {
|
|
14
14
|
readonly identityTrustDomain: string | null;
|
|
@@ -16,6 +16,7 @@ export declare function requireSessionTrustDomain(input: {
|
|
|
16
16
|
export declare function requireRegistrationIdentityPinner(input: {
|
|
17
17
|
readonly identity: Identity;
|
|
18
18
|
readonly identitySnapshot: IdentitySnapshot;
|
|
19
|
+
readonly isCurrent: () => boolean;
|
|
19
20
|
readonly onUserIdentityAvailable?: UserIdentityAvailable | undefined;
|
|
20
21
|
}): UserIdentityAvailable;
|
|
21
22
|
/** Registration made no server request; try login with the bound identity. */
|
|
@@ -35,13 +35,17 @@ export function requireSessionTrustDomain(input) {
|
|
|
35
35
|
export function requireRegistrationIdentityPinner(input) {
|
|
36
36
|
const onUserIdentityAvailable = requireUserIdentityAvailable(input.onUserIdentityAvailable, "Registration");
|
|
37
37
|
return async (userId, candidate) => {
|
|
38
|
+
const assertCurrent = () => {
|
|
39
|
+
if (!input.isCurrent() ||
|
|
40
|
+
input.identity.snapshot !== input.identitySnapshot) {
|
|
41
|
+
throw new KeyingVerificationError("object_mismatch", "Local identity changed during registration trust establishment");
|
|
42
|
+
}
|
|
43
|
+
};
|
|
38
44
|
await onUserIdentityAvailable(userId, {
|
|
39
45
|
...candidate,
|
|
40
46
|
signingKeyFingerprint: input.identitySnapshot.signingFingerprint,
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
throw new KeyingVerificationError("object_mismatch", "Local identity changed during registration trust establishment");
|
|
44
|
-
}
|
|
47
|
+
}, assertCurrent);
|
|
48
|
+
assertCurrent();
|
|
45
49
|
};
|
|
46
50
|
}
|
|
47
51
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionIdentityTrust.js","sourceRoot":"","sources":["sessionIdentityTrust.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAI5D,kFAAkF;AAClF,MAAM,OAAO,8BAA8B;IACxB,oBAAoB,GAAG,IAAI,GAAG,EAAkB,CAAC;IAElE,aAAa,CAAC,MAAc,EAAE,WAAmB;QAC/C,MAAM,kBAAkB,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACtE,IAAI,kBAAkB,IAAI,kBAAkB,KAAK,MAAM,EAAE,CAAC;YACxD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,sDAAsD,CACvD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,4EAA4E;IAC5E,cAAc,CACZ,MAAiC,EACjC,WAA0B;QAE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AC,YAAY,CAAC,wBAAwB,EAAE,CAAC;QAC3C,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,gEAAgE,CACjE,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,kBAAkB;QAAE,OAAO,IAAI,CAAC;IACrC,MAAM,WAAW,GACf,MAAM,YAAY,CAAC,wBAAwB,CAAC,kBAAkB,CAAC,CAAC;IAClE,IAAI,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC;IAC9B,YAAY,CAAC,GAAG,CACd,8DAA8D,WAAW,EAAE,CAC5E,CAAC;IACF,OAAO,EAAE,MAAM,EAAE,wBAAwB,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;AACnE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport type { Identity, IdentitySnapshot } from \"../identity\";\n\n/** Successful auth and fingerprint-bound host restores establish this binding. */\nexport class SessionIdentityAcknowledgments {\n private readonly userIdsByFingerprint = new Map<string, string>();\n\n assertMatches(userId: string, fingerprint: string): void {\n const acknowledgedUserId = this.userIdsByFingerprint.get(fingerprint);\n if (acknowledgedUserId && acknowledgedUserId !== userId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Login user ID differs from the acknowledged identity\",\n );\n }\n }\n\n /** True only for a user ID the server acknowledged for this fingerprint. */\n isAcknowledged(\n userId: string | null | undefined,\n fingerprint: string | null,\n ): boolean {\n return (\n !!userId &&\n !!fingerprint &&\n this.userIdsByFingerprint.get(fingerprint) === userId\n );\n }\n\n remember(\n userId: string | null | undefined,\n fingerprint: string | null,\n ): void {\n if (!userId || !fingerprint) return;\n this.assertMatches(userId, fingerprint);\n this.userIdsByFingerprint.set(fingerprint, userId);\n }\n}\n\nexport type UserIdentityAvailable = (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n) => Promise<void>;\n\nexport function requireUserIdentityAvailable(\n onUserIdentityAvailable: UserIdentityAvailable | undefined,\n operation: string,\n): UserIdentityAvailable {\n if (!onUserIdentityAvailable) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${operation} requires the durable local identity trust service`,\n );\n }\n return onUserIdentityAvailable;\n}\n\nexport function requireSessionTrustDomain(input: {\n readonly identityTrustDomain: string | null;\n}): string {\n if (!input.identityTrustDomain)\n throw new Error(\"Identity trust domain is unavailable\");\n return input.identityTrustDomain;\n}\n\nexport function requireRegistrationIdentityPinner(input: {\n readonly identity: Identity;\n readonly identitySnapshot: IdentitySnapshot;\n readonly isCurrent: () => boolean;\n readonly onUserIdentityAvailable?: UserIdentityAvailable | undefined;\n}): UserIdentityAvailable {\n const onUserIdentityAvailable = requireUserIdentityAvailable(\n input.onUserIdentityAvailable,\n \"Registration\",\n );\n return async (userId, candidate) => {\n const assertCurrent = () => {\n if (\n !input.isCurrent() ||\n input.identity.snapshot !== input.identitySnapshot\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Local identity changed during registration trust establishment\",\n );\n }\n };\n await onUserIdentityAvailable(\n userId,\n {\n ...candidate,\n signingKeyFingerprint: input.identitySnapshot.signingFingerprint,\n },\n assertCurrent,\n );\n assertCurrent();\n };\n}\n\n/** Registration made no server request; try login with the bound identity. */\nexport interface SessionRegistrationRefusal {\n readonly status: \"identity-already-bound\";\n readonly userId: string;\n}\n\nexport type BoundUserIdLookup = (\n signingKeyFingerprint: string,\n) => Promise<string | null>;\n\n/**\n * A key this device already binds to a user belongs to that user: the trust\n * store holds one user per key, so a new registration's pin would be refused\n * only after the server had created the account. Registration declines before\n * touching the server instead; like a lost or conflicting registration, the\n * caller then proves ownership by logging in. After an environment reset this\n * requires clearing the device's local data.\n */\nexport async function registrationKeyAlreadyBound(\n dependencies: {\n readonly boundUserIdForSigningKey?: BoundUserIdLookup | undefined;\n readonly log: (message: string) => void;\n },\n signingFingerprint: string | null,\n): Promise<SessionRegistrationRefusal | null> {\n if (!dependencies.boundUserIdForSigningKey) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Registration requires the durable local identity trust service\",\n );\n }\n if (!signingFingerprint) return null;\n const boundUserId =\n await dependencies.boundUserIdForSigningKey(signingFingerprint);\n if (!boundUserId) return null;\n dependencies.log(\n `Registration skipped: this signing key is already bound to ${boundUserId}`,\n );\n return { status: \"identity-already-bound\", userId: boundUserId };\n}\n"]}
|