@tearleads/client-sdk 0.1.45 → 0.1.47
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/client/Tearleads.js +3 -0
- package/client/Tearleads.js.map +1 -1
- package/client/userIdentities.d.ts +11 -1
- package/client/userIdentities.js +26 -8
- package/client/userIdentities.js.map +1 -1
- package/client/workflowRuntime.d.ts +2 -1
- package/client/workflowRuntime.js +1 -0
- package/client/workflowRuntime.js.map +1 -1
- package/data/trustedUserIdentity/identityLink.d.ts +12 -0
- package/data/trustedUserIdentity/identityLink.js +117 -0
- package/data/trustedUserIdentity/identityLink.js.map +1 -0
- package/data/trustedUserIdentity/index.d.ts +2 -1
- package/data/trustedUserIdentity/index.js +1 -0
- package/data/trustedUserIdentity/index.js.map +1 -1
- package/data/trustedUserIdentity/service.js +48 -2
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/data/trustedUserIdentity/types.d.ts +3 -0
- package/data/trustedUserIdentity/types.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +0 -1
- package/internal/validators/operation/organizationBilling.d.ts +0 -4
- package/internal/validators/response/organizationBillingManagementUrl.d.ts +0 -4
- package/internal/validators/response/organizationBillingManagementUrl.js +0 -2
- package/internal/validators/response/organizationBillingManagementUrl.js.map +1 -1
- package/package.json +1 -1
- package/workflows/organizations/policyHistoryReadModel.js +14 -5
- package/workflows/organizations/policyHistoryReadModel.js.map +1 -1
- package/workflows/organizations/policyHistoryTypes.d.ts +4 -3
- package/workflows/organizations/policyHistoryTypes.js.map +1 -1
package/client/Tearleads.js
CHANGED
|
@@ -122,6 +122,9 @@ export class Tearleads {
|
|
|
122
122
|
this.organizations = createOrganizations(runtime, this.containerContents);
|
|
123
123
|
this.root = createRoot(rootRuntimeOf(runtime, this.session));
|
|
124
124
|
this.userIdentities = createUserIdentities({
|
|
125
|
+
getOrganizationId: () => this.session.organizationId,
|
|
126
|
+
reportSecurityIncident: security.service.report,
|
|
127
|
+
identityLinks: runtime.identityLinks,
|
|
125
128
|
log: this.log,
|
|
126
129
|
resolveTrustedUserIdentity: (userId) => runtime.workflowInput().resolveTrustedUserIdentity(userId),
|
|
127
130
|
});
|
package/client/Tearleads.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAErE,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AAExG,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,cAAc,GAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAsB,MAAM,iBAAiB,CAAC;AAE1E,OAAO,EAAE,UAAU,EAAa,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC9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gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient, ApiRequestMetrics } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport { createVerifiedManifestCitations } from \"../data/persistence/verifiedManifestBundlePersistence\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport type { PrincipalHistoryKeyProvider } from \"./principalHistoryProtection\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n /** Reuse a memory-only request counter across client lifetimes. */\n apiRequestMetrics?: ApiRequestMetrics | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /** Private host key for durable history progress; omitted uses disposable session keys. */\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n /** Compound policy dispatch/recovery deadline in milliseconds; defaults to 60 seconds. */\n principalMutationTimeoutMs?: number | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database or signing identity changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n private expiredSessionLoginPromise: Promise<boolean> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedPrincipalHistory: InternalRuntime[\"primeProvisionedPrincipalHistory\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = this.createClientSession(options, security.service.report);\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): Session {\n return createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n primeProvisionedPrincipalHistory: (input) =>\n this.primeProvisionedPrincipalHistory(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(apiBaseUrl: string): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.primeProvisionedPrincipalHistory =\n runtime.primeProvisionedPrincipalHistory;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already verified.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(() => this.database.execSql),\n );\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n // The API client replays requests the expired session sent, so a login is\n // their renewal only when the loaded keys authenticate that known user.\n const expiredUserId = this.session.userId;\n this.expiredSessionLoginPromise ??= this.session\n .login()\n .then(\n (renewed) =>\n renewed &&\n expiredUserId !== null &&\n this.session.userId === expiredUserId,\n )\n .finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAErE,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AAExG,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,cAAc,GAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAsB,MAAM,iBAAiB,CAAC;AAE1E,OAAO,EAAE,UAAU,EAAa,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EACL,6BAA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BAAuB,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC;gBACjE,wBAAwB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient, ApiRequestMetrics } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport { createVerifiedManifestCitations } from \"../data/persistence/verifiedManifestBundlePersistence\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport type { PrincipalHistoryKeyProvider } from \"./principalHistoryProtection\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n /** Reuse a memory-only request counter across client lifetimes. */\n apiRequestMetrics?: ApiRequestMetrics | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /** Private host key for durable history progress; omitted uses disposable session keys. */\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n /** Compound policy dispatch/recovery deadline in milliseconds; defaults to 60 seconds. */\n principalMutationTimeoutMs?: number | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database or signing identity changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n private expiredSessionLoginPromise: Promise<boolean> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedPrincipalHistory: InternalRuntime[\"primeProvisionedPrincipalHistory\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = this.createClientSession(options, security.service.report);\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n getOrganizationId: () => this.session.organizationId,\n reportSecurityIncident: security.service.report,\n identityLinks: runtime.identityLinks,\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): Session {\n return createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n primeProvisionedPrincipalHistory: (input) =>\n this.primeProvisionedPrincipalHistory(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(apiBaseUrl: string): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.primeProvisionedPrincipalHistory =\n runtime.primeProvisionedPrincipalHistory;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already verified.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(() => this.database.execSql),\n );\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n // The API client replays requests the expired session sent, so a login is\n // their renewal only when the loaded keys authenticate that known user.\n const expiredUserId = this.session.userId;\n this.expiredSessionLoginPromise ??= this.session\n .login()\n .then(\n (renewed) =>\n renewed &&\n expiredUserId !== null &&\n this.session.userId === expiredUserId,\n )\n .finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { SecurityIncidentReporter } from "../data/securityIncidents.js";
|
|
2
|
+
import { type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../data/trustedUserIdentity/index.js";
|
|
2
3
|
export interface ResolvedUserIdentity {
|
|
3
4
|
encapsulationKeyFingerprint: string;
|
|
4
5
|
encapsulationPublicKey: string;
|
|
@@ -7,10 +8,19 @@ export interface ResolvedUserIdentity {
|
|
|
7
8
|
userId: string;
|
|
8
9
|
}
|
|
9
10
|
export interface UserIdentities {
|
|
11
|
+
/** Share a stable link derived exclusively from this user's local keys. */
|
|
12
|
+
createLink(appUrl: string): Promise<string>;
|
|
13
|
+
/** Compare an independently received link before durably pinning either key. */
|
|
14
|
+
verifyLink(link: string): Promise<ResolvedUserIdentity>;
|
|
15
|
+
/** Read an existing durable pin without fetching or trusting a new identity. */
|
|
16
|
+
resolvePinned(userId: string): Promise<ResolvedUserIdentity | null>;
|
|
10
17
|
/** `null` when the user is unknown or currently unresolvable; integrity failures throw. */
|
|
11
18
|
resolve(userId: string): Promise<ResolvedUserIdentity | null>;
|
|
12
19
|
}
|
|
13
20
|
export declare function createUserIdentities(input: {
|
|
21
|
+
getOrganizationId: () => string | null;
|
|
22
|
+
reportSecurityIncident: SecurityIncidentReporter;
|
|
23
|
+
identityLinks: Pick<TrustedUserIdentityService, "createLink" | "verifyLink" | "resolvePinned">;
|
|
14
24
|
log: (message: string) => void;
|
|
15
25
|
resolveTrustedUserIdentity: TrustedUserIdentityResolver;
|
|
16
26
|
}): UserIdentities;
|
package/client/userIdentities.js
CHANGED
|
@@ -1,9 +1,33 @@
|
|
|
1
1
|
import { bytesToBase64 } from "../internal/encoding/index.js";
|
|
2
2
|
import { ProjectionDependencyUnavailableError } from "../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
|
-
import {
|
|
3
|
+
import { runWithSecurityIncidentReporting } from "../data/keyingProjectionVerification/error.js";
|
|
4
|
+
import { parseIdentityLink, requireTrustedUserIdentityResolver, } from "../data/trustedUserIdentity/index.js";
|
|
5
|
+
function toResolvedIdentity(identity) {
|
|
6
|
+
return {
|
|
7
|
+
encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,
|
|
8
|
+
encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),
|
|
9
|
+
signingKeyFingerprint: identity.signingKeyFingerprint,
|
|
10
|
+
signingPublicKey: bytesToBase64(identity.signingPublicKey),
|
|
11
|
+
userId: identity.userId,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
4
14
|
export function createUserIdentities(input) {
|
|
5
15
|
const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity);
|
|
6
16
|
return {
|
|
17
|
+
createLink: (appUrl) => input.identityLinks.createLink(appUrl),
|
|
18
|
+
async verifyLink(link) {
|
|
19
|
+
const { userId } = parseIdentityLink(link);
|
|
20
|
+
return runWithSecurityIncidentReporting(input.reportSecurityIncident, {
|
|
21
|
+
objectId: userId,
|
|
22
|
+
objectKind: "user",
|
|
23
|
+
operation: "user.identity.verify_link",
|
|
24
|
+
organizationId: input.getOrganizationId(),
|
|
25
|
+
}, async () => toResolvedIdentity(await input.identityLinks.verifyLink(link)));
|
|
26
|
+
},
|
|
27
|
+
async resolvePinned(userId) {
|
|
28
|
+
const identity = await input.identityLinks.resolvePinned(userId);
|
|
29
|
+
return identity ? toResolvedIdentity(identity) : null;
|
|
30
|
+
},
|
|
7
31
|
async resolve(userId) {
|
|
8
32
|
input.log(`Loading user identity for userId: ${userId}`);
|
|
9
33
|
let identity;
|
|
@@ -19,13 +43,7 @@ export function createUserIdentities(input) {
|
|
|
19
43
|
if (!identity) {
|
|
20
44
|
return null;
|
|
21
45
|
}
|
|
22
|
-
return
|
|
23
|
-
encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,
|
|
24
|
-
encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),
|
|
25
|
-
signingKeyFingerprint: identity.signingKeyFingerprint,
|
|
26
|
-
signingPublicKey: bytesToBase64(identity.signingPublicKey),
|
|
27
|
-
userId: identity.userId,
|
|
28
|
-
};
|
|
46
|
+
return toResolvedIdentity(identity);
|
|
29
47
|
},
|
|
30
48
|
};
|
|
31
49
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"userIdentities.js","sourceRoot":"","sources":["userIdentities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,oCAAoC,EAAE,MAAM,4DAA4D,CAAC;AAClH,OAAO,EACL,kCAAkC,
|
|
1
|
+
{"version":3,"file":"userIdentities.js","sourceRoot":"","sources":["userIdentities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,oCAAoC,EAAE,MAAM,4DAA4D,CAAC;AAClH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAE9F,OAAO,EACL,iBAAiB,EACjB,kCAAkC,GAInC,MAAM,6BAA6B,CAAC;AAqBrC,SAAS,kBAAkB,CACzB,QAA6B;IAE7B,OAAO;QACL,2BAA2B,EAAE,QAAQ,CAAC,2BAA2B;QACjE,sBAAsB,EAAE,aAAa,CAAC,QAAQ,CAAC,s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,CAAC;YACtD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;oBAC1D,MAAM,KAAK,CAAC;gBACd,KAAK,CAAC,GAAG,CACP,qBAAqB,MAAM,oBAAoB,KAAK,CAAC,OAAO,EAAE,CAC/D,CAAC;gBACF,OAAO,IAAI,CAAC;YACd,CAAC;YACD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACtC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { ProjectionDependencyUnavailableError } from \"../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport {\n parseIdentityLink,\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../data/trustedUserIdentity\";\n\nexport interface ResolvedUserIdentity {\n encapsulationKeyFingerprint: string;\n encapsulationPublicKey: string;\n signingKeyFingerprint: string;\n signingPublicKey: string;\n userId: string;\n}\n\nexport interface UserIdentities {\n /** Share a stable link derived exclusively from this user's local keys. */\n createLink(appUrl: string): Promise<string>;\n /** Compare an independently received link before durably pinning either key. */\n verifyLink(link: string): Promise<ResolvedUserIdentity>;\n /** Read an existing durable pin without fetching or trusting a new identity. */\n resolvePinned(userId: string): Promise<ResolvedUserIdentity | null>;\n /** `null` when the user is unknown or currently unresolvable; integrity failures throw. */\n resolve(userId: string): Promise<ResolvedUserIdentity | null>;\n}\n\nfunction toResolvedIdentity(\n identity: TrustedUserIdentity,\n): ResolvedUserIdentity {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n userId: identity.userId,\n };\n}\n\nexport function createUserIdentities(input: {\n getOrganizationId: () => string | null;\n reportSecurityIncident: SecurityIncidentReporter;\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n log: (message: string) => void;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}): UserIdentities {\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n return {\n createLink: (appUrl) => input.identityLinks.createLink(appUrl),\n async verifyLink(link) {\n const { userId } = parseIdentityLink(link);\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.verify_link\",\n organizationId: input.getOrganizationId(),\n },\n async () =>\n toResolvedIdentity(await input.identityLinks.verifyLink(link)),\n );\n },\n async resolvePinned(userId) {\n const identity = await input.identityLinks.resolvePinned(userId);\n return identity ? toResolvedIdentity(identity) : null;\n },\n async resolve(userId) {\n input.log(`Loading user identity for userId: ${userId}`);\n let identity: Awaited<ReturnType<TrustedUserIdentityResolver>>;\n try {\n identity = await resolveTrustedUserIdentity(userId);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError))\n throw error;\n input.log(\n `User identity for ${userId} is unavailable: ${error.message}`,\n );\n return null;\n }\n if (!identity) {\n return null;\n }\n\n return toResolvedIdentity(identity);\n },\n };\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import type { DocumentProjectorRegistry } from "../data/documents/documentKinds.
|
|
|
3
3
|
import type { DomainScope } from "../data/domainScope.js";
|
|
4
4
|
import type { PrincipalHistoryProtectionLease } from "../data/principals/principalHistoryProtection.js";
|
|
5
5
|
import type { SecurityIncidentReporter } from "../data/securityIncidents.js";
|
|
6
|
-
import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver } from "../data/trustedUserIdentity/index.js";
|
|
6
|
+
import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../data/trustedUserIdentity/index.js";
|
|
7
7
|
import type { ContainerContentsRootAdopter } from "../workflows/container-contents/runtime.js";
|
|
8
8
|
import { type ProvisionedPrincipalHistoryPrimer } from "../workflows/registration/provisionedPrincipalHistory.js";
|
|
9
9
|
import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../workflows/runtimeInput.js";
|
|
@@ -32,6 +32,7 @@ export interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {
|
|
|
32
32
|
readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
|
|
33
33
|
}
|
|
34
34
|
export interface InternalRuntime {
|
|
35
|
+
identityLinks: Pick<TrustedUserIdentityService, "createLink" | "verifyLink" | "resolvePinned">;
|
|
35
36
|
retirePrincipalHistoryProtection(): void;
|
|
36
37
|
readonly sessionGeneration: number;
|
|
37
38
|
readonly adoptRootContainer: ContainerContentsRootAdopter;
|
|
@@ -97,6 +97,7 @@ export function createRuntime(dependencies) {
|
|
|
97
97
|
});
|
|
98
98
|
const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration).bind);
|
|
99
99
|
return {
|
|
100
|
+
identityLinks: trustedUserIdentityService,
|
|
100
101
|
retirePrincipalHistoryProtection: historyProtection.retire,
|
|
101
102
|
get sessionGeneration() {
|
|
102
103
|
return runtimeSubscription.sessionGeneration;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAG9F,OAAO,EAAgB,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC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,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAG9F,OAAO,EAAgB,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,uCAAuC,GAExC,MAAM,uDAAuD,CAAC;AAa/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAsEzE,SAAS,wBAAwB,CAC/B,YAAyC,EACzC,cAA4B;IAE5B,OAAO,iCAAiC,CAAC;QACvC,GAAG,EAAE,YAAY,CAAC,GAAG;QACrB,0BAA0B,EAAE,YAAY,CAAC,0BAA0B;QACnE,SAAS,EAAE,GAAG,EAAE;YAC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O,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ValidatedUserIdentityCandidate } from "./types.js";
|
|
2
|
+
interface IdentityLinkExpectation {
|
|
3
|
+
readonly identityTrustDomain: string;
|
|
4
|
+
readonly userId: string;
|
|
5
|
+
readonly fingerprint: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function parseIdentityLink(value: string): IdentityLinkExpectation;
|
|
8
|
+
/** Versioned, domain-separated tuple: exact keys, algorithms and account scope. */
|
|
9
|
+
export declare function identityLinkFingerprint(identity: ValidatedUserIdentityCandidate): Promise<string>;
|
|
10
|
+
export declare function createIdentityLink(identity: ValidatedUserIdentityCandidate, appUrl: string): Promise<string>;
|
|
11
|
+
export declare function assertIdentityLinkMatches(expectation: IdentityLinkExpectation, identity: ValidatedUserIdentityCandidate): Promise<void>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { toFingerprint } from "../../internal/crypto/index.js";
|
|
2
|
+
import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
|
|
3
|
+
import { resolveIdentityTrustDomain } from "./trustDomain.js";
|
|
4
|
+
import { TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "./types.js";
|
|
5
|
+
import { assertTrustedUserIdentityUserId } from "./validation.js";
|
|
6
|
+
const LINK_PATH = "/app/contacts/import/";
|
|
7
|
+
/** A supplied link alone cannot establish evidence of server tampering. */
|
|
8
|
+
class IdentityLinkMismatchError extends Error {
|
|
9
|
+
constructor() {
|
|
10
|
+
super("The identity keys do not match this link. Ask the person to confirm their identity link through your trusted channel.");
|
|
11
|
+
this.name = "IdentityLinkMismatchError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function invalidLink() {
|
|
15
|
+
throw new Error("Enter a complete Tearleads identity link.");
|
|
16
|
+
}
|
|
17
|
+
function httpUrl(value) {
|
|
18
|
+
let url;
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(value);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return invalidLink();
|
|
24
|
+
}
|
|
25
|
+
if (!["https:", "http:"].includes(url.protocol) ||
|
|
26
|
+
url.username ||
|
|
27
|
+
url.password)
|
|
28
|
+
return invalidLink();
|
|
29
|
+
return url;
|
|
30
|
+
}
|
|
31
|
+
function encodeExpectation(expectation) {
|
|
32
|
+
return bytesToBase64(new TextEncoder().encode(JSON.stringify([
|
|
33
|
+
1,
|
|
34
|
+
expectation.identityTrustDomain,
|
|
35
|
+
expectation.userId,
|
|
36
|
+
expectation.fingerprint,
|
|
37
|
+
])))
|
|
38
|
+
.replaceAll("+", "-")
|
|
39
|
+
.replaceAll("/", "_")
|
|
40
|
+
.replace(/=+$/u, "");
|
|
41
|
+
}
|
|
42
|
+
export function parseIdentityLink(value) {
|
|
43
|
+
if (value.length > 4096)
|
|
44
|
+
return invalidLink();
|
|
45
|
+
const url = httpUrl(value.trim());
|
|
46
|
+
if (url.search || url.hash || !url.pathname.startsWith(LINK_PATH)) {
|
|
47
|
+
return invalidLink();
|
|
48
|
+
}
|
|
49
|
+
const token = url.pathname.slice(LINK_PATH.length);
|
|
50
|
+
if (!/^[A-Za-z0-9_-]+$/u.test(token))
|
|
51
|
+
return invalidLink();
|
|
52
|
+
let payload;
|
|
53
|
+
try {
|
|
54
|
+
const base64 = token.replaceAll("-", "+").replaceAll("_", "/");
|
|
55
|
+
payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64ToBytes(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="))));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return invalidLink();
|
|
59
|
+
}
|
|
60
|
+
if (!Array.isArray(payload) ||
|
|
61
|
+
payload.length !== 4 ||
|
|
62
|
+
payload[0] !== 1 ||
|
|
63
|
+
typeof payload[1] !== "string" ||
|
|
64
|
+
typeof payload[2] !== "string" ||
|
|
65
|
+
typeof payload[3] !== "string" ||
|
|
66
|
+
!/^[a-f0-9]{64}$/u.test(payload[3]))
|
|
67
|
+
return invalidLink();
|
|
68
|
+
const expectation = {
|
|
69
|
+
identityTrustDomain: payload[1],
|
|
70
|
+
userId: payload[2],
|
|
71
|
+
fingerprint: payload[3],
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
assertTrustedUserIdentityUserId(expectation.userId);
|
|
75
|
+
if (resolveIdentityTrustDomain({
|
|
76
|
+
apiBaseUrl: expectation.identityTrustDomain,
|
|
77
|
+
}) !== expectation.identityTrustDomain)
|
|
78
|
+
return invalidLink();
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return invalidLink();
|
|
82
|
+
}
|
|
83
|
+
if (encodeExpectation(expectation) !== token)
|
|
84
|
+
return invalidLink();
|
|
85
|
+
return expectation;
|
|
86
|
+
}
|
|
87
|
+
/** Versioned, domain-separated tuple: exact keys, algorithms and account scope. */
|
|
88
|
+
export function identityLinkFingerprint(identity) {
|
|
89
|
+
return toFingerprint(new TextEncoder().encode(JSON.stringify([
|
|
90
|
+
"tearleads.identity-link.v1",
|
|
91
|
+
identity.identityTrustDomain,
|
|
92
|
+
identity.userId,
|
|
93
|
+
TRUSTED_USER_IDENTITY_SIGNING_SUITE,
|
|
94
|
+
bytesToBase64(identity.signingPublicKey),
|
|
95
|
+
TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,
|
|
96
|
+
bytesToBase64(identity.encapsulationPublicKey),
|
|
97
|
+
])));
|
|
98
|
+
}
|
|
99
|
+
export async function createIdentityLink(identity, appUrl) {
|
|
100
|
+
const url = httpUrl(appUrl);
|
|
101
|
+
url.pathname =
|
|
102
|
+
LINK_PATH +
|
|
103
|
+
encodeExpectation({
|
|
104
|
+
identityTrustDomain: identity.identityTrustDomain,
|
|
105
|
+
userId: identity.userId,
|
|
106
|
+
fingerprint: await identityLinkFingerprint(identity),
|
|
107
|
+
});
|
|
108
|
+
url.search = "";
|
|
109
|
+
url.hash = "";
|
|
110
|
+
return url.href;
|
|
111
|
+
}
|
|
112
|
+
export async function assertIdentityLinkMatches(expectation, identity) {
|
|
113
|
+
if ((await identityLinkFingerprint(identity)) !== expectation.fingerprint) {
|
|
114
|
+
throw new IdentityLinkMismatchError();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=identityLink.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identityLink.js","sourceRoot":"","sources":["identityLink.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EACL,yCAAyC,EACzC,mCAAmC,GAEpC,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,+BAA+B,EAAE,MAAM,cAAc,CAAC;AAE/D,MAAM,SAAS,GAAG,uBAAuB,CAAC;AAE1C,2EAA2E;AAC3E,MAAM,yBAA0B,SAAQ,KAAK;IAC3C;QACE,KAAK,CACH,uHAAuH,CACxH,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;IAC1C,CAAC;CACF;AAQD,SAAS,WAAW;IAClB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,OAAO,CAAC,KAAa;IAC5B,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,WAAW,EAAE,CAAC;IACvB,CAAC;IACD,IACE,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC3C,GAAG,CAAC,QAAQ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,UAAU,uBAAuB,CACrC,QAAwC;IAExC,OAAO,aAAa,CAClB,IAAI,WAAW,EAAE,CAAC,MAAM,CACtB,IAAI,CAAC,SAAS,CAAC;QACb,4BAA4B;QAC5B,QAAQ,CAAC,mBAAmB;QAC5B,QAAQ,CAAC,MAAM;QACf,mCAAmC;QACnC,aAAa,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QACxC,yCAAyC;QACzC,aAAa,CAAC,QAAQ,CAAC,sBAAsB,CAAC;KAC/C,CAAC,CACH,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,QAAwC,EACxC,MAAc;IAEd,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5B,GAAG,CAAC,QAAQ;QACV,SAAS;YACT,iBAAiB,CAAC;gBAChB,mBAAmB,EAAE,QAAQ,CAAC,mBAAmB;gBACjD,MAAM,EAAE,QAAQ,CAAC,MAAM;gBACvB,WAAW,EAAE,MAAM,uBAAuB,CAAC,QAAQ,CAAC;aACrD,CAAC,CAAC;IACL,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;IAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;IACd,OAAO,GAAG,CAAC,IAAI,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,WAAoC,EACpC,QAAwC;IAExC,IAAI,CAAC,MAAM,uBAAuB,CAAC,QAAQ,CAAC,CAAC,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;QAC1E,MAAM,IAAI,yBAAyB,EAAE,CAAC;IACxC,CAAC;AACH,CAAC","sourcesContent":["import { toFingerprint } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { resolveIdentityTrustDomain } from \"./trustDomain\";\nimport {\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport { assertTrustedUserIdentityUserId } from \"./validation\";\n\nconst LINK_PATH = \"/app/contacts/import/\";\n\n/** A supplied link alone cannot establish evidence of server tampering. */\nclass IdentityLinkMismatchError extends Error {\n constructor() {\n super(\n \"The identity keys do not match this link. Ask the person to confirm their identity link through your trusted channel.\",\n );\n this.name = \"IdentityLinkMismatchError\";\n }\n}\n\ninterface IdentityLinkExpectation {\n readonly identityTrustDomain: string;\n readonly userId: string;\n readonly fingerprint: string;\n}\n\nfunction invalidLink(): never {\n throw new Error(\"Enter a complete Tearleads identity link.\");\n}\n\nfunction httpUrl(value: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return invalidLink();\n }\n if (\n ![\"https:\", \"http:\"].includes(url.protocol) ||\n url.username ||\n url.password\n )\n return invalidLink();\n return url;\n}\n\nfunction encodeExpectation(expectation: IdentityLinkExpectation): string {\n return bytesToBase64(\n new TextEncoder().encode(\n JSON.stringify([\n 1,\n expectation.identityTrustDomain,\n expectation.userId,\n expectation.fingerprint,\n ]),\n ),\n )\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replace(/=+$/u, \"\");\n}\n\nexport function parseIdentityLink(value: string): IdentityLinkExpectation {\n if (value.length > 4096) return invalidLink();\n const url = httpUrl(value.trim());\n if (url.search || url.hash || !url.pathname.startsWith(LINK_PATH)) {\n return invalidLink();\n }\n const token = url.pathname.slice(LINK_PATH.length);\n if (!/^[A-Za-z0-9_-]+$/u.test(token)) return invalidLink();\n let payload: unknown;\n try {\n const base64 = token.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n payload = JSON.parse(\n new TextDecoder(\"utf-8\", { fatal: true }).decode(\n base64ToBytes(base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\")),\n ),\n );\n } catch {\n return invalidLink();\n }\n if (\n !Array.isArray(payload) ||\n payload.length !== 4 ||\n payload[0] !== 1 ||\n typeof payload[1] !== \"string\" ||\n typeof payload[2] !== \"string\" ||\n typeof payload[3] !== \"string\" ||\n !/^[a-f0-9]{64}$/u.test(payload[3])\n )\n return invalidLink();\n const expectation = {\n identityTrustDomain: payload[1],\n userId: payload[2],\n fingerprint: payload[3],\n };\n try {\n assertTrustedUserIdentityUserId(expectation.userId);\n if (\n resolveIdentityTrustDomain({\n apiBaseUrl: expectation.identityTrustDomain,\n }) !== expectation.identityTrustDomain\n )\n return invalidLink();\n } catch {\n return invalidLink();\n }\n if (encodeExpectation(expectation) !== token) return invalidLink();\n return expectation;\n}\n\n/** Versioned, domain-separated tuple: exact keys, algorithms and account scope. */\nexport function identityLinkFingerprint(\n identity: ValidatedUserIdentityCandidate,\n): Promise<string> {\n return toFingerprint(\n new TextEncoder().encode(\n JSON.stringify([\n \"tearleads.identity-link.v1\",\n identity.identityTrustDomain,\n identity.userId,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n bytesToBase64(identity.signingPublicKey),\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n bytesToBase64(identity.encapsulationPublicKey),\n ]),\n ),\n );\n}\n\nexport async function createIdentityLink(\n identity: ValidatedUserIdentityCandidate,\n appUrl: string,\n): Promise<string> {\n const url = httpUrl(appUrl);\n url.pathname =\n LINK_PATH +\n encodeExpectation({\n identityTrustDomain: identity.identityTrustDomain,\n userId: identity.userId,\n fingerprint: await identityLinkFingerprint(identity),\n });\n url.search = \"\";\n url.hash = \"\";\n return url.href;\n}\n\nexport async function assertIdentityLinkMatches(\n expectation: IdentityLinkExpectation,\n identity: ValidatedUserIdentityCandidate,\n): Promise<void> {\n if ((await identityLinkFingerprint(identity)) !== expectation.fingerprint) {\n throw new IdentityLinkMismatchError();\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { createApiUserIdentitySource } from "./apiAdapter.js";
|
|
2
|
+
export { parseIdentityLink } from "./identityLink.js";
|
|
2
3
|
export { requireTrustedUserIdentityResolver } from "./requiredResolver.js";
|
|
3
4
|
export { createTrustedUserIdentityService, loadPinnedUserIdentity, } from "./service.js";
|
|
4
5
|
export { resolveIdentityTrustDomain } from "./trustDomain.js";
|
|
5
|
-
export type { LocalUserIdentityCandidate, TrustedUserIdentity, TrustedUserIdentityResolver, } from "./types.js";
|
|
6
|
+
export type { LocalUserIdentityCandidate, TrustedUserIdentity, TrustedUserIdentityResolver, TrustedUserIdentityService, } from "./types.js";
|
|
6
7
|
export { validateUserIdentityKeys } from "./validation.js";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createApiUserIdentitySource } from "./apiAdapter.js";
|
|
2
|
+
export { parseIdentityLink } from "./identityLink.js";
|
|
2
3
|
export { requireTrustedUserIdentityResolver } from "./requiredResolver.js";
|
|
3
4
|
export { createTrustedUserIdentityService, loadPinnedUserIdentity, } from "./service.js";
|
|
4
5
|
export { resolveIdentityTrustDomain } from "./trustDomain.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAO3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { createApiUserIdentitySource } from \"./apiAdapter\";\nexport { parseIdentityLink } from \"./identityLink\";\nexport { requireTrustedUserIdentityResolver } from \"./requiredResolver\";\nexport {\n createTrustedUserIdentityService,\n loadPinnedUserIdentity,\n} from \"./service\";\nexport { resolveIdentityTrustDomain } from \"./trustDomain\";\nexport type {\n LocalUserIdentityCandidate,\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n TrustedUserIdentityService,\n} from \"./types\";\nexport { validateUserIdentityKeys } from \"./validation\";\n"]}
|
|
@@ -3,13 +3,18 @@ import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
|
|
|
3
3
|
import { compareOrInsertTrustedUserIdentityPin, loadTrustedUserIdentityPin, loadTrustedUserIdForSigningKey, TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/trustedUserIdentityPinPersistence.js";
|
|
4
4
|
import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
|
|
5
5
|
import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
|
|
6
|
+
import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
|
|
6
7
|
import { brandTrustedUserIdentity, TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "./types.js";
|
|
7
8
|
import { assertTrustedUserIdentityUserId, validateLocalUserIdentity, validateRemoteUserIdentity, validateUserIdentityKeys, } from "./validation.js";
|
|
8
|
-
function
|
|
9
|
+
function requireTrustDomain(dependencies) {
|
|
9
10
|
// A missing trust domain is a static misconfiguration and must stay loud.
|
|
10
11
|
if (!dependencies.identityTrustDomain) {
|
|
11
12
|
throw new KeyingVerificationError("missing_dependency", "Trusted user identity resolution requires a stable API trust domain");
|
|
12
13
|
}
|
|
14
|
+
return dependencies.identityTrustDomain;
|
|
15
|
+
}
|
|
16
|
+
function requireTrustStore(dependencies) {
|
|
17
|
+
const identityTrustDomain = requireTrustDomain(dependencies);
|
|
13
18
|
// An absent trust store is not: getExecSql() returns null exactly while the
|
|
14
19
|
// database is not ready, which happens routinely when the runtime is swapped
|
|
15
20
|
// under in-flight sync work. Callers that tolerate a vanishing database
|
|
@@ -18,7 +23,7 @@ function requireTrustStore(dependencies) {
|
|
|
18
23
|
if (!execSql) {
|
|
19
24
|
throw new DatabaseUnavailableError("Trusted user identity resolution requires a ready SQLite trust store");
|
|
20
25
|
}
|
|
21
|
-
return { execSql, identityTrustDomain
|
|
26
|
+
return { execSql, identityTrustDomain };
|
|
22
27
|
}
|
|
23
28
|
async function compareWithDurablePin(input) {
|
|
24
29
|
try {
|
|
@@ -111,6 +116,47 @@ export async function loadPinnedUserIdentity(input) {
|
|
|
111
116
|
}
|
|
112
117
|
export function createTrustedUserIdentityService(dependencies) {
|
|
113
118
|
return {
|
|
119
|
+
async resolvePinned(userId) {
|
|
120
|
+
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
121
|
+
return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });
|
|
122
|
+
},
|
|
123
|
+
async createLink(appUrl) {
|
|
124
|
+
const identityTrustDomain = requireTrustDomain(dependencies);
|
|
125
|
+
const userId = dependencies.getLocalUserId();
|
|
126
|
+
const candidate = userId ? dependencies.getLocalIdentity(userId) : null;
|
|
127
|
+
if (!userId || !candidate) {
|
|
128
|
+
throw new Error("Sign in before sharing your identity link.");
|
|
129
|
+
}
|
|
130
|
+
const identity = await validateLocalUserIdentity({
|
|
131
|
+
candidate,
|
|
132
|
+
identityTrustDomain,
|
|
133
|
+
userId,
|
|
134
|
+
});
|
|
135
|
+
return createIdentityLink(identity, appUrl);
|
|
136
|
+
},
|
|
137
|
+
async verifyLink(link) {
|
|
138
|
+
const expectation = parseIdentityLink(link);
|
|
139
|
+
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
140
|
+
if (expectation.identityTrustDomain !== identityTrustDomain) {
|
|
141
|
+
throw new Error("This identity link belongs to a different Tearleads service.");
|
|
142
|
+
}
|
|
143
|
+
const localUserId = dependencies.getLocalUserId();
|
|
144
|
+
try {
|
|
145
|
+
const identity = await resolveCandidate(dependencies, expectation.userId, identityTrustDomain);
|
|
146
|
+
if (!identity)
|
|
147
|
+
throw new Error("The identity in this link is unavailable.");
|
|
148
|
+
await assertIdentityLinkMatches(expectation, identity);
|
|
149
|
+
if (dependencies.getExecSql() !== execSql ||
|
|
150
|
+
dependencies.getLocalUserId() !== localUserId) {
|
|
151
|
+
throw new DatabaseUnavailableError("The active identity changed. Open the identity link again.");
|
|
152
|
+
}
|
|
153
|
+
return await pinIdentity({ dependencies, execSql, identity });
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
dependencies.remoteSource.invalidate(expectation.userId);
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
},
|
|
114
160
|
async boundUserId(signingKeyFingerprint) {
|
|
115
161
|
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
116
162
|
return loadTrustedUserIdForSigningKey({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EACL,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,EAC9B,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EACL,wBAAwB,EACxB,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GAKpC,MAAM,SAAS,CAAC;AACjB,OAAO,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esContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n compareOrInsertTrustedUserIdentityPin,\n loadTrustedUserIdentityPin,\n loadTrustedUserIdForSigningKey,\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n validateUserIdentityKeys,\n} from \"./validation\";\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n): {\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identityTrustDomain: string;\n} {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain: dependencies.identityTrustDomain };\n}\n\nasync function compareWithDurablePin(input: {\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identity: ValidatedUserIdentityCandidate;\n}): Promise<void> {\n try {\n await compareOrInsertTrustedUserIdentityPin({\n execSql: input.execSql,\n pin: {\n encapsulationKeyFingerprint: input.identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(\n input.identity.encapsulationPublicKey,\n ),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt: input.firstSeenAt,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: input.identity.identityTrustDomain,\n signingKeyFingerprint: input.identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(input.identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: input.identity.userId,\n },\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${input.identity.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${input.identity.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${input.identity.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${input.identity.userId}`,\n );\n }\n throw error;\n }\n}\n\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n });\n }\n\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\nasync function pinIdentity(input: {\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePin({\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identity: input.identity,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/**\n * Read-only: the identity this trust store already pins for `userId`, or null.\n * The stored keys must still match their stored fingerprints. Never inserts,\n * compares against or replaces a pin.\n */\nexport async function loadPinnedUserIdentity(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentity | null> {\n assertTrustedUserIdentityUserId(input.userId);\n const pin = await loadTrustedUserIdentityPin(input);\n if (!pin) return null;\n const keys = await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: base64ToBytes(pin.encapsulationPublicKey),\n signingKeyFingerprint: pin.signingKeyFingerprint,\n signingPublicKey: base64ToBytes(pin.signingPublicKey),\n },\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n });\n return brandTrustedUserIdentity({\n ...keys,\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n });\n}\n\nexport function createTrustedUserIdentityService(\n dependencies: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n return {\n async boundUserId(signingKeyFingerprint) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadTrustedUserIdForSigningKey({\n execSql,\n identityTrustDomain,\n signingKeyFingerprint,\n });\n },\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({ dependencies, execSql, identity });\n },\n async resolve(userId) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n try {\n const identity = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!identity) {\n return null;\n }\n return await pinIdentity({ dependencies, execSql, identity });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EACL,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,EAC9B,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,wBAAwB,EACxB,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GAKpC,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,cAAc,CAAC;AAEtB,SAAS,kBAAkB,CACzB,YAAoD;IAEpD,0EAA0E;IAC1E,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,CAAC;QACtC,MAAM,IAAI,uB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,GAAG,iBAAiB,CAAC,YAAY,CAAC,CAAC;YACzE,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,gBAAgB,CACrC,YAAY,EACZ,MAAM,EACN,mBAAmB,CACpB,CAAC;gBACF,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACd,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,OAAO,MAAM,WAAW,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;YAChE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n compareOrInsertTrustedUserIdentityPin,\n loadTrustedUserIdentityPin,\n loadTrustedUserIdForSigningKey,\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n validateUserIdentityKeys,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nasync function compareWithDurablePin(input: {\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identity: ValidatedUserIdentityCandidate;\n}): Promise<void> {\n try {\n await compareOrInsertTrustedUserIdentityPin({\n execSql: input.execSql,\n pin: {\n encapsulationKeyFingerprint: input.identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(\n input.identity.encapsulationPublicKey,\n ),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt: input.firstSeenAt,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: input.identity.identityTrustDomain,\n signingKeyFingerprint: input.identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(input.identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: input.identity.userId,\n },\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${input.identity.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${input.identity.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${input.identity.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${input.identity.userId}`,\n );\n }\n throw error;\n }\n}\n\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n });\n }\n\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\nasync function pinIdentity(input: {\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePin({\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identity: input.identity,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/**\n * Read-only: the identity this trust store already pins for `userId`, or null.\n * The stored keys must still match their stored fingerprints. Never inserts,\n * compares against or replaces a pin.\n */\nexport async function loadPinnedUserIdentity(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentity | null> {\n assertTrustedUserIdentityUserId(input.userId);\n const pin = await loadTrustedUserIdentityPin(input);\n if (!pin) return null;\n const keys = await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: base64ToBytes(pin.encapsulationPublicKey),\n signingKeyFingerprint: pin.signingKeyFingerprint,\n signingPublicKey: base64ToBytes(pin.signingPublicKey),\n },\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n });\n return brandTrustedUserIdentity({\n ...keys,\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n });\n}\n\nexport function createTrustedUserIdentityService(\n dependencies: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n async createLink(appUrl) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n },\n async verifyLink(link) {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const identity = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!identity)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, identity);\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId\n ) {\n throw new DatabaseUnavailableError(\n \"The active identity changed. Open the identity link again.\",\n );\n }\n return await pinIdentity({ dependencies, execSql, identity });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n },\n async boundUserId(signingKeyFingerprint) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadTrustedUserIdForSigningKey({\n execSql,\n identityTrustDomain,\n signingKeyFingerprint,\n });\n },\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({ dependencies, execSql, identity });\n },\n async resolve(userId) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n try {\n const identity = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!identity) {\n return null;\n }\n return await pinIdentity({ dependencies, execSql, identity });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n };\n}\n"]}
|
|
@@ -50,6 +50,9 @@ export interface LocalUserIdentityCandidate {
|
|
|
50
50
|
readonly signingPublicKey: Uint8Array;
|
|
51
51
|
}
|
|
52
52
|
export interface TrustedUserIdentityService {
|
|
53
|
+
createLink(appUrl: string): Promise<string>;
|
|
54
|
+
verifyLink(link: string): Promise<TrustedUserIdentity>;
|
|
55
|
+
resolvePinned(userId: string): Promise<TrustedUserIdentity | null>;
|
|
53
56
|
/** The user this device's trust store already binds a signing key to. */
|
|
54
57
|
boundUserId(signingKeyFingerprint: string): Promise<string | null>;
|
|
55
58
|
pinLocal(userId: string, candidate: LocalUserIdentityCandidate): Promise<TrustedUserIdentity>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;AA+E3C,MAAM,UAAU,wBAAwB,CACtC,KAAqC;IAErC,OAAO;QACL,GAAG,KAAK;QACR,CAAC,wBAAwB,CAAC,EAAE,6BAA6B;KAC1D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,wBAAwB,CAAC;YAC1C,6BAA6B,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import type { ExecSql } from \"../sqlite/sqlSchema\";\n\nexport const TRUSTED_USER_IDENTITY_FORMAT_VERSION = 1;\nexport const TRUSTED_USER_IDENTITY_SIGNING_SUITE = \"ML-DSA-87\";\nexport const TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE = \"ML-KEM-1024\";\n\nconst trustedUserIdentityBrand: unique symbol = Symbol(\"trustedUserIdentity\");\nconst trustedUserIdentityBrandValue = true;\n\n/**\n * A complete user identity bundle that has passed strict key validation and\n * the durable trust-on-first-use comparison for its trust domain.\n *\n * The nominal brand keeps raw API and organization response objects from being\n * accepted at cryptographic boundaries by structural typing. Its private\n * symbol and constructor remain package-private to the SDK trust gateway.\n */\nexport interface TrustedUserIdentity {\n readonly [trustedUserIdentityBrand]: true;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\n/** Strictly decoded and self-consistent, but not yet accepted by durable TOFU. */\nexport interface ValidatedUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentitySource {\n invalidate(userId: string): void;\n /**\n * `null` only when the server asserts the user does not exist. A transport\n * or non-404 HTTP failure throws a retryable availability error instead.\n */\n load(userId: string): Promise<RemoteUserIdentityCandidate | null>;\n}\n\nexport interface LocalUserIdentityCandidate {\n readonly encapsulationPublicKey: Uint8Array;\n readonly signingKeyFingerprint?: string | null | undefined;\n readonly signingPublicKey: Uint8Array;\n}\n\nexport interface TrustedUserIdentityService {\n createLink(appUrl: string): Promise<string>;\n verifyLink(link: string): Promise<TrustedUserIdentity>;\n resolvePinned(userId: string): Promise<TrustedUserIdentity | null>;\n /** The user this device's trust store already binds a signing key to. */\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocal(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<TrustedUserIdentity>;\n resolve(userId: string): Promise<TrustedUserIdentity | null>;\n}\n\nexport type TrustedUserIdentityResolver = TrustedUserIdentityService[\"resolve\"];\n\nexport interface TrustedUserIdentityServiceDependencies {\n readonly getExecSql: () => ExecSql | null;\n readonly getLocalIdentity: (\n userId: string,\n ) => LocalUserIdentityCandidate | null;\n readonly getLocalUserId: () => string | null;\n readonly identityTrustDomain: string | null;\n readonly now?: (() => Date) | undefined;\n readonly remoteSource: RemoteUserIdentitySource;\n}\n\nexport function brandTrustedUserIdentity(\n input: ValidatedUserIdentityCandidate,\n): TrustedUserIdentity {\n return {\n ...input,\n [trustedUserIdentityBrand]: trustedUserIdentityBrandValue,\n };\n}\n\nexport function isTrustedUserIdentity(\n value: unknown,\n): value is TrustedUserIdentity {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, trustedUserIdentityBrand) ===\n trustedUserIdentityBrandValue\n );\n}\n"]}
|
package/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// SDK: verified identity links, read-only pins and device-first handles.
|
|
2
2
|
// Authority loaders take exact heads, including cached citations. Obsolete
|
|
3
3
|
// adapters are excluded; authored policy journals survive restart. See workflows/README.md.
|
|
4
4
|
export { ApiRequestMetrics, } from "./internal/api-client/index.js";
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAmK/B,OAAO,EAEL,KAAK,EAEL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EAChC,gCAAgC,EAChC,yBAAyB,EACzB,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,QAAQ,EACR,mBAAmB,EAKnB,8BAA8B,EAC9B,2BAA2B,EAC3B,MAAM,EAGN,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,mCAAmC,EACnC,6BAA6B,EAC7B,oBAAoB,EACpB,OAAO,EACP,0BAA0B,EAG1B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,6BAA6B,EAC7B,oCAAoC,EACpC,4BAA4B,EAC5B,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC9B,uCAAuC,EACvC,iCAAiC,EACjC,2BAA2B,EAC3B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,EAChC,sBAAsB,EACtB,gCAAgC,EAChC,0CAA0C,EAC1C,gCAAgC,EAChC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EACL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACrC,kCAAkC,EAClC,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAW9B,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// Current SDK contract: unified device-first handles and atomic revision checks.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ClientDatabaseOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n type ClientOptions,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n Tearleads,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./documents\";\nexport {\n addDocumentAttachments,\n blobByteSourceInputLength,\n createBlobByteSource,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readBlobByteSource,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AcknowledgedPrincipalPredecessor,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n captureAcknowledgedPrincipalPredecessor,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAmK/B,OAAO,EAEL,KAAK,EAEL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EAChC,gCAAgC,EAChC,yBAAyB,EACzB,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,QAAQ,EACR,mBAAmB,EAKnB,8BAA8B,EAC9B,2BAA2B,EAC3B,MAAM,EAGN,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,mCAAmC,EACnC,6BAA6B,EAC7B,oBAAoB,EACpB,OAAO,EACP,0BAA0B,EAG1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,EACzB,8CAA8C,EAC9C,yBAAyB,EAKzB,eAAe,EAIf,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,GAC5B,MAAM,UAAU,CAAC;AA2BlB,OAAO,EACL,sBA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0C,EAC1C,gCAAgC,EAChC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EACL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACrC,kCAAkC,EAClC,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAW9B,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: verified identity links, read-only pins and device-first handles.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ClientDatabaseOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n type ClientOptions,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n Tearleads,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./documents\";\nexport {\n addDocumentAttachments,\n blobByteSourceInputLength,\n createBlobByteSource,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readBlobByteSource,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AcknowledgedPrincipalPredecessor,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n captureAcknowledgedPrincipalPredecessor,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
|
|
@@ -1816,7 +1816,6 @@ export declare class ApiClient {
|
|
|
1816
1816
|
}[];
|
|
1817
1817
|
} | null>;
|
|
1818
1818
|
getOrganizationBillingManagementUrl(organizationId: string): Promise<{
|
|
1819
|
-
canCancelDirectly: boolean;
|
|
1820
1819
|
managementUrl: string | null;
|
|
1821
1820
|
} | null>;
|
|
1822
1821
|
getOrganizationNativePurchaseEligibility(organizationId: string, store: NativeSubscriptionStore): Promise<{
|
|
@@ -497,16 +497,12 @@ export declare const getOrganizationBillingManagementUrlOperation: Omit<{
|
|
|
497
497
|
readonly path: "/organizations/{organizationId}/billing/management-url";
|
|
498
498
|
readonly responses: {
|
|
499
499
|
readonly 200: z.ZodType<{
|
|
500
|
-
canCancelDirectly: boolean;
|
|
501
500
|
managementUrl: string | null;
|
|
502
501
|
}, {
|
|
503
|
-
canCancelDirectly: boolean;
|
|
504
502
|
managementUrl: string | null;
|
|
505
503
|
}, z.core.$ZodTypeInternals<{
|
|
506
|
-
canCancelDirectly: boolean;
|
|
507
504
|
managementUrl: string | null;
|
|
508
505
|
}, {
|
|
509
|
-
canCancelDirectly: boolean;
|
|
510
506
|
managementUrl: string | null;
|
|
511
507
|
}>>;
|
|
512
508
|
};
|
|
@@ -12,16 +12,12 @@ import { z } from "zod";
|
|
|
12
12
|
* this response.
|
|
13
13
|
*/
|
|
14
14
|
export declare const OrganizationBillingManagementUrlResponseSchema: z.ZodType<{
|
|
15
|
-
canCancelDirectly: boolean;
|
|
16
15
|
managementUrl: string | null;
|
|
17
16
|
}, {
|
|
18
|
-
canCancelDirectly: boolean;
|
|
19
17
|
managementUrl: string | null;
|
|
20
18
|
}, z.core.$ZodTypeInternals<{
|
|
21
|
-
canCancelDirectly: boolean;
|
|
22
19
|
managementUrl: string | null;
|
|
23
20
|
}, {
|
|
24
|
-
canCancelDirectly: boolean;
|
|
25
21
|
managementUrl: string | null;
|
|
26
22
|
}>>;
|
|
27
23
|
export type OrganizationBillingManagementUrlResponse = z.infer<typeof OrganizationBillingManagementUrlResponseSchema>;
|
|
@@ -13,8 +13,6 @@ import { loosePlainObject } from "../schema.js";
|
|
|
13
13
|
* this response.
|
|
14
14
|
*/
|
|
15
15
|
export const OrganizationBillingManagementUrlResponseSchema = loosePlainObject({
|
|
16
|
-
/** Retained for installed clients; current clients read this from the snapshot. */
|
|
17
|
-
canCancelDirectly: z.boolean(),
|
|
18
16
|
managementUrl: z.string().nullable(),
|
|
19
17
|
});
|
|
20
18
|
export function isOrganizationBillingManagementUrlResponse(value) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationBillingManagementUrl.js","sourceRoot":"","sources":["organizationBillingManagementUrl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,8CAA8C,GAAG,gBAAgB,CAAC;IAC7E,
|
|
1
|
+
{"version":3,"file":"organizationBillingManagementUrl.js","sourceRoot":"","sources":["organizationBillingManagementUrl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7C;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,8CAA8C,GAAG,gBAAgB,CAAC;IAC7E,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACrC,CAAC,CAAC;AAMH,MAAM,UAAU,0CAA0C,CACxD,KAAc;IAEd,OAAO,8CAA8C,CAAC,SAAS,CAAC,KAAK,CAAC;SACnE,OAAO,CAAC;AACb,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { loosePlainObject } from \"../schema\";\n\n/**\n * The subscription-management URL for an organization's paid subscription. The\n * server resolves it from the billing provider (RevenueCat) using the org's\n * stored customer id, so any org admin — not just the buyer whose device holds\n * the subscription — can reach the manage/cancel page. Native management\n * remains available for lapsed subscriptions so the buyer can repair a payment\n * issue. `managementUrl` is null when the organization has no native\n * provider-managed subscription, the provider exposes no management link, or\n * the lookup could not be completed. Which purchase system owns the\n * subscription is part of the billing snapshot (`subscriptionSource`), not of\n * this response.\n */\nexport const OrganizationBillingManagementUrlResponseSchema = loosePlainObject({\n managementUrl: z.string().nullable(),\n});\n\nexport type OrganizationBillingManagementUrlResponse = z.infer<\n typeof OrganizationBillingManagementUrlResponseSchema\n>;\n\nexport function isOrganizationBillingManagementUrlResponse(\n value: unknown,\n): value is OrganizationBillingManagementUrlResponse {\n return OrganizationBillingManagementUrlResponseSchema.safeParse(value)\n .success;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -75,21 +75,30 @@ function buildPrincipalPolicyHistoryEntries(bundle) {
|
|
|
75
75
|
});
|
|
76
76
|
return entries.reverse();
|
|
77
77
|
}
|
|
78
|
+
// Entries run newest first; the oldest one held is the cursor for older
|
|
79
|
+
// entries unless it is genesis.
|
|
80
|
+
function olderEntriesCursor(entries) {
|
|
81
|
+
const oldestVersion = entries.at(-1)?.version;
|
|
82
|
+
return oldestVersion !== undefined && oldestVersion > 1
|
|
83
|
+
? oldestVersion
|
|
84
|
+
: null;
|
|
85
|
+
}
|
|
78
86
|
export function buildOrganizationGroupPolicyHistory(bundle, organizationId) {
|
|
87
|
+
const entries = buildPrincipalPolicyHistoryEntries(bundle);
|
|
79
88
|
return {
|
|
80
|
-
entries
|
|
89
|
+
entries,
|
|
81
90
|
groupId: bundle.currentState.principalId,
|
|
91
|
+
nextBeforeVersion: olderEntriesCursor(entries),
|
|
82
92
|
organizationId,
|
|
83
93
|
principalId: bundle.currentState.principalId,
|
|
84
94
|
principalType: "group",
|
|
85
95
|
};
|
|
86
96
|
}
|
|
87
97
|
export function buildOrganizationPolicyHistory(bundle) {
|
|
98
|
+
const entries = buildPrincipalPolicyHistoryEntries(bundle);
|
|
88
99
|
return {
|
|
89
|
-
entries:
|
|
90
|
-
|
|
91
|
-
groupChanges: null,
|
|
92
|
-
})),
|
|
100
|
+
entries: entries.map((entry) => ({ ...entry, groupChanges: null })),
|
|
101
|
+
nextBeforeVersion: olderEntriesCursor(entries),
|
|
93
102
|
organizationId: bundle.currentState.principalId,
|
|
94
103
|
principalId: bundle.currentState.principalId,
|
|
95
104
|
principalType: "organization",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policyHistoryReadModel.js","sourceRoot":"","sources":["policyHistoryReadModel.ts"],"names":[],"mappings":"AA8BA,SAAS,mBAAmB,CAC1B,MAAyD;IAEzD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC;AAED,SAAS,6BAA6B,CACpC,IAAuC,EACvC,KAAwC;IAExC,OAAO,CACL,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC;QACvC,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAChD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8BAA8B,CAAC,KAG9C;IACC,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAClC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,CACtE,CAAC;IACF,MAAM,mBAAmB,GAAG,IAAI,GAAG,CACjC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,CACrE,CAAC;IACF,MAAM,OAAO,GAAwC,EAAE,CAAC;IAExD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EAAE,kBAAkB,CAAC,OAAO,CAAC;QAC9C,cAAc;QACd,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,aAAa,EAAE,OAAO;KACvB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,MAAqC;IAErC,MAAM,OAAO,GAAG,kCAAkC,CAAC,MAAM,CAAC,CAAC;IAC3D,OAAO;QACL,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;QACnE,iBAAiB,EAAE,kBAAkB,CAAC,OAAO,CAAC;QAC9C,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC/C,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;QAC5C,aAAa,EAAE,cAAc;KAC9B,CAAC;AACJ,CAAC","sourcesContent":["import type {\n PrincipalPolicyBundleResponse,\n PrincipalProjectionMemberResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n OrganizationGroupPolicyHistory,\n OrganizationPolicyHistory,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalPolicyHistoryEntry,\n} from \"./policyHistoryTypes\";\n\nexport type {\n OrganizationGroupPolicyHistory,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n} from \"./policyHistoryTypes\";\n\ninterface PrincipalPolicyHistoryState {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberResponse>;\n readonly state: PrincipalStateResponse;\n}\n\nfunction projectionMemberKey(\n member: Pick<PrincipalProjectionMemberResponse, \"userId\">,\n): string {\n return member.userId;\n}\n\nfunction comparePrincipalMemberChanges(\n left: OrganizationPrincipalMemberChange,\n right: OrganizationPrincipalMemberChange,\n): number {\n return (\n left.userId.localeCompare(right.userId) ||\n left.changeType.localeCompare(right.changeType)\n );\n}\n\nexport function diffPrincipalProjectionMembers(input: {\n readonly current: ReadonlyArray<PrincipalProjectionMemberResponse>;\n readonly previous: ReadonlyArray<PrincipalProjectionMemberResponse>;\n}): OrganizationPrincipalMemberChange[] {\n const previousMembersByKey = new Map(\n input.previous.map((member) => [projectionMemberKey(member), member]),\n );\n const currentMembersByKey = new Map(\n input.current.map((member) => [projectionMemberKey(member), member]),\n );\n const changes: OrganizationPrincipalMemberChange[] = [];\n\n for (const currentMember of input.current) {\n const previousMember = previousMembersByKey.get(\n projectionMemberKey(currentMember),\n );\n if (!previousMember) {\n changes.push({\n changeType: \"added\",\n userId: currentMember.userId,\n nextRole: currentMember.role,\n previousRole: null,\n });\n continue;\n }\n\n if (previousMember.role !== currentMember.role) {\n changes.push({\n changeType: \"role_changed\",\n userId: currentMember.userId,\n nextRole: currentMember.role,\n previousRole: previousMember.role,\n });\n }\n }\n\n for (const previousMember of input.previous) {\n if (currentMembersByKey.has(projectionMemberKey(previousMember))) {\n continue;\n }\n\n changes.push({\n changeType: \"removed\",\n userId: previousMember.userId,\n nextRole: null,\n previousRole: previousMember.role,\n });\n }\n\n return changes.sort(comparePrincipalMemberChanges);\n}\n\nfunction principalPolicyHistoryStates(\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyHistoryState[] {\n return [\n ...bundle.previousStates.map((entry) => ({\n projection: entry.projection,\n state: entry.state,\n })),\n {\n projection: bundle.currentProjection,\n state: bundle.currentState,\n },\n ].sort((left, right) => left.state.version - right.state.version);\n}\n\nfunction buildPrincipalPolicyHistoryEntries(\n bundle: PrincipalPolicyBundleResponse,\n): OrganizationPrincipalPolicyHistoryEntry[] {\n const states = principalPolicyHistoryStates(bundle);\n const entries = states.map((entry, index) => {\n const previousProjection = states[index - 1]?.projection ?? [];\n\n return {\n changes: diffPrincipalProjectionMembers({\n current: entry.projection,\n previous: previousProjection,\n }),\n createdAt: entry.state.createdAt,\n keyEpoch: entry.state.keyEpoch,\n memberCount: entry.state.memberCount,\n signedAt: entry.state.signedAt,\n signerUserId: entry.state.signerUserId,\n signerUserKeyFingerprint: entry.state.signerUserKeyFingerprint,\n stateHash: entry.state.stateHash,\n version: entry.state.version,\n };\n });\n\n return entries.reverse();\n}\n\n// Entries run newest first; the oldest one held is the cursor for older\n// entries unless it is genesis.\nfunction olderEntriesCursor(\n entries: ReadonlyArray<OrganizationPrincipalPolicyHistoryEntry>,\n): number | null {\n const oldestVersion = entries.at(-1)?.version;\n return oldestVersion !== undefined && oldestVersion > 1\n ? oldestVersion\n : null;\n}\n\nexport function buildOrganizationGroupPolicyHistory(\n bundle: PrincipalPolicyBundleResponse,\n organizationId: string,\n): OrganizationGroupPolicyHistory {\n const entries = buildPrincipalPolicyHistoryEntries(bundle);\n return {\n entries,\n groupId: bundle.currentState.principalId,\n nextBeforeVersion: olderEntriesCursor(entries),\n organizationId,\n principalId: bundle.currentState.principalId,\n principalType: \"group\",\n };\n}\n\nexport function buildOrganizationPolicyHistory(\n bundle: PrincipalPolicyBundleResponse,\n): OrganizationPolicyHistory {\n const entries = buildPrincipalPolicyHistoryEntries(bundle);\n return {\n entries: entries.map((entry) => ({ ...entry, groupChanges: null })),\n nextBeforeVersion: olderEntriesCursor(entries),\n organizationId: bundle.currentState.principalId,\n principalId: bundle.currentState.principalId,\n principalType: \"organization\",\n };\n}\n"]}
|
|
@@ -24,14 +24,15 @@ export interface OrganizationPrincipalPolicyHistory {
|
|
|
24
24
|
readonly principalType: PrincipalStateResponse["principalType"];
|
|
25
25
|
}
|
|
26
26
|
export interface OrganizationGroupPolicyHistory extends OrganizationPrincipalPolicyHistory {
|
|
27
|
-
/** Exclusive cursor for older entries;
|
|
28
|
-
readonly nextBeforeVersion
|
|
27
|
+
/** Exclusive cursor for older entries; null once the oldest is loaded. */
|
|
28
|
+
readonly nextBeforeVersion: number | null;
|
|
29
29
|
readonly groupId: string;
|
|
30
30
|
readonly organizationId: string;
|
|
31
31
|
readonly principalType: "group";
|
|
32
32
|
}
|
|
33
33
|
export interface OrganizationPolicyHistory extends OrganizationPrincipalPolicyHistory {
|
|
34
|
-
|
|
34
|
+
/** Exclusive cursor for older entries; null once the oldest is loaded. */
|
|
35
|
+
readonly nextBeforeVersion: number | null;
|
|
35
36
|
readonly entries: OrganizationPolicyHistoryEntry[];
|
|
36
37
|
readonly organizationId: string;
|
|
37
38
|
readonly principalType: "organization";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policyHistoryTypes.js","sourceRoot":"","sources":["policyHistoryTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n PrincipalContainerGrantResponse,\n PrincipalProjectionMemberResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\n\nexport type OrganizationPrincipalMemberChangeType =\n | \"added\"\n | \"removed\"\n | \"role_changed\";\nexport interface OrganizationPrincipalMemberChange {\n readonly changeType: OrganizationPrincipalMemberChangeType;\n readonly userId: string;\n readonly nextRole: PrincipalProjectionMemberResponse[\"role\"] | null;\n readonly previousRole: PrincipalProjectionMemberResponse[\"role\"] | null;\n}\nexport interface OrganizationPrincipalPolicyHistoryEntry {\n readonly changes: OrganizationPrincipalMemberChange[];\n readonly createdAt: string;\n readonly keyEpoch: number;\n readonly memberCount: number;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signerUserKeyFingerprint: string;\n readonly stateHash: string;\n readonly version: number;\n}\nexport type OrganizationGroupPolicyHistoryEntry =\n OrganizationPrincipalPolicyHistoryEntry;\nexport interface OrganizationPrincipalPolicyHistory {\n readonly entries: OrganizationPrincipalPolicyHistoryEntry[];\n readonly principalId: string;\n readonly principalType: PrincipalStateResponse[\"principalType\"];\n}\nexport interface OrganizationGroupPolicyHistory\n extends OrganizationPrincipalPolicyHistory {\n /** Exclusive cursor for older entries;
|
|
1
|
+
{"version":3,"file":"policyHistoryTypes.js","sourceRoot":"","sources":["policyHistoryTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n PrincipalContainerGrantResponse,\n PrincipalProjectionMemberResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\n\nexport type OrganizationPrincipalMemberChangeType =\n | \"added\"\n | \"removed\"\n | \"role_changed\";\nexport interface OrganizationPrincipalMemberChange {\n readonly changeType: OrganizationPrincipalMemberChangeType;\n readonly userId: string;\n readonly nextRole: PrincipalProjectionMemberResponse[\"role\"] | null;\n readonly previousRole: PrincipalProjectionMemberResponse[\"role\"] | null;\n}\nexport interface OrganizationPrincipalPolicyHistoryEntry {\n readonly changes: OrganizationPrincipalMemberChange[];\n readonly createdAt: string;\n readonly keyEpoch: number;\n readonly memberCount: number;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signerUserKeyFingerprint: string;\n readonly stateHash: string;\n readonly version: number;\n}\nexport type OrganizationGroupPolicyHistoryEntry =\n OrganizationPrincipalPolicyHistoryEntry;\nexport interface OrganizationPrincipalPolicyHistory {\n readonly entries: OrganizationPrincipalPolicyHistoryEntry[];\n readonly principalId: string;\n readonly principalType: PrincipalStateResponse[\"principalType\"];\n}\nexport interface OrganizationGroupPolicyHistory\n extends OrganizationPrincipalPolicyHistory {\n /** Exclusive cursor for older entries; null once the oldest is loaded. */\n readonly nextBeforeVersion: number | null;\n readonly groupId: string;\n readonly organizationId: string;\n readonly principalType: \"group\";\n}\nexport interface OrganizationPolicyHistory\n extends OrganizationPrincipalPolicyHistory {\n /** Exclusive cursor for older entries; null once the oldest is loaded. */\n readonly nextBeforeVersion: number | null;\n readonly entries: OrganizationPolicyHistoryEntry[];\n readonly organizationId: string;\n readonly principalType: \"organization\";\n}\n\nexport interface OrganizationPolicyHistoryEntry\n extends OrganizationPrincipalPolicyHistoryEntry {\n /** Null when the additional signed evidence has not been loaded. */\n readonly groupChanges: OrganizationPolicyGroupChange[] | null;\n}\n\nexport interface OrganizationPolicyGrantChange {\n readonly containerId: string;\n readonly previousAccess:\n | PrincipalContainerGrantResponse[\"accessLevel\"]\n | null;\n readonly nextAccess: PrincipalContainerGrantResponse[\"accessLevel\"] | null;\n}\n\nexport interface OrganizationPolicyGroupChange {\n readonly groupId: string;\n readonly changeType: \"created\" | \"updated\" | \"deleted\";\n readonly previousVersion: number | null;\n readonly version: number;\n readonly previousKeyEpoch: number | null;\n readonly keyEpoch: number;\n readonly changes: OrganizationPrincipalMemberChange[];\n readonly grantChanges: OrganizationPolicyGrantChange[];\n}\n"]}
|