@tearleads/client-sdk 0.1.250 → 0.1.252
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 +14 -25
- package/Tearleads.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 +1 -1
- package/client/runtime/workflowRuntime.js +20 -77
- 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/documents/shared/events.js +2 -1
- package/data/documents/shared/events.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/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/internal/validators/documentCreateSeedRefinements.js +2 -2
- package/internal/validators/documentCreateSeedRefinements.js.map +1 -1
- package/internal/validators/operation/auth.d.ts +50 -1703
- package/internal/validators/operation/auth.js +2 -2
- package/internal/validators/operation/auth.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +1 -294
- package/internal/validators/operation/containerMutations.js +2 -2
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/documentMutations.d.ts +1 -294
- package/internal/validators/operation/documentMutations.js +2 -2
- package/internal/validators/operation/documentMutations.js.map +1 -1
- package/internal/validators/operation/organizations.d.ts +50 -1703
- package/internal/validators/operation/organizations.js +2 -2
- package/internal/validators/operation/organizations.js.map +1 -1
- package/internal/validators/organizationProvisioningRefinements.js +2 -2
- package/internal/validators/organizationProvisioningRefinements.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -276
- package/internal/validators/request/containerMetadata.js +5 -4
- package/internal/validators/request/containerMetadata.js.map +1 -1
- package/internal/validators/request/document.d.ts +0 -277
- package/internal/validators/request/document.js +8 -4
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentCreateSeed.d.ts +99 -0
- package/internal/validators/request/documentCreateSeed.js +132 -9
- package/internal/validators/request/documentCreateSeed.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +41 -0
- package/internal/validators/request/documentSyncSchema.js +1 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -0
- package/internal/validators/request/index.js +1 -0
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organizationProvisioning.d.ts +263 -5567
- package/internal/validators/request/organizationProvisioning.js +10 -4
- package/internal/validators/request/organizationProvisioning.js.map +1 -1
- package/internal/validators/request/registration.d.ts +71 -1703
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +6 -3
- package/workflows/container-contents/container-state/create/createWithMetadata.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/documents/create/index.js +4 -4
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.d.ts +26 -11
- package/workflows/documents/sync/initialSync.js +32 -12
- package/workflows/documents/sync/initialSync.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/provisionedProfileDocument.js +2 -2
- package/workflows/registration/provisionedProfileDocument.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -68
- package/workflows/registration/provisioningBootstrapBuilders.js +3 -3
- package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { DatabaseUnavailableError } from "../../data/sqlite/availability/databaseUnavailable.js";
|
|
2
|
+
import { createScopedExecSql } from "../../data/sqlite/sqlExec.js";
|
|
3
|
+
import { SessionAuthentication } from "./authenticationMachine.js";
|
|
4
|
+
import { createSessionBlobStore } from "./sessionBlobStore.js";
|
|
5
|
+
export function sessionBoundary(previous, next, kind) {
|
|
6
|
+
if (kind === "renewal-refused")
|
|
7
|
+
return kind;
|
|
8
|
+
if (kind === "boundary" || previous.isAuthenticated !== next.isAuthenticated)
|
|
9
|
+
return "replacement";
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
class SessionLifetime {
|
|
13
|
+
epoch = 0;
|
|
14
|
+
signInRevision = 0;
|
|
15
|
+
signInCurrent = this.captureSignIn();
|
|
16
|
+
authentication = new SessionAuthentication();
|
|
17
|
+
hasSignedIn = false;
|
|
18
|
+
onBoundary;
|
|
19
|
+
lastRenewal = null;
|
|
20
|
+
stores = new WeakMap();
|
|
21
|
+
executors = new WeakMap();
|
|
22
|
+
captureSignIn() {
|
|
23
|
+
const revision = this.signInRevision;
|
|
24
|
+
return () => revision === this.signInRevision;
|
|
25
|
+
}
|
|
26
|
+
currentSignIn(purpose) {
|
|
27
|
+
const current = this.signInCurrent;
|
|
28
|
+
if (purpose !== "restore")
|
|
29
|
+
return current;
|
|
30
|
+
const canRestore = this.authentication.captureRestore();
|
|
31
|
+
return () => current() && canRestore();
|
|
32
|
+
}
|
|
33
|
+
guard() {
|
|
34
|
+
const current = this.capture();
|
|
35
|
+
return () => {
|
|
36
|
+
if (!current())
|
|
37
|
+
throw new DatabaseUnavailableError("Sign-in generation expired");
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
capture() {
|
|
41
|
+
const epoch = this.epoch;
|
|
42
|
+
return () => this.epoch === epoch;
|
|
43
|
+
}
|
|
44
|
+
transition(wasSignedIn, signedIn) {
|
|
45
|
+
this.signInRevision += 1;
|
|
46
|
+
this.signInCurrent = this.captureSignIn();
|
|
47
|
+
this.authentication.invalidate();
|
|
48
|
+
// The first sign-in adopts the device's unclaimed local work. A client
|
|
49
|
+
// that has already had a sign-in gives every replacement a fresh scope.
|
|
50
|
+
const retire = wasSignedIn || (signedIn && this.hasSignedIn);
|
|
51
|
+
if (signedIn)
|
|
52
|
+
this.hasSignedIn = true;
|
|
53
|
+
if (!retire)
|
|
54
|
+
return false;
|
|
55
|
+
this.epoch += 1;
|
|
56
|
+
this.stores = new WeakMap();
|
|
57
|
+
this.executors = new WeakMap();
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
bindBlobStore(store) {
|
|
61
|
+
const existing = this.stores.get(store);
|
|
62
|
+
if (existing)
|
|
63
|
+
return existing;
|
|
64
|
+
const bound = createSessionBlobStore(store, this.guard());
|
|
65
|
+
this.stores.set(store, bound);
|
|
66
|
+
return bound;
|
|
67
|
+
}
|
|
68
|
+
bind(execSql) {
|
|
69
|
+
const existing = this.executors.get(execSql);
|
|
70
|
+
if (existing)
|
|
71
|
+
return existing;
|
|
72
|
+
const bound = createScopedExecSql(execSql, this.guard());
|
|
73
|
+
this.executors.set(execSql, bound);
|
|
74
|
+
return bound;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const lifetimes = new WeakMap();
|
|
78
|
+
/** Private to the SDK: session epochs are process-local and never restored. */
|
|
79
|
+
export function sessionLifetime(session) {
|
|
80
|
+
let lifetime = lifetimes.get(session);
|
|
81
|
+
if (!lifetime) {
|
|
82
|
+
lifetime = new SessionLifetime();
|
|
83
|
+
lifetimes.set(session, lifetime);
|
|
84
|
+
}
|
|
85
|
+
return lifetime;
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=sessionLifetime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionLifetime.js","sourceRoot":"","sources":["sessionLifetime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,oDAAoD,CAAC;AA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C;IAED,IAAI,CAAC,OAAgB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7C,IAAI,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC9B,MAAM,KAAK,GAAG,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACnC,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,MAAM,SAAS,GAAG,IAAI,OAAO,EAA2B,CAAC;AAEzD,+EAA+E;AAC/E,MAAM,UAAU,eAAe,CAAC,OAAe;IAC7C,IAAI,QAAQ,GAAG,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACtC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;QACjC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IACnC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { BlobStore } from \"../../data/blobs/blobContracts\";\nimport { DatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport { createScopedExecSql, type ExecSql } from \"../../data/sqlite/sqlExec\";\nimport { SessionAuthentication } from \"./authenticationMachine\";\nimport { createSessionBlobStore } from \"./sessionBlobStore\";\nimport type { SessionSnapshot } from \"./sessionTypes\";\n\nexport type SessionTransition = \"boundary\" | \"renewal\" | \"renewal-refused\";\n\nexport function sessionBoundary(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n kind?: SessionTransition,\n) {\n if (kind === \"renewal-refused\") return kind;\n if (kind === \"boundary\" || previous.isAuthenticated !== next.isAuthenticated)\n return \"replacement\";\n return undefined;\n}\n\nclass SessionLifetime {\n epoch = 0;\n signInRevision = 0;\n signInCurrent = this.captureSignIn();\n readonly authentication = new SessionAuthentication();\n private hasSignedIn = false;\n onBoundary?: () => void;\n lastRenewal: SessionSnapshot | null = null;\n private stores = new WeakMap<BlobStore, BlobStore>();\n private executors = new WeakMap<ExecSql, ExecSql>();\n\n private captureSignIn(): () => boolean {\n const revision = this.signInRevision;\n return () => revision === this.signInRevision;\n }\n\n currentSignIn(purpose?: \"restore\"): () => boolean {\n const current = this.signInCurrent;\n if (purpose !== \"restore\") return current;\n const canRestore = this.authentication.captureRestore();\n return () => current() && canRestore();\n }\n\n guard(): () => void {\n const current = this.capture();\n return () => {\n if (!current())\n throw new DatabaseUnavailableError(\"Sign-in generation expired\");\n };\n }\n\n capture(): () => boolean {\n const epoch = this.epoch;\n return () => this.epoch === epoch;\n }\n\n transition(wasSignedIn: boolean, signedIn: boolean): boolean {\n this.signInRevision += 1;\n this.signInCurrent = this.captureSignIn();\n this.authentication.invalidate();\n // The first sign-in adopts the device's unclaimed local work. A client\n // that has already had a sign-in gives every replacement a fresh scope.\n const retire = wasSignedIn || (signedIn && this.hasSignedIn);\n if (signedIn) this.hasSignedIn = true;\n if (!retire) return false;\n this.epoch += 1;\n this.stores = new WeakMap();\n this.executors = new WeakMap();\n return true;\n }\n\n bindBlobStore(store: BlobStore): BlobStore {\n const existing = this.stores.get(store);\n if (existing) return existing;\n const bound = createSessionBlobStore(store, this.guard());\n this.stores.set(store, bound);\n return bound;\n }\n\n bind(execSql: ExecSql): ExecSql {\n const existing = this.executors.get(execSql);\n if (existing) return existing;\n const bound = createScopedExecSql(execSql, this.guard());\n this.executors.set(execSql, bound);\n return bound;\n }\n}\n\nconst lifetimes = new WeakMap<object, SessionLifetime>();\n\n/** Private to the SDK: session epochs are process-local and never restored. */\nexport function sessionLifetime(session: object): SessionLifetime {\n let lifetime = lifetimes.get(session);\n if (!lifetime) {\n lifetime = new SessionLifetime();\n lifetimes.set(session, lifetime);\n }\n return lifetime;\n}\n"]}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { requireUserIdentityAvailable, } from "./sessionIdentityTrust.js";
|
|
2
|
+
import { sessionLifetime } from "./sessionLifetime.js";
|
|
3
|
+
import { authenticateUnlessSuspended, refuseSessionLogin, } from "./sessionLoginRefusal.js";
|
|
4
|
+
import { commitSessionRootAcknowledgment } from "./sessionRootAuthority.js";
|
|
5
|
+
export async function authenticateSession(dependencies, session, acknowledgments, challengeHex, renewal) {
|
|
6
|
+
const attempt = sessionLifetime(session).authentication.start(renewal);
|
|
7
|
+
try {
|
|
8
|
+
return (attempt.current() &&
|
|
9
|
+
(await runAuthentication(dependencies, session, acknowledgments, challengeHex, renewal, attempt.current)));
|
|
10
|
+
}
|
|
11
|
+
finally {
|
|
12
|
+
attempt.finish();
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
async function runAuthentication(dependencies, session, acknowledgments, challengeHex, renewal, isCurrent) {
|
|
16
|
+
const signingKeyPair = dependencies.identity.requireSigningKeyPair("login");
|
|
17
|
+
const fingerprint = (await dependencies.identity.refreshSigningFingerprint()) ?? null;
|
|
18
|
+
if (!isCurrent() || !fingerprint) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
// A refusal below clears the session it is evidence against; a session
|
|
22
|
+
// another login committed meanwhile is not that session and stays.
|
|
23
|
+
const snapshotAtStart = session.snapshot;
|
|
24
|
+
const identitySnapshot = dependencies.identity.snapshot;
|
|
25
|
+
const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;
|
|
26
|
+
if (!encapsulationKeyPair ||
|
|
27
|
+
identitySnapshot.signingKeyPair !== signingKeyPair) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const pinLocalUserIdentity = requireUserIdentityAvailable(dependencies.onUserIdentityAvailable, "Login");
|
|
31
|
+
dependencies.log(challengeHex ? "Authenticating with challenge..." : "Authenticating...");
|
|
32
|
+
const authentication = await authenticate(dependencies.api, fingerprint, signingKeyPair.signingPrivateKey, challengeHex, () => {
|
|
33
|
+
if (isCurrent() && session.authToken === snapshotAtStart.authToken)
|
|
34
|
+
session.clearAuthentication(renewal);
|
|
35
|
+
});
|
|
36
|
+
const identityCurrent = () => isCurrent() && dependencies.identity.snapshot === identitySnapshot;
|
|
37
|
+
if (!identityCurrent()) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (!authentication) {
|
|
41
|
+
session.clearAuthentication(renewal);
|
|
42
|
+
dependencies.log("Authentication failed");
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
acknowledgments.assertMatches(authentication.userId, fingerprint);
|
|
47
|
+
if (renewal && authentication.userId !== snapshotAtStart.userId) {
|
|
48
|
+
session.clearAuthentication(renewal);
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
await pinLocalUserIdentity(authentication.userId, {
|
|
52
|
+
encapsulationPublicKey: encapsulationKeyPair.publicKey,
|
|
53
|
+
signingKeyFingerprint: fingerprint,
|
|
54
|
+
signingPublicKey: signingKeyPair.signingPublicKey,
|
|
55
|
+
}, () => assertSignInCurrent(identityCurrent));
|
|
56
|
+
if (!identityCurrent())
|
|
57
|
+
return false;
|
|
58
|
+
acknowledgments.remember(authentication.userId, fingerprint);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (!isCurrent())
|
|
62
|
+
return false;
|
|
63
|
+
return refuseSessionLogin(error, authentication.userId, {
|
|
64
|
+
clear: () => session.clearAuthentication(renewal),
|
|
65
|
+
report: dependencies.reportSecurityIncident,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// A changed root for this identity+org is refused before the token is
|
|
69
|
+
// usable. Decision and commit are one synchronous step against the live
|
|
70
|
+
// snapshot (no await in between); the refusal clears the prior session in
|
|
71
|
+
// that same step and then reports its own incident.
|
|
72
|
+
await commitSessionRootAcknowledgment({
|
|
73
|
+
context: authenticatedSessionContext(session, authentication, renewal),
|
|
74
|
+
onRefused: () => {
|
|
75
|
+
if (session.snapshot === snapshotAtStart)
|
|
76
|
+
session.clearAuthentication(renewal);
|
|
77
|
+
},
|
|
78
|
+
reporter: dependencies.reportSecurityIncident,
|
|
79
|
+
root: authentication,
|
|
80
|
+
session: {
|
|
81
|
+
snapshot: session.snapshot,
|
|
82
|
+
setContext: (context) => session.commitContext(context, renewal ? "renewal" : "boundary", authentication.wsTicket),
|
|
83
|
+
},
|
|
84
|
+
signingFingerprint: fingerprint,
|
|
85
|
+
});
|
|
86
|
+
dependencies.log("Authentication successful");
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
function authenticatedSessionContext(session, authentication, renewal) {
|
|
90
|
+
// An independently selected organization survives renewal. A selection
|
|
91
|
+
// following the server default follows a change to that default.
|
|
92
|
+
const { organizationId: serverDefault } = authentication;
|
|
93
|
+
const selected = session.organizationId;
|
|
94
|
+
return {
|
|
95
|
+
authToken: authentication.token,
|
|
96
|
+
defaultOrganizationId: serverDefault,
|
|
97
|
+
isAuthenticated: true,
|
|
98
|
+
isRoot: authentication.isRoot,
|
|
99
|
+
organizationId: renewal && selected && selected !== session.defaultOrganizationId
|
|
100
|
+
? selected
|
|
101
|
+
: serverDefault,
|
|
102
|
+
userId: authentication.userId,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function assertSignInCurrent(isCurrent) {
|
|
106
|
+
if (!isCurrent())
|
|
107
|
+
throw new Error("Sign-in attempt was superseded");
|
|
108
|
+
}
|
|
109
|
+
function authenticate(api, fingerprint, privateKey, challengeHex, clear) {
|
|
110
|
+
return authenticateUnlessSuspended(() => challengeHex
|
|
111
|
+
? api.authenticateWithChallenge(fingerprint, privateKey, challengeHex)
|
|
112
|
+
: api.authenticate(fingerprint, privateKey), clear);
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=sessionLogin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionLogin.js","sourceRoot":"","sources":["sessionLogin.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,GAE7B,MAAM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AAC;IACH,YAAY,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,2BAA2B,CAClC,OAAgB,EAChB,cAAqE,EACrE,OAAgB;IAEhB,uEAAuE;IACvE,iEAAiE;IACjE,MAAM,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,cAAc,CAAC;IACzD,MAAM,QAAQ,GAAG,OAAO,CAAC,cAAc,CAAC;IACxC,OAAO;QACL,SAAS,EAAE,cAAc,CAAC,KAAK;QAC/B,qBAAqB,EAAE,aAAa;QACpC,eAAe,EAAE,IAAI;QACrB,MAAM,EAAE,cAAc,CAAC,MAAM;QAC7B,cAAc,EACZ,OAAO,IAAI,QAAQ,IAAI,QAAQ,KAAK,OAAO,CAAC,qBAAqB;YAC/D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,aAAa;QACnB,MAAM,EAAE,cAAc,CAAC,MAAM;KAC9B,CAAC;AACJ,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAwB;IACnD,IAAI,CAAC,SAAS,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,YAAY,CACnB,GAAc,EACd,WAAmB,EACnB,UAAsB,EACtB,YAAgC,EAChC,KAAiB;IAEjB,OAAO,2BAA2B,CAChC,GAAG,EAAE,CACH,YAAY;QACV,CAAC,CAAC,GAAG,CAAC,yBAAyB,CAAC,WAAW,EAAE,UAAU,EAAE,YAAY,CAAC;QACtE,CAAC,CAAC,GAAG,CAAC,YAAY,CAAC,WAAW,EAAE,UAAU,CAAC,EAC/C,KAAK,CACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n requireUserIdentityAvailable,\n type SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { sessionLifetime } from \"./sessionLifetime\";\nimport {\n authenticateUnlessSuspended,\n refuseSessionLogin,\n} from \"./sessionLoginRefusal\";\nimport { commitSessionRootAcknowledgment } from \"./sessionRootAuthority\";\nimport type {\n Session,\n SessionContext,\n SessionDependencies,\n} from \"./sessionTypes\";\n\nexport async function authenticateSession(\n dependencies: SessionDependencies,\n session: Session & {\n commitContext(\n context: SessionContext,\n kind: \"renewal\" | \"boundary\",\n verifiedTicket: string,\n ): void;\n clearAuthentication(renewal: boolean): void;\n },\n acknowledgments: SessionIdentityAcknowledgments,\n challengeHex: string | undefined,\n renewal: boolean,\n): Promise<boolean> {\n const attempt = sessionLifetime(session).authentication.start(renewal);\n try {\n return (\n attempt.current() &&\n (await runAuthentication(\n dependencies,\n session,\n acknowledgments,\n challengeHex,\n renewal,\n attempt.current,\n ))\n );\n } finally {\n attempt.finish();\n }\n}\n\nasync function runAuthentication(\n dependencies: SessionDependencies,\n session: Parameters<typeof authenticateSession>[1],\n acknowledgments: SessionIdentityAcknowledgments,\n challengeHex: string | undefined,\n renewal: boolean,\n isCurrent: () => boolean,\n): Promise<boolean> {\n const signingKeyPair = dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!isCurrent() || !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 = session.snapshot;\n const identitySnapshot = dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (\n !encapsulationKeyPair ||\n identitySnapshot.signingKeyPair !== signingKeyPair\n ) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = await authenticate(\n dependencies.api,\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n () => {\n if (isCurrent() && session.authToken === snapshotAtStart.authToken)\n session.clearAuthentication(renewal);\n },\n );\n\n const identityCurrent = () =>\n isCurrent() && dependencies.identity.snapshot === identitySnapshot;\n if (!identityCurrent()) {\n return false;\n }\n\n if (!authentication) {\n session.clearAuthentication(renewal);\n dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n acknowledgments.assertMatches(authentication.userId, fingerprint);\n if (renewal && authentication.userId !== snapshotAtStart.userId) {\n session.clearAuthentication(renewal);\n return false;\n }\n await pinLocalUserIdentity(\n authentication.userId,\n {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n },\n () => assertSignInCurrent(identityCurrent),\n );\n if (!identityCurrent()) return false;\n acknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n if (!isCurrent()) return false;\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => session.clearAuthentication(renewal),\n report: 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: authenticatedSessionContext(session, authentication, renewal),\n onRefused: () => {\n if (session.snapshot === snapshotAtStart)\n session.clearAuthentication(renewal);\n },\n reporter: dependencies.reportSecurityIncident,\n root: authentication,\n session: {\n snapshot: session.snapshot,\n setContext: (context) =>\n session.commitContext(\n context,\n renewal ? \"renewal\" : \"boundary\",\n authentication.wsTicket,\n ),\n },\n signingFingerprint: fingerprint,\n });\n dependencies.log(\"Authentication successful\");\n return true;\n}\n\nfunction authenticatedSessionContext(\n session: Session,\n authentication: NonNullable<Awaited<ReturnType<typeof authenticate>>>,\n renewal: boolean,\n): SessionContext {\n // An independently selected organization survives renewal. A selection\n // following the server default follows a change to that default.\n const { organizationId: serverDefault } = authentication;\n const selected = session.organizationId;\n return {\n authToken: authentication.token,\n defaultOrganizationId: serverDefault,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId:\n renewal && selected && selected !== session.defaultOrganizationId\n ? selected\n : serverDefault,\n userId: authentication.userId,\n };\n}\n\nfunction assertSignInCurrent(isCurrent: () => boolean): void {\n if (!isCurrent()) throw new Error(\"Sign-in attempt was superseded\");\n}\n\nfunction authenticate(\n api: ApiClient,\n fingerprint: string,\n privateKey: Uint8Array,\n challengeHex: string | undefined,\n clear: () => void,\n) {\n return authenticateUnlessSuspended(\n () =>\n challengeHex\n ? api.authenticateWithChallenge(fingerprint, privateKey, challengeHex)\n : api.authenticate(fingerprint, privateKey),\n clear,\n );\n}\n"]}
|
|
@@ -25,7 +25,8 @@ export async function createSessionOrganization(dependencies, input) {
|
|
|
25
25
|
dbClient,
|
|
26
26
|
documentProjectors: dependencies.documentProjectors,
|
|
27
27
|
encapsulationKeyPair,
|
|
28
|
-
isIdentityCurrent: () =>
|
|
28
|
+
isIdentityCurrent: () => input.isCurrent() &&
|
|
29
|
+
dependencies.identity.snapshot === identitySnapshot,
|
|
29
30
|
log: dependencies.log,
|
|
30
31
|
logError: dependencies.logError,
|
|
31
32
|
nativeSubscriptionRestore: input.nativeSubscriptionRestore,
|
|
@@ -42,7 +43,7 @@ export async function createSessionOrganization(dependencies, input) {
|
|
|
42
43
|
dependencies.logError("Organization creation failed", error);
|
|
43
44
|
throw error;
|
|
44
45
|
}
|
|
45
|
-
if (dependencies.identity.snapshot !== identitySnapshot)
|
|
46
|
+
if (!input.isCurrent() || dependencies.identity.snapshot !== identitySnapshot)
|
|
46
47
|
return null;
|
|
47
48
|
if (!response) {
|
|
48
49
|
dependencies.log("Organization creation failed");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionOrganizationCreation.js","sourceRoot":"","sources":["sessionOrganizationCreation.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,kBAAkB,IAAI,0BAA0B,GAEjD,MAAM,8BAA8B,CAAC;AAuBtC,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,YAAqD,EACrD,
|
|
1
|
+
{"version":3,"file":"s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AAE,YAAY,CAAC,GAAG;YACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;YAC/B,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,uBAAuB,EAAE,KAAK,CAAC,OAAO,EAAE,uBAAuB;YAC/D,qBAAqB,EAAE,YAAY,CAAC,qBAAqB;YACzD,2BAA2B,EAAE,YAAY,CAAC,2BAA2B;YACrE,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,qBAAqB,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB;YAC3D,cAAc;YACd,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,YAAY,CAAC,QAAQ,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;QAC7D,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,QAAQ,CAAC,QAAQ,KAAK,gBAAgB;QAC3E,OAAO,IAAI,CAAC;IACd,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,YAAY,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QACjD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oEAAoE;IACpE,OAAO;QACL,WAAW,EAAE,QAAQ,CAAC,eAAe;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport {\n createOrganization as createOrganizationWorkflow,\n type ProvisionedSystemContainerSpec,\n} from \"../../workflows/registration\";\nimport type { ProvisionedStatePrimer } from \"../../workflows/registration/provisionedStatePrimer\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n CreateOrganizationOptions,\n SessionCreateOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionOrganizationCreationDependencies {\n readonly identityTrustDomain: string | null;\n readonly api: ApiClient;\n readonly database: Database;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly identity: Identity;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly primeProvisionedState?: ProvisionedStatePrimer | undefined;\n readonly provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport async function createSessionOrganization(\n dependencies: SessionOrganizationCreationDependencies,\n input: {\n readonly isCurrent: () => boolean;\n readonly nativeSubscriptionRestore?: boolean | undefined;\n readonly options?: CreateOrganizationOptions | undefined;\n readonly replacesOrganizationId?: string | undefined;\n readonly userId: string | null;\n },\n): Promise<SessionCreateOrganizationResult | null> {\n if (!input.userId) {\n dependencies.log(\"Create organization skipped: user id is unavailable\");\n return null;\n }\n\n const identitySnapshot = dependencies.identity.snapshot;\n const { encapsulationKeyPair, signingKeyPair } = identitySnapshot;\n if (!signingKeyPair || !encapsulationKeyPair) {\n dependencies.log(\n \"Create organization skipped: identity keys are unavailable\",\n );\n return null;\n }\n\n const dbClient = dependencies.database.client;\n if (!dbClient) {\n dependencies.log(\n \"Create organization skipped: database client is unavailable\",\n );\n return null;\n }\n\n if (!dependencies.identityTrustDomain)\n throw new Error(\"Identity trust domain is unavailable\");\n let response: Awaited<ReturnType<typeof createOrganizationWorkflow>>;\n try {\n response = await createOrganizationWorkflow({\n identityTrustDomain: dependencies.identityTrustDomain,\n apiClient: dependencies.api,\n dbClient,\n documentProjectors: dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n input.isCurrent() &&\n dependencies.identity.snapshot === identitySnapshot,\n log: dependencies.log,\n logError: dependencies.logError,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n organizationProfileName: input.options?.organizationProfileName,\n primeProvisionedState: dependencies.primeProvisionedState,\n provisionedSystemContainers: dependencies.provisionedSystemContainers,\n replacesOrganizationId: input.replacesOrganizationId,\n rosterProfileNickname: input.options?.rosterProfileNickname,\n signingKeyPair,\n userId: input.userId,\n });\n } catch (error: unknown) {\n dependencies.logError(\"Organization creation failed\", error);\n throw error;\n }\n\n if (!input.isCurrent() || dependencies.identity.snapshot !== identitySnapshot)\n return null;\n if (!response) {\n dependencies.log(\"Organization creation failed\");\n return null;\n }\n // Creating an organization does not switch the active organization.\n return {\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n };\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolveOrganizationBillingView } from "../../workflows/organizations/index.js";
|
|
2
2
|
import { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, verifyOrganizationReplacementResponse, } from "../../workflows/registration/index.js";
|
|
3
3
|
import { clearRemoteSyncState } from "../../workflows/sync/index.js";
|
|
4
|
+
import { sessionLifetime } from "./sessionLifetime.js";
|
|
4
5
|
import { PurgedOrganizationRecoveryBillingRequiredError } from "./sessionRecoveryErrors.js";
|
|
5
6
|
function requireReplacementCanSync(replacement, billing) {
|
|
6
7
|
if (!billing) {
|
|
@@ -11,10 +12,14 @@ function requireReplacementCanSync(replacement, billing) {
|
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
14
|
export async function clearSessionRemoteSyncState(dependencies, session, organizationId) {
|
|
14
|
-
const
|
|
15
|
+
const lifetime = sessionLifetime(session);
|
|
16
|
+
const isCurrent = lifetime.capture();
|
|
17
|
+
const execSql = lifetime.bind(dependencies.database.requireExecSql("clearRemoteSyncState"));
|
|
15
18
|
const result = await clearRemoteSyncState(execSql, {
|
|
16
19
|
organizationId,
|
|
17
20
|
});
|
|
21
|
+
if (!isCurrent())
|
|
22
|
+
return result;
|
|
18
23
|
dependencies.api.clearWriterProjectionCaches();
|
|
19
24
|
if (session.organizationId === organizationId) {
|
|
20
25
|
session.setContext({ containerId: null, organizationId: null });
|
|
@@ -46,7 +51,10 @@ export async function recoverPurgedSessionOrganization(dependencies, session, or
|
|
|
46
51
|
if (!userId) {
|
|
47
52
|
throw new Error("Purged organization recovery requires a current user");
|
|
48
53
|
}
|
|
49
|
-
const
|
|
54
|
+
const lifetime = sessionLifetime(session);
|
|
55
|
+
const signInCurrent = lifetime.capture();
|
|
56
|
+
const isRecoveryCurrent = () => signInCurrent() &&
|
|
57
|
+
dependencies.identity.snapshot === identitySnapshot &&
|
|
50
58
|
session.organizationId === sessionOrganizationId &&
|
|
51
59
|
session.userId === userId;
|
|
52
60
|
const billing = await dependencies.api.getOrganizationBilling(organizationId);
|
|
@@ -64,7 +72,7 @@ export async function recoverPurgedSessionOrganization(dependencies, session, or
|
|
|
64
72
|
if (!isRecoveryCurrent())
|
|
65
73
|
return null;
|
|
66
74
|
requireReplacementCanSync(replacement, replacementBilling);
|
|
67
|
-
const execSql = dependencies.database.requireExecSql("recoverPurgedOrganization");
|
|
75
|
+
const execSql = lifetime.bind(dependencies.database.requireExecSql("recoverPurgedOrganization"));
|
|
68
76
|
const reset = await clearRemoteSyncState(execSql, {
|
|
69
77
|
organizationId,
|
|
70
78
|
replacement: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,EACrC,qCAAqC,GACtC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,C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W,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n verifyOrganizationReplacementResponse,\n} from \"../../workflows/registration\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,EACrC,qCAAqC,GACtC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,8CAA8C,EAAE,MAAM,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AAE;QAAE,OAAO,IAAI,CAAC;IACtC,0BAA0B,CACxB,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,EACN,gBAAgB,CAAC,cAAc,CAChC,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,qCAAqC,CAAC;QACjE,SAAS,EAAE,iBAAiB;QAC5B,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,cAAc,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACzD,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,OAAO,CAAC,UAAU,CAAC;QACjB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,qBAAqB,EAAE,WAAW,CAAC,cAAc;QACjD,cAAc,EAAE,WAAW,CAAC,cAAc;KAC3C,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CACd,iCAAiC,WAAW,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n verifyOrganizationReplacementResponse,\n} from \"../../workflows/registration\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { sessionLifetime } from \"./sessionLifetime\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const lifetime = sessionLifetime(session);\n const isCurrent = lifetime.capture();\n const execSql = lifetime.bind(\n dependencies.database.requireExecSql(\"clearRemoteSyncState\"),\n );\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n if (!isCurrent()) return result;\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const lifetime = sessionLifetime(session);\n const signInCurrent = lifetime.capture();\n const isRecoveryCurrent = () =>\n signInCurrent() &&\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = lifetime.bind(\n dependencies.database.requireExecSql(\"recoverPurgedOrganization\"),\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
|
|
@@ -131,6 +131,8 @@ export interface Session {
|
|
|
131
131
|
* it as this identity's account.
|
|
132
132
|
*/
|
|
133
133
|
readonly userIdAcknowledged: boolean;
|
|
134
|
+
/** Stable predicate for this sign-in, including after verified renewal. */
|
|
135
|
+
captureSignIn(purpose?: "restore"): () => boolean;
|
|
134
136
|
bootstrapLocalRootContainer(isCurrent?: () => boolean): Promise<{
|
|
135
137
|
containerId: string;
|
|
136
138
|
created: boolean;
|
|
@@ -142,13 +144,15 @@ export interface Session {
|
|
|
142
144
|
listSessions(): Promise<UserSession[]>;
|
|
143
145
|
login(challengeHex?: string | undefined): Promise<boolean>;
|
|
144
146
|
logout(): void;
|
|
145
|
-
|
|
147
|
+
/** Runs host cleanup only after this invocation clears its own local session. */
|
|
148
|
+
logoutRemote(onLocalLogout?: (current: () => boolean) => void | Promise<void>): Promise<boolean>;
|
|
146
149
|
prepareNativeSubscriptionRestoreOrganization(options?: CreateOrganizationOptions): Promise<SessionCreateOrganizationResult | null>;
|
|
147
150
|
registerIdentity(options?: RegisterIdentityOptions): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null>;
|
|
148
151
|
recoverPurgedOrganization(organizationId: string, options?: CreateOrganizationOptions): Promise<SessionRecoverOrganizationResult | null>;
|
|
149
152
|
setAuthToken(authToken: string | null): void;
|
|
150
153
|
setContainerId(containerId: string | null): void;
|
|
151
|
-
/**
|
|
154
|
+
/** A host restore supplying both isAuthenticated and its token begins a
|
|
155
|
+
* sign-in. Partial view updates preserve it. User acknowledgments must match. */
|
|
152
156
|
setContext(context: SessionContext): void;
|
|
153
157
|
setOrganizationId(organizationId: string | null): void;
|
|
154
158
|
setSyncEnabled(enabled: boolean): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionTypes.js","sourceRoot":"","sources":["sessionTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedStatePrimer } from \"../../workflows/registration/provisionedStatePrimer\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n BoundUserIdLookup,\n SessionRegistrationRefusal,\n UserIdentityAvailable,\n} from \"./sessionIdentityTrust\";\n\nexport type { SessionRegistrationRefusal } from \"./sessionIdentityTrust\";\n\nexport interface SessionDependencies {\n identityTrustDomain: string | null;\n api: ApiClient;\n database: Database;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n identity: Identity;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n /** The user this device's trust store already binds a signing key to. */\n boundUserIdForSigningKey?: BoundUserIdLookup | undefined;\n onUserIdentityAvailable?: UserIdentityAvailable | undefined;\n /** Seeds what a new organization's committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /** App-owned system containers provisioned with each new organization. */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Records a refused login (a different account than acknowledged) or a\n * refused root acknowledgement; absent in bare test harnesses.\n */\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n}\n\nexport interface SessionContext {\n /** Fingerprint-bound host restore only; view selections never acknowledge roots. */\n rootAcknowledgments?: SessionSnapshot[\"rootAcknowledgments\"] | undefined;\n authToken?: string | null | undefined;\n containerId?: string | null | undefined;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId?: string | null | undefined;\n isAuthenticated?: boolean | undefined;\n /** Platform-operator flag reported by the server at login. */\n isRoot?: boolean | undefined;\n organizationId?: string | null | undefined;\n userId?: string | null | undefined;\n}\n\nexport interface SessionSnapshot {\n /**\n * Server acknowledgements retained independently of the selected container.\n * Bound to (signing fingerprint, user, organization): once acknowledged, an\n * organization's root id may only be re-acknowledged or reported purged.\n */\n rootAcknowledgments: ReadonlyArray<{\n readonly signingFingerprint: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string | null;\n }>;\n authToken: string | null;\n containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId: string | null;\n isAuthenticated: boolean;\n /** Platform-operator flag reported by the server at login. */\n isRoot: boolean;\n organizationId: string | null;\n userId: string | null;\n}\n\nexport type SessionListener = () => void;\n\nexport interface SessionRegistrationResult {\n readonly challenge: string;\n readonly containerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport interface SessionCreateOrganizationResult {\n readonly containerId: string;\n readonly organizationId: string;\n}\n\nexport interface SessionRecoverOrganizationResult\n extends SessionCreateOrganizationResult {\n readonly reset: ClearRemoteSyncStateResult;\n readonly replacedOrganizationId: string;\n}\n\nexport interface CreateOrganizationOptions {\n /** Overrides the seeded organization profile name; see registration. */\n readonly organizationProfileName?: string | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface RegisterIdentityOptions {\n /**\n * Overrides the seeded personal-organization profile name. Optional; when\n * omitted the default personal-org name is used. The demo host passes each\n * pane's peer-labeled org name (\"Peer 1's Org\").\n */\n readonly organizationProfileName?: string | undefined;\n /**\n * Overrides the seeded self roster-profile nickname. Optional; when omitted\n * the default (\"You\") is used. The demo host passes each pane's peer-labeled\n * self name (\"Peer 1 (You)\").\n */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface UserSession {\n readonly createdAt: string;\n readonly id: string;\n readonly ipAddresses: string[];\n readonly isCurrent: boolean;\n readonly lastActiveAt: string;\n readonly lastActiveIp: string | null;\n readonly signingKeyFingerprint: string;\n}\n\nexport interface Session {\n readonly authToken: string | null;\n readonly containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n readonly defaultOrganizationId: string | null;\n readonly isAuthenticated: boolean;\n /**\n * Platform-operator flag reported by the server at login. It only decides\n * whether the root console is offered; the API enforces root access itself.\n */\n readonly isRoot: boolean;\n readonly organizationId: string | null;\n readonly snapshot: SessionSnapshot;\n /** Controls server replication without changing network connectivity. */\n readonly syncEnabled: boolean;\n readonly userId: string | null;\n /**\n * Whether `userId` was acknowledged by the server for the active signing\n * identity (a successful login or a fingerprint-bound host restore). A user\n * ID chosen locally through `setUserId` is not, and hosts must not persist\n * it as this identity's account.\n */\n readonly userIdAcknowledged: boolean;\n bootstrapLocalRootContainer(isCurrent?: () => boolean): Promise<{\n containerId: string;\n created: boolean;\n }>;\n clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult>;\n createOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean>;\n destroySession(sessionId: string): Promise<boolean>;\n listSessions(): Promise<UserSession[]>;\n login(challengeHex?: string | undefined): Promise<boolean>;\n logout(): void;\n logoutRemote(): Promise<boolean>;\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null>;\n recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null>;\n setAuthToken(authToken: string | null): void;\n setContainerId(containerId: string | null): void;\n /**
|
|
1
|
+
{"version":3,"file":"sessionTypes.js","sourceRoot":"","sources":["sessionTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedStatePrimer } from \"../../workflows/registration/provisionedStatePrimer\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n BoundUserIdLookup,\n SessionRegistrationRefusal,\n UserIdentityAvailable,\n} from \"./sessionIdentityTrust\";\n\nexport type { SessionRegistrationRefusal } from \"./sessionIdentityTrust\";\n\nexport interface SessionDependencies {\n identityTrustDomain: string | null;\n api: ApiClient;\n database: Database;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n identity: Identity;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n /** The user this device's trust store already binds a signing key to. */\n boundUserIdForSigningKey?: BoundUserIdLookup | undefined;\n onUserIdentityAvailable?: UserIdentityAvailable | undefined;\n /** Seeds what a new organization's committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /** App-owned system containers provisioned with each new organization. */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Records a refused login (a different account than acknowledged) or a\n * refused root acknowledgement; absent in bare test harnesses.\n */\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n}\n\nexport interface SessionContext {\n /** Fingerprint-bound host restore only; view selections never acknowledge roots. */\n rootAcknowledgments?: SessionSnapshot[\"rootAcknowledgments\"] | undefined;\n authToken?: string | null | undefined;\n containerId?: string | null | undefined;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId?: string | null | undefined;\n isAuthenticated?: boolean | undefined;\n /** Platform-operator flag reported by the server at login. */\n isRoot?: boolean | undefined;\n organizationId?: string | null | undefined;\n userId?: string | null | undefined;\n}\n\nexport interface SessionSnapshot {\n /**\n * Server acknowledgements retained independently of the selected container.\n * Bound to (signing fingerprint, user, organization): once acknowledged, an\n * organization's root id may only be re-acknowledged or reported purged.\n */\n rootAcknowledgments: ReadonlyArray<{\n readonly signingFingerprint: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string | null;\n }>;\n authToken: string | null;\n containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId: string | null;\n isAuthenticated: boolean;\n /** Platform-operator flag reported by the server at login. */\n isRoot: boolean;\n organizationId: string | null;\n userId: string | null;\n}\n\nexport type SessionListener = () => void;\n\nexport interface SessionRegistrationResult {\n readonly challenge: string;\n readonly containerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport interface SessionCreateOrganizationResult {\n readonly containerId: string;\n readonly organizationId: string;\n}\n\nexport interface SessionRecoverOrganizationResult\n extends SessionCreateOrganizationResult {\n readonly reset: ClearRemoteSyncStateResult;\n readonly replacedOrganizationId: string;\n}\n\nexport interface CreateOrganizationOptions {\n /** Overrides the seeded organization profile name; see registration. */\n readonly organizationProfileName?: string | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface RegisterIdentityOptions {\n /**\n * Overrides the seeded personal-organization profile name. Optional; when\n * omitted the default personal-org name is used. The demo host passes each\n * pane's peer-labeled org name (\"Peer 1's Org\").\n */\n readonly organizationProfileName?: string | undefined;\n /**\n * Overrides the seeded self roster-profile nickname. Optional; when omitted\n * the default (\"You\") is used. The demo host passes each pane's peer-labeled\n * self name (\"Peer 1 (You)\").\n */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface UserSession {\n readonly createdAt: string;\n readonly id: string;\n readonly ipAddresses: string[];\n readonly isCurrent: boolean;\n readonly lastActiveAt: string;\n readonly lastActiveIp: string | null;\n readonly signingKeyFingerprint: string;\n}\n\nexport interface Session {\n readonly authToken: string | null;\n readonly containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n readonly defaultOrganizationId: string | null;\n readonly isAuthenticated: boolean;\n /**\n * Platform-operator flag reported by the server at login. It only decides\n * whether the root console is offered; the API enforces root access itself.\n */\n readonly isRoot: boolean;\n readonly organizationId: string | null;\n readonly snapshot: SessionSnapshot;\n /** Controls server replication without changing network connectivity. */\n readonly syncEnabled: boolean;\n readonly userId: string | null;\n /**\n * Whether `userId` was acknowledged by the server for the active signing\n * identity (a successful login or a fingerprint-bound host restore). A user\n * ID chosen locally through `setUserId` is not, and hosts must not persist\n * it as this identity's account.\n */\n readonly userIdAcknowledged: boolean;\n /** Stable predicate for this sign-in, including after verified renewal. */\n captureSignIn(purpose?: \"restore\"): () => boolean;\n bootstrapLocalRootContainer(isCurrent?: () => boolean): Promise<{\n containerId: string;\n created: boolean;\n }>;\n clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult>;\n createOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean>;\n destroySession(sessionId: string): Promise<boolean>;\n listSessions(): Promise<UserSession[]>;\n login(challengeHex?: string | undefined): Promise<boolean>;\n logout(): void;\n /** Runs host cleanup only after this invocation clears its own local session. */\n logoutRemote(\n onLocalLogout?: (current: () => boolean) => void | Promise<void>,\n ): Promise<boolean>;\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null>;\n recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null>;\n setAuthToken(authToken: string | null): void;\n setContainerId(containerId: string | null): void;\n /** A host restore supplying both isAuthenticated and its token begins a\n * sign-in. Partial view updates preserve it. User acknowledgments must match. */\n setContext(context: SessionContext): void;\n setOrganizationId(organizationId: string | null): void;\n setSyncEnabled(enabled: boolean): void;\n setUserId(userId: string | null): void;\n subscribe(listener: SessionListener): () => void;\n}\n"]}
|
|
@@ -6,11 +6,12 @@ export interface BlobByteSource {
|
|
|
6
6
|
}
|
|
7
7
|
export type BlobByteSourceInput = BlobBytes | BlobByteSource | Pick<Blob, "size" | "slice">;
|
|
8
8
|
export interface BlobStore {
|
|
9
|
-
|
|
9
|
+
/** Mutations check assertCurrent immediately before committing to storage. */
|
|
10
|
+
deleteBytes: (storageKey: string, assertCurrent?: () => void) => Promise<void>;
|
|
10
11
|
openByteSource: (storageKey: string) => Promise<BlobByteSource | null>;
|
|
11
12
|
readBytes: (storageKey: string) => Promise<BlobBytes | null>;
|
|
12
|
-
writeByteSource: (storageKey: string, source: BlobByteSource) => Promise<void>;
|
|
13
|
-
writeBytes: (storageKey: string, bytes: BlobBytes) => Promise<void>;
|
|
13
|
+
writeByteSource: (storageKey: string, source: BlobByteSource, assertCurrent?: () => void) => Promise<void>;
|
|
14
|
+
writeBytes: (storageKey: string, bytes: BlobBytes, assertCurrent?: () => void) => Promise<void>;
|
|
14
15
|
}
|
|
15
16
|
export declare function assertReadRange(sourceByteLength: number, offset: number, byteLength: number): void;
|
|
16
17
|
export declare function readExactBlobBytes(source: BlobByteSource, offset: number, byteLength: number): Promise<BlobBytes>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blobContracts.js","sourceRoot":"","sources":["blobContracts.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"blobContracts.js","sourceRoot":"","sources":["blobContracts.ts"],"names":[],"mappings":"AAiCA,MAAM,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,C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ose reads return exactly the requested range. */\nexport interface BlobByteSource {\n readonly byteLength: number;\n read(offset: number, byteLength: number): Promise<BlobBytes>;\n}\n\nexport type BlobByteSourceInput =\n | BlobBytes\n | BlobByteSource\n | Pick<Blob, \"size\" | \"slice\">;\n\nexport interface BlobStore {\n /** Mutations check assertCurrent immediately before committing to storage. */\n deleteBytes: (\n storageKey: string,\n assertCurrent?: () => void,\n ) => Promise<void>;\n openByteSource: (storageKey: string) => Promise<BlobByteSource | null>;\n readBytes: (storageKey: string) => Promise<BlobBytes | null>;\n writeByteSource: (\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) => Promise<void>;\n writeBytes: (\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ) => Promise<void>;\n}\n\nconst SOURCE_READ_CHUNK_SIZE = 5 * 1024 * 1024;\n\nfunction assertByteLength(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative safe integer.`);\n }\n}\n\nexport function assertReadRange(\n sourceByteLength: number,\n offset: number,\n byteLength: number,\n): void {\n assertByteLength(offset, \"Blob byte source read offset\");\n assertByteLength(byteLength, \"Blob byte source read length\");\n if (offset + byteLength > sourceByteLength) {\n throw new Error(\"Blob byte source read exceeds the source length.\");\n }\n}\n\nexport async function readExactBlobBytes(\n source: BlobByteSource,\n offset: number,\n byteLength: number,\n): Promise<BlobBytes> {\n const bytes = await source.read(offset, byteLength);\n if (bytes.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n return bytes;\n}\n\nfunction copyBlobBytes(bytes: Uint8Array): BlobBytes {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n}\n\nfunction isBlobByteSource(input: BlobByteSourceInput): input is BlobByteSource {\n return (\n !(input instanceof Uint8Array) &&\n \"byteLength\" in input &&\n typeof input.byteLength === \"number\" &&\n \"read\" in input &&\n typeof input.read === \"function\"\n );\n}\n\nexport function blobByteSourceInputLength(input: BlobByteSourceInput): number {\n const byteLength =\n isBlobByteSource(input) || input instanceof Uint8Array\n ? input.byteLength\n : input.size;\n assertByteLength(byteLength, \"Blob byte source length\");\n return byteLength;\n}\n\nexport function createBlobByteSource(\n input: BlobByteSourceInput,\n): BlobByteSource {\n if (isBlobByteSource(input)) {\n assertByteLength(input.byteLength, \"Blob byte source length\");\n return input;\n }\n\n if (input instanceof Uint8Array) {\n return {\n byteLength: input.byteLength,\n async read(offset, byteLength) {\n assertReadRange(input.byteLength, offset, byteLength);\n return copyBlobBytes(input.subarray(offset, offset + byteLength));\n },\n };\n }\n\n assertByteLength(input.size, \"Blob size\");\n return {\n byteLength: input.size,\n async read(offset, byteLength) {\n assertReadRange(input.size, offset, byteLength);\n const bytes = new Uint8Array(\n await input.slice(offset, offset + byteLength).arrayBuffer(),\n );\n if (bytes.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n return bytes;\n },\n };\n}\n\nexport async function readBlobByteSource(\n source: BlobByteSource,\n): Promise<BlobBytes> {\n assertByteLength(source.byteLength, \"Blob byte source length\");\n const bytes = new Uint8Array(source.byteLength);\n\n if (source.byteLength === 0) {\n const empty = await source.read(0, 0);\n if (empty.byteLength !== 0) {\n throw new Error(\"Blob byte source returned an invalid empty read.\");\n }\n return bytes;\n }\n\n for (let offset = 0; offset < source.byteLength; ) {\n const byteLength = Math.min(\n SOURCE_READ_CHUNK_SIZE,\n source.byteLength - offset,\n );\n const chunk = await source.read(offset, byteLength);\n if (chunk.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n bytes.set(chunk, offset);\n offset += byteLength;\n }\n\n return bytes;\n}\n"]}
|
|
@@ -1,17 +1,10 @@
|
|
|
1
1
|
import { createOpfsBlobStore, isOpfsBlobStoreSupported } from "./opfsBlobStore.js";
|
|
2
|
-
const opfsStoreByNamespace = new Map();
|
|
3
2
|
// namespace is a 64-character hex SHA-256 fingerprint of the
|
|
4
3
|
// signing public key bytes.
|
|
5
4
|
export function createBlobStore(namespace) {
|
|
6
5
|
if (!isOpfsBlobStoreSupported()) {
|
|
7
6
|
throw new Error("OPFS blob store is not supported.");
|
|
8
7
|
}
|
|
9
|
-
|
|
10
|
-
if (existingOpfsStore) {
|
|
11
|
-
return existingOpfsStore;
|
|
12
|
-
}
|
|
13
|
-
const nextOpfsStore = createOpfsBlobStore(namespace);
|
|
14
|
-
opfsStoreByNamespace.set(namespace, nextOpfsStore);
|
|
15
|
-
return nextOpfsStore;
|
|
8
|
+
return createOpfsBlobStore(namespace);
|
|
16
9
|
}
|
|
17
10
|
//# sourceMappingURL=createBlobStore.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createBlobStore.js","sourceRoot":"","sources":["createBlobStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEhF,
|
|
1
|
+
{"version":3,"file":"createBlobStore.js","sourceRoot":"","sources":["createBlobStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEhF,6DAA6D;AAC7D,4BAA4B;AAC5B,MAAM,UAAU,eAAe,CAAC,SAAiB;IAC/C,IAAI,CAAC,wBAAwB,EAAE,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IAED,OAAO,mBAAmB,CAAC,SAAS,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import type { BlobStore } from \"./blobContracts\";\nimport { createOpfsBlobStore, isOpfsBlobStoreSupported } from \"./opfsBlobStore\";\n\n// namespace is a 64-character hex SHA-256 fingerprint of the\n// signing public key bytes.\nexport function createBlobStore(namespace: string): BlobStore {\n if (!isOpfsBlobStoreSupported()) {\n throw new Error(\"OPFS blob store is not supported.\");\n }\n\n return createOpfsBlobStore(namespace);\n}\n"]}
|
|
@@ -61,8 +61,9 @@ class EncryptedBlobStore {
|
|
|
61
61
|
}
|
|
62
62
|
this.rawKeyPromise = importRawAesKey(options.key);
|
|
63
63
|
}
|
|
64
|
-
async deleteBytes(storageKey) {
|
|
65
|
-
|
|
64
|
+
async deleteBytes(storageKey, assertCurrent) {
|
|
65
|
+
assertCurrent?.();
|
|
66
|
+
await this.innerStore.deleteBytes(storageKey, assertCurrent);
|
|
66
67
|
}
|
|
67
68
|
async openByteSource(storageKey) {
|
|
68
69
|
const encryptedSource = await this.innerStore.openByteSource(storageKey);
|
|
@@ -85,7 +86,7 @@ class EncryptedBlobStore {
|
|
|
85
86
|
const source = await this.openByteSource(storageKey);
|
|
86
87
|
return source ? readBlobByteSource(source) : null;
|
|
87
88
|
}
|
|
88
|
-
async writeByteSource(storageKey, source) {
|
|
89
|
+
async writeByteSource(storageKey, source, assertCurrent) {
|
|
89
90
|
const keyDerivation = this.createKeyDerivationEnvelope();
|
|
90
91
|
const key = await this.getCipherKey(keyDerivation);
|
|
91
92
|
const iv = createAesGcmIv();
|
|
@@ -100,6 +101,7 @@ class EncryptedBlobStore {
|
|
|
100
101
|
version: ENCRYPTED_BLOB_STORE_VERSION,
|
|
101
102
|
};
|
|
102
103
|
const { headerBytes, prefixBytes } = serializeEncryptedBlobEnvelope(envelope);
|
|
104
|
+
assertCurrent?.();
|
|
103
105
|
await this.innerStore.writeByteSource(storageKey, createEncryptedBlobByteSource({
|
|
104
106
|
envelope,
|
|
105
107
|
headerBytes,
|
|
@@ -109,10 +111,10 @@ class EncryptedBlobStore {
|
|
|
109
111
|
plaintextSource: source,
|
|
110
112
|
prefixBytes,
|
|
111
113
|
storageKey,
|
|
112
|
-
}));
|
|
114
|
+
}), assertCurrent);
|
|
113
115
|
}
|
|
114
|
-
async writeBytes(storageKey, bytes) {
|
|
115
|
-
await this.writeByteSource(storageKey, createBlobByteSource(bytes));
|
|
116
|
+
async writeBytes(storageKey, bytes, assertCurrent) {
|
|
117
|
+
await this.writeByteSource(storageKey, createBlobByteSource(bytes), assertCurrent);
|
|
116
118
|
}
|
|
117
119
|
createKeyDerivationEnvelope() {
|
|
118
120
|
if (!this.passphraseMaterialPromise) {
|
|
@@ -191,9 +193,10 @@ export function createLazyEncryptedBlobStore(namespace, keyProvider) {
|
|
|
191
193
|
return innerStorePromise;
|
|
192
194
|
}
|
|
193
195
|
return {
|
|
194
|
-
deleteBytes: async (storageKey) => {
|
|
196
|
+
deleteBytes: async (storageKey, assertCurrent) => {
|
|
195
197
|
const store = await getStore();
|
|
196
|
-
|
|
198
|
+
assertCurrent?.();
|
|
199
|
+
return store.deleteBytes(storageKey, assertCurrent);
|
|
197
200
|
},
|
|
198
201
|
openByteSource: async (storageKey) => {
|
|
199
202
|
const store = await getStore();
|
|
@@ -203,13 +206,15 @@ export function createLazyEncryptedBlobStore(namespace, keyProvider) {
|
|
|
203
206
|
const store = await getStore();
|
|
204
207
|
return store.readBytes(storageKey);
|
|
205
208
|
},
|
|
206
|
-
writeByteSource: async (storageKey, source) => {
|
|
209
|
+
writeByteSource: async (storageKey, source, assertCurrent) => {
|
|
207
210
|
const store = await getStore();
|
|
208
|
-
|
|
211
|
+
assertCurrent?.();
|
|
212
|
+
return store.writeByteSource(storageKey, source, assertCurrent);
|
|
209
213
|
},
|
|
210
|
-
writeBytes: async (storageKey, bytes) => {
|
|
214
|
+
writeBytes: async (storageKey, bytes, assertCurrent) => {
|
|
211
215
|
const store = await getStore();
|
|
212
|
-
|
|
216
|
+
assertCurrent?.();
|
|
217
|
+
return store.writeBytes(storageKey, bytes, assertCurrent);
|
|
213
218
|
},
|
|
214
219
|
};
|
|
215
220
|
}
|