@hediet/linkrpc 0.0.3-next.20261024.1 → 0.0.3-next.20261025.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node.d.ts +3 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +6 -2
- package/dist/node.js.map +1 -1
- package/package.json +2 -2
package/dist/node.d.ts
CHANGED
|
@@ -281,6 +281,8 @@ interface PersistedIdentity {
|
|
|
281
281
|
* identities — not for anything that must resist file-system attackers.
|
|
282
282
|
*/
|
|
283
283
|
declare function loadOrCreateIdentity(opts: LoadOrCreateIdentityOptions): Promise<PersistedIdentity>;
|
|
284
|
+
/** The on-disk file {@link loadOrCreateIdentity} uses for `opts`, without reading or creating it. */
|
|
285
|
+
declare function identityFilePath(opts: LoadOrCreateIdentityOptions): string;
|
|
284
286
|
//#endregion
|
|
285
287
|
//#region src/node/hubReconnect.d.ts
|
|
286
288
|
interface ServeOverHubIdentityOptions {
|
|
@@ -504,5 +506,5 @@ interface OpenWebSocketOptions {
|
|
|
504
506
|
/** Node-only header extension. The web entry exposes the standard overload. */
|
|
505
507
|
declare function openWebSocket(url: string, opts?: OpenWebSocketOptions): Promise<WebSocket>;
|
|
506
508
|
//#endregion
|
|
507
|
-
export { Ability, type AcceptedRootIssuer, ApplicationErrorDescriptor, ApplicationErrorDescriptorBase, ApplicationErrorOf, ApplicationErrorValue, ApplicationErrorsOf, ArraySchema, BareGetOptions, type BareInterfaceTarget, Base64Sha256, BooleanSchema, BoundInterfaceTemplate, Call, CallBind, CallMeta, CallTarget, type CancellableRequest, CapBag, CapBagOptions, type CapProvider, type CapProviderResult, Capability, CapabilityIssuanceError, type CapabilityIssuancePlan, type CapabilityIssuanceProposal, Channel, ChannelConnector, type Result as ChannelResult, type ChannelTransport, CheckedCall, CheckedCallResult, type CmdEnvEndpoint, type CmdStdioEndpoint, Components, type ConnectNdjsonOptions, type ConnectToHubOptions, type ConnectableChannel, type ConnectedNdjson, ConstSchema, CreatedApplicationErrorValue, CreatedRpcErrorValue, DEFAULT_RPC_TIMEOUT_MS, DeclaredApplicationErrorOf, DefaultInterfaceTarget, DiscriminatorSchema, EXTENSION_PREFIX, type EndpointCommand, type EndpointConnection, EnumSchema, ErrorCode, ErrorSchema, type ExpBackoffOptions, ExportStaticHubSchemaOptions, FlattenInterfaceDeclarations, type FormatEndpointOptions, GenerateContractOptions, GenerateInterfaceOptions, GenericRpcError, GetOptions, HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY, HeaderDelimitedTransport, type HeaderDelimitedTransportOptions, type HubChannel, type HubClientHandle, type HubPrefixClaimer, type HubPrefixClaimerOptions, IMessageTransport, INITIALIZE_METHOD, INITIALIZE_PROTOCOL_VERSION, INTERFACE_TEMPLATES_EXTENSION, type IRequestHandler, type IRequestSender, Identity, InMemoryManagedIdentity, InMemoryManagedIdentityStorage, type IncomingCall, type IncomingStream, type InitializeParams, type InitializeResult, type InitializeRole, InspectionRegistration, IntegerSchema, InterfaceAuthoringOptions, InterfaceClient, InterfaceDeclarations, InterfaceDefinition, InterfaceDefinitionOpts, InterfaceHandlers, InterfaceInfo, InterfaceMemberRef, InterfaceMemberRefMap, InterfaceRef, InterfaceRegistration, InterfaceResultClient, InterfaceTarget, type InterfaceTemplateArgument, InterfaceTemplateClient, type InterfaceTemplateErrorSchema, type InterfaceTemplateGroup, type InterfaceTemplateInstance, type InterfaceTemplateJsonSchema, type InterfaceTemplateMethodSchema, InterfaceTemplateResultClient, type InterfaceTemplateSchema, type InterfaceTemplatesMetadata, type IssueCapabilitiesOptions, type IssueCapabilityOptions, JsonObject, JsonRpcChannel, JsonRpcError, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, JsonRpcSuccess, JsonValue, KEY_ID_PREFIX, type KeepConnectedHandle, KeyId, Keypair, KeypairIdentity, KeypairSigningIdentity, LINKRPC_ENDPOINT_VAR, LINKRPC_INITIALIZE_METHOD_ALIAS, LINKRPC_META_KEY, LINKRPC_SIGNATURE_KEY, LINKRPC_TOKEN_VAR, LINKRPC_UNSIGNED_KEY, LegacyErrorSchema, LinkRpcConnection, LinkRpcConnectionOptions, LinkRpcInterfaceSchema, LinkRpcJsonRpcMessage, LinkRpcJsonRpcNotification, LinkRpcJsonRpcRequest, LinkRpcJsonSchema, LinkRpcUnsigned, LinkRpcWireMeta, LinkRpcWireParams, type LoadOrCreateIdentityOptions, LocalRpcError, ManagedIdentity, ManagedIdentityStorage, ManagedIdentityStorageBackend, type ManagedSigningChannel, type MappedInterfaceTemplate, MaterializedJsonSchema, MemberAnnotations, MemberDocs, MemberMap, MemberType, MessageTransportDirection, MessageTransportTrace, MessageTransportWithContext, MessageWithContext, type MessageWithCtx, MethodSchema, MultiplexedTransport, MuxEnvelope, NodeInfo, NonCompliantServerError, NotificationType, NullSchema, NumberSchema, ObjectSchema, type OnChannelConnect, OneOfSchema, OneShotCapStaging, type OpenHubChannelOptions, type OpenWebSocketOptions, PRINCIPAL_PREFIX, ParamMatcher, type ParamMatcherFor, type ParamMatchers, ParsedMethodName, ParticipantDescriptor, ParticipantDescriptorSource, Pattern, Permission, type PermitResult, type PersistedIdentity, Principal, PrincipalId, PrincipalWithStore, PrivateKey, PublicApplicationErrorOf, PublicKey, PublicSigningIdentity, PublicWrappingIdentity, QualifiedInterfaceTarget, RawErrorSchema, type RawStreamingCall, RefSchema, type RegisterHubPrefixOptions, RegisterOptions, RemoteRpcError, RequestId, RequestType, ResolveSigningKeyArgs, type ResolvedEndpoint, type Result$1 as Result, RootPrincipalReq, RootPrincipalSet, RouteClaim, RpcCallError, RpcError, RpcErrorBody, RpcErrorDescriptor, RpcErrorValue, RpcFailure, RpcValidationIssue, type RunInitializeHandshakeOptions, STREAM_METHOD, Schema, SchemaBase, type SchemaParameterReference, SchemaToZodContext, SeededPrincipalOptions, type SendOpts, SerializedKeypairSigningIdentity, type ServeOverHubController, type ServeOverHubIdentityOptions, type ServeOverHubOptions, ServiceHandle, ServiceIdPattern, SignDomain, SignParamsOptions, SignRpcCallOptions, Signature, SignatureEnvelope, Signatures, SignedCapability, SignedRpcCall, type SigningCallCtx, SigningIdentity, SigningSender, type SigningSenderConfig, type SocketEndpoint, type StartEndpointOptions, type StartedEndpoint, StaticHubSchema, StaticHubSchemaDocument, StaticInterfaceReference, StaticService, type StdioChannel, StreamApi, StreamCallOptions, StreamControlReason, StreamControlType, StreamDir, type StreamSendOpts, StreamSendParams, StreamingCall, StringSchema, TargetPattern, TopologyGraph, TopologyIdGenerator, TopologyLink, TopologyLinkEndpoint, TopologyNode, TopologyPort, TopologyTransportEndpoint, TopologyTransportInfo, TrafficEvent, TrafficOverflowEvent, TrafficTransitEndpoint, TrafficTransitEvent, TrafficWatchResult, TransportPair, TransportRpcError, TupleSchema, UnionSchema, VerifyCallOptions, VerifyResult, VerifyRpcCallOptions, VerifyRpcCallResult, WebSocketTransport, WrappingIdentity, type WsEndpoint, type WsNoInitEndpoint, X25519Keypair, ZodToSvcJsonSchemaOptions, applicationError, assertSchemaReferences, attachCapabilities, bareInterfaceTarget, base64UrlToBytes, bytesToBase64Url, capBagFreshAt, capabilityFreshAt, capabilityPermits, componentSchemaName, componentSchemaRef, computeInterfaceHash, connectNdjson, connectToCmdStdio, connectToHub, connectTransports, createHubPrefixClaimer, createManagedIdentity, createManagedPrincipal, createMemoryPrincipal, createSchemaToZod, createSeededMemoryPrincipal, createSeededSigningIdentity, createSelfManagedPrincipal, createSelfManagedPrincipalFromFile, crypto_d_exports as crypto, defaultInterfaceTarget, defaultsInterface, defineInterface, defineInterfaceTemplate, directoryInterface, directoryWatchNever, exportStaticHubSchema, fileManagedIdentityStorage, formatEndpointUri, generateTsContract, generateTsInterface, getDelegationRootIds, getHubEnvironment, getInterfaceTags, getKeyId, hasSignedCapabilityShape, httpRequestListener, identityInterface, identityStorageInterface, interfaceFromSchema, interfaceTarget, interfaceTemplateArgumentsEquivalent, interfaceTemplateMemberName, interfaceTemplatesEqual, invoke, isApplicationErrorValue, isAssignable, isHubEndpoint, isInterfaceTarget, isNotification, isRequest, isResponse, isRpcFailure, issueCapabilities, issueCapability, jcsCanonicalize, jcsCanonicalizeBytes, keyIdForPrincipal, keyIdForPublicKey, loadOrCreateIdentity, matchParams, matchesJsonSchema, materializeJsonSchema, methodNameToTarget, nodeInterface, normalizeJsonSchema, notificationType, openHubChannel, openStdioChannel, openWebSocket, parseEndpointUri, parseMethodName, parseStaticHubSchema, permissionMatchesTarget, permissionPermits, permits, prefix, prepareCapabilityIssuance, principalForPublicKey, publicKeyForKeyId, readSignature, registerHubPrefix, registerIdentityOnOverlay, registerLazyIdentityOnOverlay, requestType, requireHubEndpoint, requireObjectParams, resolveSigningKey, rpcError, runInitializeHandshake, schemaToZod, schemasInterface, serveOnStdio, serveOverHubWithReconnect, signCapability, signParams, signRpcCall, signedHash, signingDomainValue, signingInput, startEndpoint, streamInterface, stripLinkRpcWireMeta, toMethodSchema, topologyInterface, traceMessageTransport, trafficInterface, validateInterfaceTemplates, validateJsonSchema, verifyCall, verifyRpcCall, withRpcTimeout, withSignature, zParticipantDescriptor, zParticipantDescriptorSource, zRouteClaim, zServiceIdPattern, zTopologyGraph, zTopologyLink, zTopologyLinkEndpoint, zTopologyNode, zTopologyPort, zTopologyTransportEndpoint, zTopologyTransportInfo, zTrafficEvent, zTrafficOverflowEvent, zTrafficTransitEndpoint, zTrafficTransitEvent, zTrafficWatchResult, zodToSvcJsonSchema };
|
|
509
|
+
export { Ability, type AcceptedRootIssuer, ApplicationErrorDescriptor, ApplicationErrorDescriptorBase, ApplicationErrorOf, ApplicationErrorValue, ApplicationErrorsOf, ArraySchema, BareGetOptions, type BareInterfaceTarget, Base64Sha256, BooleanSchema, BoundInterfaceTemplate, Call, CallBind, CallMeta, CallTarget, type CancellableRequest, CapBag, CapBagOptions, type CapProvider, type CapProviderResult, Capability, CapabilityIssuanceError, type CapabilityIssuancePlan, type CapabilityIssuanceProposal, Channel, ChannelConnector, type Result as ChannelResult, type ChannelTransport, CheckedCall, CheckedCallResult, type CmdEnvEndpoint, type CmdStdioEndpoint, Components, type ConnectNdjsonOptions, type ConnectToHubOptions, type ConnectableChannel, type ConnectedNdjson, ConstSchema, CreatedApplicationErrorValue, CreatedRpcErrorValue, DEFAULT_RPC_TIMEOUT_MS, DeclaredApplicationErrorOf, DefaultInterfaceTarget, DiscriminatorSchema, EXTENSION_PREFIX, type EndpointCommand, type EndpointConnection, EnumSchema, ErrorCode, ErrorSchema, type ExpBackoffOptions, ExportStaticHubSchemaOptions, FlattenInterfaceDeclarations, type FormatEndpointOptions, GenerateContractOptions, GenerateInterfaceOptions, GenericRpcError, GetOptions, HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY, HeaderDelimitedTransport, type HeaderDelimitedTransportOptions, type HubChannel, type HubClientHandle, type HubPrefixClaimer, type HubPrefixClaimerOptions, IMessageTransport, INITIALIZE_METHOD, INITIALIZE_PROTOCOL_VERSION, INTERFACE_TEMPLATES_EXTENSION, type IRequestHandler, type IRequestSender, Identity, InMemoryManagedIdentity, InMemoryManagedIdentityStorage, type IncomingCall, type IncomingStream, type InitializeParams, type InitializeResult, type InitializeRole, InspectionRegistration, IntegerSchema, InterfaceAuthoringOptions, InterfaceClient, InterfaceDeclarations, InterfaceDefinition, InterfaceDefinitionOpts, InterfaceHandlers, InterfaceInfo, InterfaceMemberRef, InterfaceMemberRefMap, InterfaceRef, InterfaceRegistration, InterfaceResultClient, InterfaceTarget, type InterfaceTemplateArgument, InterfaceTemplateClient, type InterfaceTemplateErrorSchema, type InterfaceTemplateGroup, type InterfaceTemplateInstance, type InterfaceTemplateJsonSchema, type InterfaceTemplateMethodSchema, InterfaceTemplateResultClient, type InterfaceTemplateSchema, type InterfaceTemplatesMetadata, type IssueCapabilitiesOptions, type IssueCapabilityOptions, JsonObject, JsonRpcChannel, JsonRpcError, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, JsonRpcSuccess, JsonValue, KEY_ID_PREFIX, type KeepConnectedHandle, KeyId, Keypair, KeypairIdentity, KeypairSigningIdentity, LINKRPC_ENDPOINT_VAR, LINKRPC_INITIALIZE_METHOD_ALIAS, LINKRPC_META_KEY, LINKRPC_SIGNATURE_KEY, LINKRPC_TOKEN_VAR, LINKRPC_UNSIGNED_KEY, LegacyErrorSchema, LinkRpcConnection, LinkRpcConnectionOptions, LinkRpcInterfaceSchema, LinkRpcJsonRpcMessage, LinkRpcJsonRpcNotification, LinkRpcJsonRpcRequest, LinkRpcJsonSchema, LinkRpcUnsigned, LinkRpcWireMeta, LinkRpcWireParams, type LoadOrCreateIdentityOptions, LocalRpcError, ManagedIdentity, ManagedIdentityStorage, ManagedIdentityStorageBackend, type ManagedSigningChannel, type MappedInterfaceTemplate, MaterializedJsonSchema, MemberAnnotations, MemberDocs, MemberMap, MemberType, MessageTransportDirection, MessageTransportTrace, MessageTransportWithContext, MessageWithContext, type MessageWithCtx, MethodSchema, MultiplexedTransport, MuxEnvelope, NodeInfo, NonCompliantServerError, NotificationType, NullSchema, NumberSchema, ObjectSchema, type OnChannelConnect, OneOfSchema, OneShotCapStaging, type OpenHubChannelOptions, type OpenWebSocketOptions, PRINCIPAL_PREFIX, ParamMatcher, type ParamMatcherFor, type ParamMatchers, ParsedMethodName, ParticipantDescriptor, ParticipantDescriptorSource, Pattern, Permission, type PermitResult, type PersistedIdentity, Principal, PrincipalId, PrincipalWithStore, PrivateKey, PublicApplicationErrorOf, PublicKey, PublicSigningIdentity, PublicWrappingIdentity, QualifiedInterfaceTarget, RawErrorSchema, type RawStreamingCall, RefSchema, type RegisterHubPrefixOptions, RegisterOptions, RemoteRpcError, RequestId, RequestType, ResolveSigningKeyArgs, type ResolvedEndpoint, type Result$1 as Result, RootPrincipalReq, RootPrincipalSet, RouteClaim, RpcCallError, RpcError, RpcErrorBody, RpcErrorDescriptor, RpcErrorValue, RpcFailure, RpcValidationIssue, type RunInitializeHandshakeOptions, STREAM_METHOD, Schema, SchemaBase, type SchemaParameterReference, SchemaToZodContext, SeededPrincipalOptions, type SendOpts, SerializedKeypairSigningIdentity, type ServeOverHubController, type ServeOverHubIdentityOptions, type ServeOverHubOptions, ServiceHandle, ServiceIdPattern, SignDomain, SignParamsOptions, SignRpcCallOptions, Signature, SignatureEnvelope, Signatures, SignedCapability, SignedRpcCall, type SigningCallCtx, SigningIdentity, SigningSender, type SigningSenderConfig, type SocketEndpoint, type StartEndpointOptions, type StartedEndpoint, StaticHubSchema, StaticHubSchemaDocument, StaticInterfaceReference, StaticService, type StdioChannel, StreamApi, StreamCallOptions, StreamControlReason, StreamControlType, StreamDir, type StreamSendOpts, StreamSendParams, StreamingCall, StringSchema, TargetPattern, TopologyGraph, TopologyIdGenerator, TopologyLink, TopologyLinkEndpoint, TopologyNode, TopologyPort, TopologyTransportEndpoint, TopologyTransportInfo, TrafficEvent, TrafficOverflowEvent, TrafficTransitEndpoint, TrafficTransitEvent, TrafficWatchResult, TransportPair, TransportRpcError, TupleSchema, UnionSchema, VerifyCallOptions, VerifyResult, VerifyRpcCallOptions, VerifyRpcCallResult, WebSocketTransport, WrappingIdentity, type WsEndpoint, type WsNoInitEndpoint, X25519Keypair, ZodToSvcJsonSchemaOptions, applicationError, assertSchemaReferences, attachCapabilities, bareInterfaceTarget, base64UrlToBytes, bytesToBase64Url, capBagFreshAt, capabilityFreshAt, capabilityPermits, componentSchemaName, componentSchemaRef, computeInterfaceHash, connectNdjson, connectToCmdStdio, connectToHub, connectTransports, createHubPrefixClaimer, createManagedIdentity, createManagedPrincipal, createMemoryPrincipal, createSchemaToZod, createSeededMemoryPrincipal, createSeededSigningIdentity, createSelfManagedPrincipal, createSelfManagedPrincipalFromFile, crypto_d_exports as crypto, defaultInterfaceTarget, defaultsInterface, defineInterface, defineInterfaceTemplate, directoryInterface, directoryWatchNever, exportStaticHubSchema, fileManagedIdentityStorage, formatEndpointUri, generateTsContract, generateTsInterface, getDelegationRootIds, getHubEnvironment, getInterfaceTags, getKeyId, hasSignedCapabilityShape, httpRequestListener, identityFilePath, identityInterface, identityStorageInterface, interfaceFromSchema, interfaceTarget, interfaceTemplateArgumentsEquivalent, interfaceTemplateMemberName, interfaceTemplatesEqual, invoke, isApplicationErrorValue, isAssignable, isHubEndpoint, isInterfaceTarget, isNotification, isRequest, isResponse, isRpcFailure, issueCapabilities, issueCapability, jcsCanonicalize, jcsCanonicalizeBytes, keyIdForPrincipal, keyIdForPublicKey, loadOrCreateIdentity, matchParams, matchesJsonSchema, materializeJsonSchema, methodNameToTarget, nodeInterface, normalizeJsonSchema, notificationType, openHubChannel, openStdioChannel, openWebSocket, parseEndpointUri, parseMethodName, parseStaticHubSchema, permissionMatchesTarget, permissionPermits, permits, prefix, prepareCapabilityIssuance, principalForPublicKey, publicKeyForKeyId, readSignature, registerHubPrefix, registerIdentityOnOverlay, registerLazyIdentityOnOverlay, requestType, requireHubEndpoint, requireObjectParams, resolveSigningKey, rpcError, runInitializeHandshake, schemaToZod, schemasInterface, serveOnStdio, serveOverHubWithReconnect, signCapability, signParams, signRpcCall, signedHash, signingDomainValue, signingInput, startEndpoint, streamInterface, stripLinkRpcWireMeta, toMethodSchema, topologyInterface, traceMessageTransport, trafficInterface, validateInterfaceTemplates, validateJsonSchema, verifyCall, verifyRpcCall, withRpcTimeout, withSignature, zParticipantDescriptor, zParticipantDescriptorSource, zRouteClaim, zServiceIdPattern, zTopologyGraph, zTopologyLink, zTopologyLinkEndpoint, zTopologyNode, zTopologyPort, zTopologyTransportEndpoint, zTopologyTransportInfo, zTrafficEvent, zTrafficOverflowEvent, zTrafficTransitEndpoint, zTrafficTransitEvent, zTrafficWatchResult, zodToSvcJsonSchema };
|
|
508
510
|
//# sourceMappingURL=node.d.ts.map
|
package/dist/node.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.ts","names":[],"sources":["../src/node/http.ts","../src/node/endpoint.ts","../src/node/stdio.ts","../src/node/hubClient.ts","../src/node/hubReconnect.ts","../src/node/fileManagedIdentityStorage.ts","../src/node/principal.ts","../src/node/headerDelimitedTransport.ts","../src/node/initialize.ts","../src/node/webSocketClientTransport.ts"],"mappings":";;;;;;;;;;;;;;;iBAiBgB,oBACZ,SAAS,SAAS,SAAS,SAAS,sBAAsB,QAAQ,WAClE,WAAU,0BACX;;;UCNc;;WAEJ;;WAEA;;WAEA,eAAe,YAAY,8BAA8B;;WAEzD,WAAW,OAAO;;UAGd,2BAA2B;WAC/B,SAAS;;WAET,QAAQ;;;;;;EAMjB,eAAe;;UAGF,wBAAwB;;WAE5B;;WAEA,QAAQ;;;;;;;;iBASC,cAAc,SAAS,uBAAuB,QAAQ;;;;;;;;;;;;;;iBChCtD,kBAAkB,kCAAkC,QAAQ;;;;;;iBAyB5D,gBAAgB,QAAQ;;;;;;;;KAYlC,eAAe;;EAEvB,QAAQ,uBAAuB;;EAE/B;;EAEA,eAAe;;iBAGG,iBAAiB;WAAoB;IAAiC,QAAQ;;;;cC7BvF;;cAEA;iBAEG;WAAgC;WAAuC;;iBAQvE,mBAAmB;UAMlB;;WAEJ;;WAEA;;;;;;;WAOA,YAAY;;;;;WAKZ,cAAc;;;;;;;;KASf;EACR,YAAY;EACZ,cAAc;EACd,cAAc;;UAGD;;WAEJ,YAAY,6BAA6B;;;;;;;;WAQzC,KAAK;;WAEL;WACA;;;;;;WAMA,SAAS;;;;;;EAMlB,QAAQ,uBAAuB;;EAE/B;;;;;;;;;;;;iBAakB,aAAa,UAAS,sBAA2B,QAAQ;;UAuB9D;;WAEJ;;;;;;WAMA;;WAEA;;;;;;;;;;;KAYD,aAAa;WACZ;WACA;;;;;EAKT,QAAQ,uBAAuB;;EAE/B;;EAEA,eAAe;;;;;;;iBAQG,eAClB,UAAS,wBACV,QAAQ;;;;;;;;;;;UA2GM;WACJ,QAAQ;WACR;;;;;;;;WAQA;aAAsB,WAAW;aAAsB,SAAS;;;;;;;;WAOhE,wBAAwB;;iBAGf,kBAClB,MAAM,2BACP;UA6Bc;;;;;;WAMJ;;WAEA;;;;;;WAMA;;UAGI;WACJ,WAAW;WACX,SAAS;;WAET,aAAa;;WAEb;;;;;;;;;;;;;;;;iBAiBS,qBAClB,MAAM,8BACP,QAAQ;;;
|
|
1
|
+
{"version":3,"file":"node.d.ts","names":[],"sources":["../src/node/http.ts","../src/node/endpoint.ts","../src/node/stdio.ts","../src/node/hubClient.ts","../src/node/hubReconnect.ts","../src/node/fileManagedIdentityStorage.ts","../src/node/principal.ts","../src/node/headerDelimitedTransport.ts","../src/node/initialize.ts","../src/node/webSocketClientTransport.ts"],"mappings":";;;;;;;;;;;;;;;iBAiBgB,oBACZ,SAAS,SAAS,SAAS,SAAS,sBAAsB,QAAQ,WAClE,WAAU,0BACX;;;UCNc;;WAEJ;;WAEA;;WAEA,eAAe,YAAY,8BAA8B;;WAEzD,WAAW,OAAO;;UAGd,2BAA2B;WAC/B,SAAS;;WAET,QAAQ;;;;;;EAMjB,eAAe;;UAGF,wBAAwB;;WAE5B;;WAEA,QAAQ;;;;;;;;iBASC,cAAc,SAAS,uBAAuB,QAAQ;;;;;;;;;;;;;;iBChCtD,kBAAkB,kCAAkC,QAAQ;;;;;;iBAyB5D,gBAAgB,QAAQ;;;;;;;;KAYlC,eAAe;;EAEvB,QAAQ,uBAAuB;;EAE/B;;EAEA,eAAe;;iBAGG,iBAAiB;WAAoB;IAAiC,QAAQ;;;;cC7BvF;;cAEA;iBAEG;WAAgC;WAAuC;;iBAQvE,mBAAmB;UAMlB;;WAEJ;;WAEA;;;;;;;WAOA,YAAY;;;;;WAKZ,cAAc;;;;;;;;KASf;EACR,YAAY;EACZ,cAAc;EACd,cAAc;;UAGD;;WAEJ,YAAY,6BAA6B;;;;;;;;WAQzC,KAAK;;WAEL;WACA;;;;;;WAMA,SAAS;;;;;;EAMlB,QAAQ,uBAAuB;;EAE/B;;;;;;;;;;;;iBAakB,aAAa,UAAS,sBAA2B,QAAQ;;UAuB9D;;WAEJ;;;;;;WAMA;;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AAY,SAAS;EAOjC;EAIA,MAAM;UAYL;UAmDA;UAOA;;;;UCjKK;WACJ,OAAO,OAAO;WACd,QAAQ,OAAO;WACf;;WAEA,aAAa;;WAEb,QAAQ;WACR;WACA,SAAS;;UAGL;WACJ,WAAW;WACX;;;iBAIS,cAAc,MAAM,uBAAuB,QAAQ;;;UCzBxD;WACJ,UAAU;;;iBAIP,cAAc,aAAa,OAAM,uBAA4B,QAAQ"}
|
package/dist/node.js
CHANGED
|
@@ -390,7 +390,7 @@ async function registerHubPrefix(opts) {
|
|
|
390
390
|
* identities — not for anything that must resist file-system attackers.
|
|
391
391
|
*/
|
|
392
392
|
async function loadOrCreateIdentity(opts) {
|
|
393
|
-
const file =
|
|
393
|
+
const file = identityFilePath(opts);
|
|
394
394
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
395
395
|
try {
|
|
396
396
|
const raw = await fs.readFile(file, "utf8");
|
|
@@ -430,6 +430,10 @@ async function loadOrCreateIdentity(opts) {
|
|
|
430
430
|
file
|
|
431
431
|
};
|
|
432
432
|
}
|
|
433
|
+
/** The on-disk file {@link loadOrCreateIdentity} uses for `opts`, without reading or creating it. */
|
|
434
|
+
function identityFilePath(opts) {
|
|
435
|
+
return opts.file ?? path.join(opts.storeDir ?? _defaultStoreDir(), `${_slotName(opts.id)}.json`);
|
|
436
|
+
}
|
|
433
437
|
async function _writeIdentityFile(file, keypair, wrapKeypair, id) {
|
|
434
438
|
const payload = {
|
|
435
439
|
privateKey: bytesToBase64Url(keypair.privateKey),
|
|
@@ -1270,6 +1274,6 @@ function positiveLimit(value, fallback, name) {
|
|
|
1270
1274
|
return result;
|
|
1271
1275
|
}
|
|
1272
1276
|
//#endregion
|
|
1273
|
-
export { CapBag, CapabilityIssuanceError, Channel, ChannelConnector, DEFAULT_RPC_TIMEOUT_MS, EXTENSION_PREFIX, ErrorCode, HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY, HeaderDelimitedTransport, INITIALIZE_METHOD, INITIALIZE_PROTOCOL_VERSION, INTERFACE_TEMPLATES_EXTENSION, InMemoryManagedIdentity, InMemoryManagedIdentityStorage, InterfaceDefinition, JsonRpcChannel, KEY_ID_PREFIX, KeypairIdentity, KeypairSigningIdentity, LINKRPC_ENDPOINT_VAR, LINKRPC_INITIALIZE_METHOD_ALIAS, LINKRPC_META_KEY, LINKRPC_SIGNATURE_KEY, LINKRPC_TOKEN_VAR, LINKRPC_UNSIGNED_KEY, LinkRpcConnection, MultiplexedTransport, NonCompliantServerError, NotificationType, OneShotCapStaging, PRINCIPAL_PREFIX, Principal, PrincipalWithStore, PublicSigningIdentity, PublicWrappingIdentity, RequestType, RpcError, RpcFailure, STREAM_METHOD, ServiceHandle, SigningSender, StreamControlReason, StreamControlType, StreamDir, TransportPair, WebSocketTransport, applicationError, assertSchemaReferences, attachCapabilities, bareInterfaceTarget, base64UrlToBytes, bytesToBase64Url, capBagFreshAt, capabilityFreshAt, capabilityPermits, componentSchemaName, componentSchemaRef, computeInterfaceHash, connectNdjson, connectToCmdStdio, connectToHub, connectTransports, createHubPrefixClaimer, createManagedIdentity, createManagedPrincipal, createMemoryPrincipal, createSchemaToZod, createSeededMemoryPrincipal, createSeededSigningIdentity, createSelfManagedPrincipal, createSelfManagedPrincipalFromFile, crypto_exports as crypto, defaultInterfaceTarget, defaultsInterface, defineInterface, defineInterfaceTemplate, directoryInterface, directoryWatchNever, exportStaticHubSchema, fileManagedIdentityStorage, formatEndpointUri, generateTsContract, generateTsInterface, getDelegationRootIds, getHubEnvironment, getInterfaceTags, getKeyId, hasSignedCapabilityShape, httpRequestListener, identityInterface, identityStorageInterface, interfaceFromSchema, interfaceTarget, interfaceTemplateArgumentsEquivalent, interfaceTemplateMemberName, interfaceTemplatesEqual, invoke, isApplicationErrorValue, isAssignable, isHubEndpoint, isInterfaceTarget, isNotification, isRequest, isResponse, isRpcFailure, issueCapabilities, issueCapability, jcsCanonicalize, jcsCanonicalizeBytes, keyIdForPrincipal, keyIdForPublicKey, loadOrCreateIdentity, matchParams, matchesJsonSchema, materializeJsonSchema, methodNameToTarget, nodeInterface, normalizeJsonSchema, notificationType, openHubChannel, openStdioChannel, openWebSocket, parseEndpointUri, parseMethodName, parseStaticHubSchema, permissionMatchesTarget, permissionPermits, permits, prefix, prepareCapabilityIssuance, principalForPublicKey, publicKeyForKeyId, readSignature, registerHubPrefix, registerIdentityOnOverlay, registerLazyIdentityOnOverlay, requestType, requireHubEndpoint, requireObjectParams, resolveSigningKey, rpcError, runInitializeHandshake, schemaToZod, schemasInterface, serveOnStdio, serveOverHubWithReconnect, signCapability, signParams, signRpcCall, signedHash, signingDomainValue, signingInput, startEndpoint, streamInterface, stripLinkRpcWireMeta, toMethodSchema, topologyInterface, traceMessageTransport, trafficInterface, validateInterfaceTemplates, validateJsonSchema, verifyCall, verifyRpcCall, withRpcTimeout, withSignature, zParticipantDescriptor, zParticipantDescriptorSource, zRouteClaim, zServiceIdPattern, zTopologyGraph, zTopologyLink, zTopologyLinkEndpoint, zTopologyNode, zTopologyPort, zTopologyTransportEndpoint, zTopologyTransportInfo, zTrafficEvent, zTrafficOverflowEvent, zTrafficTransitEndpoint, zTrafficTransitEvent, zTrafficWatchResult, zodToSvcJsonSchema };
|
|
1277
|
+
export { CapBag, CapabilityIssuanceError, Channel, ChannelConnector, DEFAULT_RPC_TIMEOUT_MS, EXTENSION_PREFIX, ErrorCode, HUBRPC_META_KEY, HUBRPC_SIGNATURE_KEY, HUBRPC_UNSIGNED_KEY, HeaderDelimitedTransport, INITIALIZE_METHOD, INITIALIZE_PROTOCOL_VERSION, INTERFACE_TEMPLATES_EXTENSION, InMemoryManagedIdentity, InMemoryManagedIdentityStorage, InterfaceDefinition, JsonRpcChannel, KEY_ID_PREFIX, KeypairIdentity, KeypairSigningIdentity, LINKRPC_ENDPOINT_VAR, LINKRPC_INITIALIZE_METHOD_ALIAS, LINKRPC_META_KEY, LINKRPC_SIGNATURE_KEY, LINKRPC_TOKEN_VAR, LINKRPC_UNSIGNED_KEY, LinkRpcConnection, MultiplexedTransport, NonCompliantServerError, NotificationType, OneShotCapStaging, PRINCIPAL_PREFIX, Principal, PrincipalWithStore, PublicSigningIdentity, PublicWrappingIdentity, RequestType, RpcError, RpcFailure, STREAM_METHOD, ServiceHandle, SigningSender, StreamControlReason, StreamControlType, StreamDir, TransportPair, WebSocketTransport, applicationError, assertSchemaReferences, attachCapabilities, bareInterfaceTarget, base64UrlToBytes, bytesToBase64Url, capBagFreshAt, capabilityFreshAt, capabilityPermits, componentSchemaName, componentSchemaRef, computeInterfaceHash, connectNdjson, connectToCmdStdio, connectToHub, connectTransports, createHubPrefixClaimer, createManagedIdentity, createManagedPrincipal, createMemoryPrincipal, createSchemaToZod, createSeededMemoryPrincipal, createSeededSigningIdentity, createSelfManagedPrincipal, createSelfManagedPrincipalFromFile, crypto_exports as crypto, defaultInterfaceTarget, defaultsInterface, defineInterface, defineInterfaceTemplate, directoryInterface, directoryWatchNever, exportStaticHubSchema, fileManagedIdentityStorage, formatEndpointUri, generateTsContract, generateTsInterface, getDelegationRootIds, getHubEnvironment, getInterfaceTags, getKeyId, hasSignedCapabilityShape, httpRequestListener, identityFilePath, identityInterface, identityStorageInterface, interfaceFromSchema, interfaceTarget, interfaceTemplateArgumentsEquivalent, interfaceTemplateMemberName, interfaceTemplatesEqual, invoke, isApplicationErrorValue, isAssignable, isHubEndpoint, isInterfaceTarget, isNotification, isRequest, isResponse, isRpcFailure, issueCapabilities, issueCapability, jcsCanonicalize, jcsCanonicalizeBytes, keyIdForPrincipal, keyIdForPublicKey, loadOrCreateIdentity, matchParams, matchesJsonSchema, materializeJsonSchema, methodNameToTarget, nodeInterface, normalizeJsonSchema, notificationType, openHubChannel, openStdioChannel, openWebSocket, parseEndpointUri, parseMethodName, parseStaticHubSchema, permissionMatchesTarget, permissionPermits, permits, prefix, prepareCapabilityIssuance, principalForPublicKey, publicKeyForKeyId, readSignature, registerHubPrefix, registerIdentityOnOverlay, registerLazyIdentityOnOverlay, requestType, requireHubEndpoint, requireObjectParams, resolveSigningKey, rpcError, runInitializeHandshake, schemaToZod, schemasInterface, serveOnStdio, serveOverHubWithReconnect, signCapability, signParams, signRpcCall, signedHash, signingDomainValue, signingInput, startEndpoint, streamInterface, stripLinkRpcWireMeta, toMethodSchema, topologyInterface, traceMessageTransport, trafficInterface, validateInterfaceTemplates, validateJsonSchema, verifyCall, verifyRpcCall, withRpcTimeout, withSignature, zParticipantDescriptor, zParticipantDescriptorSource, zRouteClaim, zServiceIdPattern, zTopologyGraph, zTopologyLink, zTopologyLinkEndpoint, zTopologyNode, zTopologyPort, zTopologyTransportEndpoint, zTopologyTransportInfo, zTrafficEvent, zTrafficOverflowEvent, zTrafficTransitEndpoint, zTrafficTransitEvent, zTrafficWatchResult, zodToSvcJsonSchema };
|
|
1274
1278
|
|
|
1275
1279
|
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":["openNativeWebSocket","crypto.generateX25519Keypair","err","crypto.generateKeypair"],"sources":["../src/node/http.ts","../src/node/ndjsonTransport.ts","../src/node/initialize.ts","../src/node/webSocketClientTransport.ts","../src/node/hubClient.ts","../src/node/stdio.ts","../src/node/endpoint.ts","../src/node/hubReconnect.ts","../src/node/fileManagedIdentityStorage.ts","../src/node/principal.ts","../src/node/headerDelimitedTransport.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse, RequestListener } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { JsonValue } from '../protocol/jsonRpc';\nimport type { HttpHandleOptions } from '../http/server';\n\n/** Shape added by Express/Connect; plain Node requests have none of these. */\ninterface MiddlewareRequest extends IncomingMessage {\n readonly originalUrl?: string;\n readonly body?: unknown;\n}\n\n/**\n * Mount a Web Request/Response handler on Node's HTTP server, or as Express/Connect\n * middleware. Routes are matched against the mount-relative `req.url`; a body already\n * consumed by e.g. `express.json()` is reused instead of re-reading the stream.\n */\nexport function httpRequestListener(\n handle: (request: Request, options: HttpHandleOptions) => Promise<Response>,\n onError: (error: unknown) => void = error => console.error('LinkRPC HTTP request failed', error),\n): RequestListener {\n return (incoming, outgoing) => {\n void handleNodeRequest(incoming, outgoing, handle).catch(error => {\n if (incoming.aborted || outgoing.destroyed) return;\n onError(error);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { 'Content-Type': 'text/plain' });\n outgoing.end('Internal server error');\n } else outgoing.destroy();\n });\n };\n}\n\nasync function handleNodeRequest(\n incoming: MiddlewareRequest, outgoing: ServerResponse,\n handle: (request: Request, options: HttpHandleOptions) => Promise<Response>,\n): Promise<void> {\n const abort = new AbortController();\n const onClose = () => {\n if (!outgoing.writableFinished) abort.abort(new Error('HTTP client disconnected'));\n };\n incoming.once('aborted', onClose);\n outgoing.once('close', onClose);\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(incoming.headers)) {\n if (Array.isArray(value)) for (const item of value) headers.append(name, item);\n else if (value !== undefined) headers.set(name, value);\n }\n const init: RequestInit & { duplex: 'half' } = {\n method: incoming.method, headers, signal: abort.signal, duplex: 'half',\n };\n let parsedBody: JsonValue | undefined;\n if (incoming.method !== 'GET' && incoming.method !== 'HEAD') {\n if (!incoming.readableEnded) {\n init.body = Readable.toWeb(incoming) as ReadableStream<Uint8Array>;\n } else if (incoming.body instanceof Uint8Array) {\n init.body = new Uint8Array(incoming.body);\n } else if (incoming.body !== undefined) {\n // body-parser reports an empty body as `{}`; keep \"no params\" distinct from `{}`.\n if (incoming.headers['content-length'] !== '0') parsedBody = incoming.body as JsonValue;\n } else if (incoming.headers['content-length'] !== '0') {\n throw new Error('Request body was consumed by earlier middleware without exposing req.body');\n }\n }\n const base = `http://${incoming.headers.host ?? 'localhost'}`;\n const request = new Request(new URL(incoming.originalUrl ?? incoming.url ?? '/', base), init);\n const response = await handle(request, { path: new URL(incoming.url ?? '/', base).pathname, parsedBody });\n outgoing.writeHead(response.status, Object.fromEntries(response.headers));\n outgoing.flushHeaders();\n if (response.body) {\n await pipeline(Readable.fromWeb(response.body as import('node:stream/web').ReadableStream<Uint8Array>), outgoing);\n } else outgoing.end();\n } finally {\n incoming.removeListener('aborted', onClose);\n outgoing.removeListener('close', onClose);\n }\n}\n","import type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport type { IMessageTransport } from '../transport/messageTransport';\n\n/**\n * Newline-delimited JSON transport over a Node Readable/Writable pair.\n * One JSON value per line, both directions.\n *\n * Not LSP-style headers — those add no value for a private link between two\n * cooperating processes and require a length-prefixed framer.\n */\nexport class NdjsonTransport implements IMessageTransport {\n private _listener: ((m: JsonRpcMessage) => void) | undefined;\n private readonly _buffer: JsonRpcMessage[] = [];\n private _residual = '';\n private _closed = false;\n private readonly _onDataEvent = (chunk: string) => this._onData(chunk);\n private readonly _onEndEvent = () => this.dispose();\n\n constructor(\n private readonly _input: NodeJS.ReadableStream,\n private readonly _output: NodeJS.WritableStream,\n private readonly _onClose?: () => void,\n ) {\n this._input.setEncoding?.('utf8');\n this._input.on('data', this._onDataEvent);\n this._input.on('end', this._onEndEvent);\n this._input.on('close', this._onEndEvent);\n this._input.on('error', this._onEndEvent);\n if (!Object.is(this._output, this._input)) {\n this._output.on('error', this._onEndEvent);\n }\n }\n\n public send(message: JsonRpcMessage): void {\n if (this._closed) return;\n this._output.write(JSON.stringify(message) + '\\n');\n }\n\n public setListener(listener: ((m: JsonRpcMessage) => void) | undefined): void {\n this._listener = listener;\n if (listener) {\n while (this._buffer.length > 0 && this._listener) {\n const m = this._buffer.shift()!;\n this._listener(m);\n }\n }\n }\n\n public dispose(): void {\n if (this._closed) return;\n this._closed = true;\n this._input.removeListener('data', this._onDataEvent);\n this._input.removeListener('end', this._onEndEvent);\n this._input.removeListener('close', this._onEndEvent);\n this._input.removeListener('error', this._onEndEvent);\n this._output.removeListener('error', this._onEndEvent);\n this._listener = undefined;\n this._buffer.length = 0;\n this._residual = '';\n this._onClose?.();\n }\n\n private _onData(chunk: string): void {\n this._residual += chunk;\n let nl: number;\n while ((nl = this._residual.indexOf('\\n')) >= 0) {\n const line = this._residual.slice(0, nl).trim();\n this._residual = this._residual.slice(nl + 1);\n if (!line) continue;\n let parsed: JsonRpcMessage;\n try {\n parsed = JSON.parse(line) as JsonRpcMessage;\n } catch {\n continue;\n }\n this._deliver(parsed);\n }\n }\n\n private _deliver(m: JsonRpcMessage): void {\n if (this._listener) this._listener(m);\n else this._buffer.push(m);\n }\n}\n","import {\n type IMessageTransport,\n type MessageTransportTrace,\n traceMessageTransport,\n} from '../transport/messageTransport';\nimport { runInitializeHandshake, type InitializeRole } from '../transport/initialize';\nimport { NdjsonTransport } from './ndjsonTransport';\n\nexport * from '../transport/initialize';\n\nexport interface ConnectNdjsonOptions {\n readonly input: NodeJS.ReadableStream;\n readonly output: NodeJS.WritableStream;\n readonly onClose?: () => void;\n /** Complete initialization before exposing the transport. */\n readonly initialize?: InitializeRole;\n /** Includes handshake messages; may contain credentials. */\n readonly trace?: MessageTransportTrace;\n readonly handshakeTimeoutMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ConnectedNdjson {\n readonly transport: IMessageTransport;\n readonly token?: string;\n}\n\n/** Construct NDJSON and complete the shared transport initialization handshake. */\nexport async function connectNdjson(opts: ConnectNdjsonOptions): Promise<ConnectedNdjson> {\n const role = opts.initialize;\n const closed = new AbortController();\n const baseTransport = new NdjsonTransport(opts.input, opts.output, () => {\n try {\n opts.onClose?.();\n } finally {\n closed.abort(new Error('hubrpc::initialize: transport closed during handshake'));\n }\n });\n const transport = opts.trace === undefined\n ? baseTransport\n : traceMessageTransport(baseTransport, opts.trace);\n if (!role) return { transport };\n try {\n const { token } = await runInitializeHandshake(transport, role, {\n handshakeTimeoutMs: opts.handshakeTimeoutMs,\n signal: opts.signal ? AbortSignal.any([closed.signal, opts.signal]) : closed.signal,\n });\n return { transport, ...(token !== undefined ? { token } : {}) };\n } catch (err) {\n transport.dispose();\n throw err;\n }\n}\n","export { WebSocketTransport } from '../transport/webSocketTransport';\nimport { openWebSocket as openNativeWebSocket } from '../transport/webSocketTransport';\n\nexport interface OpenWebSocketOptions {\n readonly headers?: Record<string, string>;\n}\n\n/** Node-only header extension. The web entry exposes the standard overload. */\nexport function openWebSocket(url: string, opts: OpenWebSocketOptions = {}): Promise<WebSocket> {\n if (!opts.headers || Object.keys(opts.headers).length === 0) return openNativeWebSocket(url);\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(url, { headers: opts.headers } as unknown as string[]);\n const onOpen = () => {\n ws.removeEventListener('error', onError);\n resolve(ws);\n };\n const onError = () => {\n ws.removeEventListener('open', onOpen);\n reject(new Error('WebSocket connection failed'));\n };\n ws.addEventListener('open', onOpen, { once: true });\n ws.addEventListener('error', onError, { once: true });\n });\n}\n","import * as fs from 'node:fs/promises';\nimport * as net from 'node:net';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { Channel } from '../connection/channel';\nimport { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport {\n OneShotCapStaging,\n Principal, SigningSender,\n type SigningCallCtx,\n type SigningSenderConfig\n} from '../identity/signingSender';\nimport type { SignedCapability } from '../identity/capability';\nimport {\n base64UrlToBytes,\n bytesToBase64Url,\n type Keypair,\n type PrincipalId,\n principalForPublicKey,\n type X25519Keypair,\n} from '../crypto/cryptoProvider';\nimport * as crypto from '../crypto/crypto';\nimport { signParams } from '../identity/metaEnvelope';\nimport { KeypairSigningIdentity } from '../identity/identity';\nimport type { JsonValue } from '../protocol/jsonValue';\nimport type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport { sha256 } from '../crypto/sha256';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport { connectNdjson, runInitializeHandshake } from './initialize';\nimport { openWebSocket, WebSocketTransport } from './webSocketClientTransport';\nimport { IDisposable } from '../disposable';\nimport { Hub, hubFromConnection } from '../hub/client/hubFacade';\n\n/** Env var the hub publishes for its endpoint (named pipe / UDS path). */\nexport const LINKRPC_ENDPOINT_VAR = 'LINKRPC_ENDPOINT';\n/** Env var the hub publishes for its shared attribution token. */\nexport const LINKRPC_TOKEN_VAR = 'LINKRPC_TOKEN';\n\nexport function getHubEnvironment(): { readonly endpoint: string | undefined; readonly token: string | undefined } {\n const endpoint = process.env[LINKRPC_ENDPOINT_VAR];\n if (endpoint !== undefined) return { endpoint, token: process.env[LINKRPC_TOKEN_VAR] };\n const legacyEndpoint = process.env.HUBRPC_ENDPOINT;\n if (legacyEndpoint !== undefined) return { endpoint: legacyEndpoint, token: process.env.HUBRPC_TOKEN };\n return { endpoint: undefined, token: process.env[LINKRPC_TOKEN_VAR] ?? process.env.HUBRPC_TOKEN };\n}\n\nexport function requireHubEndpoint(endpoint: string | undefined = getHubEnvironment().endpoint): string {\n const value = endpoint?.trim();\n if (!value) throw new Error('LINKRPC_ENDPOINT (or HUBRPC_ENDPOINT) is not set; specify an endpoint.');\n return value;\n}\n\nexport interface ConnectToHubOptions {\n /** Defaults to LINKRPC_ENDPOINT, or the legacy HUBRPC_ENDPOINT. */\n readonly endpoint?: string;\n /** Defaults to the token from the selected environment variable family. */\n readonly token?: string;\n /**\n * Initial {@link Principal} (identity + persistent caps) for outbound\n * calls. Stored on the returned handle's {@link HubClientHandle.signing}\n * config; mutate that later to install or swap. `undefined` leaves the\n * connection unsigned (plain JSON-RPC) until a principal is installed.\n */\n readonly principal?: Principal;\n /**\n * Initial one-shot capability staging policy. Same lifecycle as\n * {@link principal}; drained per outbound signed call.\n */\n readonly oneShotCaps?: OneShotCapStaging;\n}\n\n/**\n * Mutable signing config consulted per-call by the {@link SigningSender}\n * wrapping a {@link HubClientHandle.connection}. Mutating either field\n * takes effect on the next outbound call. No setter on the sender\n * itself — it is a plain caller-owned {@link SigningSenderConfig}.\n */\nexport type HubSigningHolder = {\n principal?: Principal;\n capProvider?: SigningSenderConfig['capProvider'];\n oneShotCaps?: OneShotCapStaging;\n};\n\nexport interface HubClientHandle {\n /** Full linkrpc connection wrapping the same transport. */\n readonly connection: LinkRpcConnection<undefined, SigningCallCtx>;\n /**\n * Façade over the hub's own serviceId-routed services (`hubGrantedServiceId`,\n * `hubAccess`, …) on this {@link connection}. Use it to read connection\n * facts ({@link Hub.getConnectionInfo}) or claim this connection's granted\n * serviceId namespace ({@link Hub.claimGrantedServiceIdNamespace}) without\n * hand-routing the interface clients.\n */\n readonly hub: Hub;\n /** Configured endpoint + token (in case the caller defaulted from env). */\n readonly endpoint: string;\n readonly token: string;\n /**\n * Mutable signing config. Starts empty (every call goes out\n * unsigned). `installManagedIdentitySigner` and `setupHubSigning`\n * populate this; user code can also drive it directly.\n */\n readonly signing: HubSigningHolder;\n /**\n * Register a callback that fires when the underlying socket closes\n * (peer end, error, or explicit {@link close}). Fires at most once.\n * Returns an unsubscribe function.\n */\n onClose(listener: () => void): IDisposable;\n /** Close the underlying socket and tear everything down. */\n close(): void;\n}\n\n/**\n * Open a connection to a running linkrpc hub. Reads `LINKRPC_ENDPOINT` and\n * `LINKRPC_TOKEN` (or the legacy HUBRPC pair) from the environment unless overridden. Sends the single-\n * line `{\"hello\":1,\"token\":\"...\"}` preamble that the hub's socket server\n * requires, then wraps the socket in an `LinkRpcConnection`.\n *\n * Throws if env vars are missing, if the socket cannot be opened, or if the\n * hub refuses the preamble (the socket simply closes — callers should treat\n * an immediate close of the channel as an auth failure).\n */\nexport async function connectToHub(options: ConnectToHubOptions = {}): Promise<HubClientHandle> {\n const hubChannel = await openHubChannel(options);\n const signing: HubSigningHolder = {\n principal: options.principal,\n oneShotCaps: options.oneShotCaps,\n };\n const channel = SigningSender.wrapChannel(hubChannel, signing);\n const connection = new LinkRpcConnection(channel);\n return {\n connection,\n hub: hubFromConnection(connection),\n endpoint: hubChannel.endpoint,\n token: hubChannel.token,\n signing,\n onClose: hubChannel.onClose,\n close: () => {\n connection.close();\n hubChannel.close();\n },\n };\n}\n\n/** Options for {@link openHubChannel}. Subset of {@link ConnectToHubOptions}. */\nexport interface OpenHubChannelOptions {\n /** Defaults to LINKRPC_ENDPOINT, or the legacy HUBRPC_ENDPOINT. */\n readonly endpoint?: string;\n /**\n * Defaults to the selected environment family's token, or `''` when unset. The token\n * is sent in the hello preamble; provenance-authenticated hubs (hubv2)\n * ignore it, so an empty token is valid there.\n */\n readonly token?: string;\n /** Queue incoming requests until resumeRequests; outbound responses remain live. */\n readonly deferRequests?: boolean;\n}\n\n/**\n * A raw, unsigned hub channel: the socket transport wrapped only in a\n * {@link JsonRpcChannel}, with no signing applied. It *is* a {@link Channel}\n * (so it plugs straight into {@link SigningSender.wrapChannel} /\n * `new LinkRpcConnection`), augmented with the hub endpoint/token and the\n * socket lifecycle. Identity/signing is composed on top by the caller;\n * {@link connectToHub} is the batteries-included version that adds a\n * mutable signing holder.\n */\nexport type HubChannel = Channel<undefined, unknown> & {\n readonly endpoint: string;\n readonly token: string;\n /**\n * Register a callback that fires when the socket closes. Fires at most\n * once. Returns an unsubscribe function.\n */\n onClose(listener: () => void): IDisposable;\n /** Close the underlying socket. */\n close(): void;\n /** Release incoming requests after installing application handlers. */\n resumeRequests(methods?: readonly string[]): void;\n};\n\n/**\n * Open the hub socket and send the preamble, returning the raw\n * {@link HubChannel} without any signing. Use this when you want to\n * compose identity yourself; otherwise prefer {@link connectToHub}.\n */\nexport async function openHubChannel(\n options: OpenHubChannelOptions = {},\n): Promise<HubChannel> {\n const environment = getHubEnvironment();\n const endpoint = requireHubEndpoint(options.endpoint ?? environment.endpoint);\n const token = options.token ?? environment.token ?? '';\n\n const closeListeners = new Set<() => void>();\n let closed = false;\n let closeChannel: (() => void) | undefined;\n const fireClose = () => {\n if (closed) return;\n closed = true;\n closeChannel?.();\n for (const l of closeListeners) {\n try {\n l();\n } catch { /* ignore */ }\n }\n closeListeners.clear();\n };\n\n const { transport, destroy } = await _openHubTransport(endpoint, token, fireClose);\n const rpc = JsonRpcChannel.createWithClose(transport, { deferRequests: options.deferRequests });\n closeChannel = rpc.close;\n if (closed) rpc.close();\n return Object.assign(rpc.channel, {\n endpoint,\n token,\n resumeRequests: rpc.resumeRequests,\n onClose: (listener: () => void) => {\n if (closed) {\n queueMicrotask(listener);\n return { dispose: () => { } };\n }\n closeListeners.add(listener);\n return { dispose: () => closeListeners.delete(listener) };\n },\n close: () => {\n destroy();\n fireClose();\n },\n });\n}\n\n/** True for `ws://` / `wss://` endpoints (case-insensitive). */\nfunction _isWebSocketEndpoint(endpoint: string): boolean {\n return /^wss?:\\/\\//i.test(endpoint);\n}\n\n/**\n * Open the underlying transport for {@link openHubChannel}, picking the\n * scheme from the endpoint:\n * - `ws://` / `wss://` → WebSocket; the token is presented via the\n * `hubrpc::initialize` handshake (browsers cannot set request headers).\n * - anything else → named pipe / UDS; the token is presented via the\n * `hubrpc::initialize` handshake the socket server requires.\n *\n * `onClose` fires once when the peer ends the transport.\n */\nasync function _openHubTransport(\n endpoint: string,\n token: string,\n onClose: () => void,\n): Promise<{ transport: IMessageTransport<JsonRpcMessage, JsonRpcMessage>; destroy: () => void; }> {\n if (_isWebSocketEndpoint(endpoint)) {\n const ws = await openWebSocket(endpoint);\n const closed = new AbortController();\n const transport = new WebSocketTransport(ws, () => {\n closed.abort(new Error('hubrpc::initialize: transport closed during handshake'));\n onClose();\n });\n const destroy = () => {\n try {\n ws.close();\n } catch { /* ignore */ }\n };\n try {\n await runInitializeHandshake(transport, { kind: 'client', token }, { signal: closed.signal });\n } catch (err) {\n transport.dispose();\n destroy();\n throw err;\n }\n return { transport, destroy };\n }\n const socket = await _openSocket(endpoint);\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => {\n socket.destroy();\n onClose();\n },\n initialize: { kind: 'client', token },\n });\n return { transport, destroy: () => socket.destroy() };\n}\n\n/**\n * Send the `linkrpc.hub::hubServiceIdRegistry::registerServiceId` call on an open\n * hub connection. In `openMode` the hub accepts the unsigned call directly —\n * pass no `identity`. Outside `openMode` the caller must sign the params\n * with their `identity` keypair (via `signParams`) and present a\n * capability that authorizes the claim — unless the signer is already an\n * admin on the hub, in which case `capabilities` may be omitted.\n *\n * Resolves once the hub has registered the prefix; rejects on denial.\n */\nexport interface RegisterHubPrefixOptions {\n readonly handle: HubClientHandle;\n readonly prefix: string;\n /**\n * Caller's signing identity. Required when the hub is not in openMode.\n * The `principal` must encode the `publicKey` (round-tripped through\n * `principalForPublicKey`). Bound to this transport on first successful\n * `register` — subsequent calls on the same socket may not switch\n * identity.\n */\n readonly identity?: { readonly principal: PrincipalId; readonly keypair: Keypair; };\n /**\n * Capabilities to present. Each must be issued (directly or\n * transitively) by an admin and permit\n * `<prefix>::hubServiceIdRegistry::registerServiceId`. Omit when the signer\n * is already an admin.\n */\n readonly capabilities?: readonly SignedCapability[];\n}\n\nexport async function registerHubPrefix(\n opts: RegisterHubPrefixOptions,\n): Promise<void> {\n let params: Record<string, unknown>;\n if (opts.identity) {\n const signer = new KeypairSigningIdentity(\n opts.identity.principal,\n opts.identity.keypair.privateKey,\n );\n params = await signParams({\n method: 'hubServiceIdRegistry::registerServiceId',\n params: { requestedPrefix: opts.prefix },\n signingIdentity: signer,\n ...(opts.capabilities && opts.capabilities.length > 0 ?\n { capabilities: [...opts.capabilities] } :\n {}),\n });\n } else {\n if (opts.capabilities && opts.capabilities.length > 0) {\n throw new Error('registerHubPrefix: capabilities require identity to be set');\n }\n params = { requestedPrefix: opts.prefix };\n }\n await opts.handle.connection.channel.sendRequest(\n 'hubServiceIdRegistry::registerServiceId',\n params as JsonValue,\n );\n}\n\n// ---- Identity persistence -----------------------------------------------\n\nexport interface LoadOrCreateIdentityOptions {\n /**\n * Stable string that identifies this identity slot. Typically the calling\n * module's `import.meta.filename` — each service then automatically gets\n * its own slot.\n */\n readonly id: string;\n /** Override the storage directory (defaults to a per-user folder). */\n readonly storeDir?: string;\n /**\n * Use this exact on-disk path for the keypair file instead of deriving one\n * from `id` (and `storeDir`). Takes precedence over `storeDir`; the parent\n * directory is created if missing.\n */\n readonly file?: string;\n}\n\nexport interface PersistedIdentity {\n readonly principal: PrincipalId;\n readonly keypair: Keypair;\n /** Long-lived X25519 keypair used for HPKE wrap/unwrap. */\n readonly wrapKeypair: X25519Keypair;\n /** Absolute path of the on-disk file. */\n readonly file: string;\n}\n\n/**\n * Load the Ed25519 + X25519 keypairs for `id` from disk, or\n * generate-and-persist them on first call. The slot is keyed by SHA-256 of\n * `id` so callers can pass any stable string (e.g. `import.meta.filename`)\n * without worrying about filesystem-safe characters.\n *\n * Identity files written before wrapping support carried only the Ed25519\n * keypair; on load they are transparently migrated — the Ed25519 keypair\n * (and therefore the `nodeId`) is preserved and a fresh X25519 wrap keypair\n * is generated and written back.\n *\n * NOTE: keys are stored unencrypted. Only suitable for local development\n * identities — not for anything that must resist file-system attackers.\n */\nexport async function loadOrCreateIdentity(\n opts: LoadOrCreateIdentityOptions,\n): Promise<PersistedIdentity> {\n const file = opts.file ??\n path.join(opts.storeDir ?? _defaultStoreDir(), `${_slotName(opts.id)}.json`);\n await fs.mkdir(path.dirname(file), { recursive: true });\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as {\n privateKey?: string;\n publicKey?: string;\n wrapPrivateKey?: string;\n wrapPublicKey?: string;\n };\n if (typeof parsed.privateKey !== 'string' || typeof parsed.publicKey !== 'string') {\n throw new Error('malformed identity file');\n }\n const privateKey = base64UrlToBytes(parsed.privateKey);\n const publicKey = base64UrlToBytes(parsed.publicKey);\n const keypair: Keypair = { privateKey, publicKey };\n let wrapKeypair: X25519Keypair;\n if (typeof parsed.wrapPrivateKey === 'string' && typeof parsed.wrapPublicKey === 'string') {\n wrapKeypair = {\n privateKey: base64UrlToBytes(parsed.wrapPrivateKey),\n publicKey: base64UrlToBytes(parsed.wrapPublicKey),\n };\n } else {\n // Pre-wrapping identity file: keep the Ed25519 keypair (stable\n // principal) and add a fresh X25519 wrap keypair, written back.\n wrapKeypair = await crypto.generateX25519Keypair();\n await _writeIdentityFile(file, keypair, wrapKeypair, opts.id);\n }\n return { keypair, wrapKeypair, principal: principalForPublicKey(publicKey), file };\n } catch (e: unknown) {\n const err = e as NodeJS.ErrnoException;\n if (err.code !== 'ENOENT') throw e;\n }\n const keypair = await crypto.generateKeypair();\n const wrapKeypair = await crypto.generateX25519Keypair();\n await _writeIdentityFile(file, keypair, wrapKeypair, opts.id);\n return { keypair, wrapKeypair, principal: principalForPublicKey(keypair.publicKey), file };\n}\n\nasync function _writeIdentityFile(\n file: string,\n keypair: Keypair,\n wrapKeypair: X25519Keypair,\n id: string,\n): Promise<void> {\n const payload = {\n privateKey: bytesToBase64Url(keypair.privateKey),\n publicKey: bytesToBase64Url(keypair.publicKey),\n wrapPrivateKey: bytesToBase64Url(wrapKeypair.privateKey),\n wrapPublicKey: bytesToBase64Url(wrapKeypair.publicKey),\n id,\n };\n await fs.writeFile(file, JSON.stringify(payload, null, 2), { mode: 0o600 });\n}\n\nfunction _defaultStoreDir(): string {\n const home = os.homedir();\n if (process.platform === 'win32') {\n const appdata = process.env.APPDATA;\n if (appdata) return path.join(appdata, 'hubrpc', 'identities');\n return path.join(home, 'AppData', 'Roaming', 'hubrpc', 'identities');\n }\n if (process.platform === 'darwin') {\n return path.join(home, 'Library', 'Application Support', 'hubrpc', 'identities');\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg) return path.join(xdg, 'hubrpc', 'identities');\n return path.join(home, '.config', 'hubrpc', 'identities');\n}\n\nfunction _slotName(id: string): string {\n const digest = sha256(new TextEncoder().encode(id));\n let out = '';\n for (let i = 0; i < 16; i++) {\n out += digest[i].toString(16).padStart(2, '0');\n }\n return out;\n}\n\n// ---- Capability persistence ---------------------------------------------\n\n/**\n * On-disk capability cache, keyed by `(identity slot, prefix)`. Lives next\n * to the identity files so the lifecycle is the same: lose the dir, get a\n * fresh prompt next time. Caps are not secret; the cache is read/write\n * mode 0o600 anyway for consistency.\n */\nexport interface PersistedRegisterCap {\n readonly capability: SignedCapability;\n /** Absolute path of the on-disk file. */\n readonly file: string;\n}\n\nexport async function loadPersistedRegisterCap(args: {\n readonly identityId: string;\n readonly prefix: string;\n readonly storeDir?: string;\n}): Promise<PersistedRegisterCap | undefined> {\n const file = _capFilePath(args.identityId, args.prefix, args.storeDir);\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as { capability?: SignedCapability; };\n if (!parsed.capability) return undefined;\n // Drop the cap if it expired so the caller re-acquires.\n if (\n parsed.capability.expiresAtMs !== undefined &&\n parsed.capability.expiresAtMs < Date.now()\n ) {\n return undefined;\n }\n return { capability: parsed.capability, file };\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;\n return undefined;\n }\n}\n\nexport async function persistRegisterCap(args: {\n readonly identityId: string;\n readonly prefix: string;\n readonly capability: SignedCapability;\n readonly storeDir?: string;\n}): Promise<string> {\n const file = _capFilePath(args.identityId, args.prefix, args.storeDir);\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.writeFile(\n file,\n JSON.stringify({ capability: args.capability }, null, 2),\n { mode: 0o600 },\n );\n return file;\n}\n\nfunction _capFilePath(\n identityId: string,\n prefix: string,\n storeDir: string | undefined,\n): string {\n const dir = storeDir ?? _defaultStoreDir();\n const slot = _slotName(identityId);\n return path.join(dir, `${slot}-cap-${_slotName(prefix)}.json`);\n}\n\nfunction _openSocket(endpoint: string): Promise<net.Socket> {\n return new Promise((resolve, reject) => {\n const socket = net.createConnection(endpoint);\n const onError = (err: Error) => {\n socket.removeListener('connect', onConnect);\n reject(err);\n };\n const onConnect = () => {\n socket.removeListener('error', onError);\n resolve(socket);\n };\n socket.once('error', onError);\n socket.once('connect', onConnect);\n });\n}\n","import { type ChildProcess, spawn } from 'node:child_process';\nimport { connectNdjson } from './initialize';\nimport type { Channel } from '../connection/channel';\nimport type { IDisposable } from '../disposable';\nimport { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\n\n/**\n * Spawn a child process and connect to its stdio as a linkrpc connection.\n *\n * Pass a single command line (split on whitespace) or an array `[cmd, ...args]`.\n * The child's stderr is piped to the parent's stderr so logs surface naturally.\n *\n * @example\n * const c = await connectToCmdStdio(\"node ./ghConnector.js\");\n * const gh = c.get(ghInterface);\n * await gh.createIssue({ title: \"...\" });\n */\nexport async function connectToCmdStdio(cmd: string | readonly string[]): Promise<LinkRpcConnection> {\n const parts = typeof cmd === 'string' ? cmd.split(/\\s+/).filter(Boolean) : [...cmd];\n if (parts.length === 0) throw new Error('connectToCmdStdio: empty command');\n const [bin, ...args] = parts;\n const child: ChildProcess = spawn(bin, args, {\n stdio: ['pipe', 'pipe', 'inherit'],\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connectToCmdStdio: child has no stdio');\n }\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => {\n if (!child.killed) child.kill();\n },\n });\n return LinkRpcConnection.fromTransport(transport);\n}\n\n/**\n * For the child side: a linkrpc connection over this process's stdin/stdout.\n * The child MUST NOT write user output to stdout — only RPC messages — or\n * the parent's parser will choke.\n */\nexport async function serveOnStdio(): Promise<LinkRpcConnection> {\n const { transport } = await connectNdjson({ input: process.stdin, output: process.stdout });\n return LinkRpcConnection.fromTransport(transport);\n}\n\n/**\n * A raw, unsigned channel over this process's stdin/stdout — the stdio\n * counterpart to `openHubChannel`. It *is* a {@link Channel} (so it plugs\n * straight into {@link SigningSender.wrapChannel} / `new LinkRpcConnection`),\n * augmented with a close signal for stdin end. Use {@link serveOnStdio}\n * instead when no signing is needed.\n */\nexport type StdioChannel = Channel<undefined, unknown> & {\n /** Fires once when stdin ends/closes. Returns a disposable to unsubscribe. */\n onClose(listener: () => void): IDisposable;\n /** Detach from stdin/stdout without closing these process-owned streams. */\n close(): void;\n /** Release incoming requests after installing application handlers. */\n resumeRequests(methods?: readonly string[]): void;\n};\n\nexport async function openStdioChannel(options: { readonly deferRequests?: boolean } = {}): Promise<StdioChannel> {\n const closeListeners = new Set<() => void>();\n let closed = false;\n let closeChannel: (() => void) | undefined;\n const fireClose = () => {\n if (closed) return;\n closed = true;\n closeChannel?.();\n if (process.stdin.listenerCount('data') === 0) process.stdin.pause();\n for (const l of closeListeners) {\n try {\n l();\n } catch { /* ignore */ }\n }\n closeListeners.clear();\n };\n const { transport } = await connectNdjson({\n input: process.stdin, output: process.stdout, onClose: fireClose,\n });\n const rpc = JsonRpcChannel.createWithClose(transport, options);\n closeChannel = rpc.close;\n if (closed) rpc.close();\n\n return Object.assign(rpc.channel, {\n resumeRequests: rpc.resumeRequests,\n close: fireClose,\n onClose: (listener: () => void) => {\n if (closed) {\n queueMicrotask(listener);\n return { dispose: () => { } };\n }\n closeListeners.add(listener);\n return { dispose: () => closeListeners.delete(listener) };\n },\n });\n}\n","import { timingSafeEqual } from 'node:crypto';\nimport * as http from 'node:http';\nimport * as net from 'node:net';\nimport type { WebSocketServer } from 'ws';\nimport type { Channel } from '../connection/channel';\nimport { formatEndpointUri, parseEndpointUri, type SocketEndpoint, type WsEndpoint } from '../connection/endpointUri';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport type { IDisposable } from '../disposable';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport { getHubEnvironment, requireHubEndpoint, openHubChannel } from './hubClient';\nimport { connectNdjson, runInitializeHandshake } from './initialize';\nimport { openStdioChannel } from './stdio';\nimport { WebSocketTransport } from './webSocketClientTransport';\n\nexport interface StartEndpointOptions {\n /** Overrides LINKRPC_ENDPOINT / HUBRPC_ENDPOINT. Use `listen:` to accept rather than dial. */\n readonly endpoint?: string;\n /** Overrides the URI token, then the selected environment token. Required for listeners. */\n readonly token?: string;\n /** Install services/signing. Inbound requests wait for completion; outbound calls remain live. */\n readonly onConnection: (connection: EndpointConnection) => void | Promise<void>;\n /** Listener peer/transport failures. Defaults to process.emitWarning. Must not throw. */\n readonly onError?: (error: Error) => void;\n}\n\nexport interface EndpointConnection extends IDisposable {\n readonly channel: Channel<undefined, unknown>;\n /** Resolves on peer disconnect or disposal; pending RPC calls are rejected. */\n readonly closed: Promise<void>;\n /**\n * Release selected non-streaming bootstrap requests during onConnection.\n * Without arguments, release all requests. Notifications and input streams\n * remain queued until all requests are released.\n */\n resumeRequests(methods?: readonly string[]): void;\n}\n\nexport interface StartedEndpoint extends IDisposable {\n /** Dialable bound address (including the assigned port), without credentials; or `stdio:`. */\n readonly endpoint: string;\n /** Resolves after shutdown. Listeners stay open until disposed or a server error. */\n readonly closed: Promise<void>;\n}\n\n/**\n * Start a Node application's RPC endpoint without imposing argument parsing,\n * signing, service registration, signal handlers, or process-exit policy.\n * Startup and initial onConnection failures reject. A listener isolates failed\n * peers, reports them via onError, and continues accepting other connections.\n */\nexport async function startEndpoint(options: StartEndpointOptions): Promise<StartedEndpoint> {\n const environment = getHubEnvironment();\n const configured = requireHubEndpoint(options.endpoint ?? environment.endpoint);\n if (configured === 'stdio' || configured === 'stdio:') {\n return _startSingle('stdio:', await openStdioChannel({ deferRequests: true }), options);\n }\n const listening = configured.startsWith('listen:');\n const target = parseEndpointUri(listening ? configured.slice('listen:'.length) : configured);\n if (target.kind !== 'socket' && target.kind !== 'ws') {\n throw new Error('startEndpoint supports stdio, socket, and LinkRPC WebSocket endpoints only.');\n }\n const token = options.token ?? target.token ?? environment.token ?? '';\n const endpoint = formatEndpointUri({ ...target, token: undefined });\n if (!listening) {\n const channel = await openHubChannel({\n endpoint: target.kind === 'socket' ? target.path : target.url, token, deferRequests: true,\n });\n return _startSingle(endpoint, channel, options);\n }\n if (!token) throw new Error('Listening endpoints require a nonempty token.');\n return EndpointListener.start(target, token, options);\n}\n\nasync function _startSingle(\n endpoint: string,\n source: Channel<undefined, unknown> & {\n close(): void;\n resumeRequests(methods?: readonly string[]): void;\n onClose(listener: () => void): IDisposable;\n },\n options: StartEndpointOptions,\n): Promise<StartedEndpoint> {\n let finish!: () => void;\n const closed = new Promise<void>(resolve => { finish = resolve; });\n const subscription = source.onClose(finish);\n void closed.then(() => subscription.dispose());\n const connection: EndpointConnection = {\n channel: source, closed, dispose: () => source.close(), resumeRequests: source.resumeRequests,\n };\n try {\n await options.onConnection(connection);\n source.resumeRequests();\n return { endpoint, closed, dispose: connection.dispose };\n } catch (error) {\n connection.dispose();\n await closed;\n throw error;\n }\n}\n\nclass EndpointListener implements StartedEndpoint {\n private readonly _peers = new Set<ListenerPeer>();\n private readonly _tasks = new Set<Promise<void>>();\n private readonly _sockets = new Set<net.Socket>();\n private _disposed = false;\n private _finish!: () => void;\n public readonly closed = new Promise<void>(resolve => { this._finish = resolve; });\n\n private constructor(\n public readonly endpoint: string,\n private readonly _server: net.Server,\n private readonly _token: string,\n private readonly _options: StartEndpointOptions,\n private readonly _webSocketServer?: WebSocketServer,\n ) {\n _server.on('connection', socket => {\n this._sockets.add(socket);\n socket.on('close', () => this._sockets.delete(socket));\n if (this._disposed) socket.destroy();\n });\n _server.on('error', error => {\n this._report(error);\n this.dispose();\n });\n }\n\n public static async start(\n target: SocketEndpoint | WsEndpoint,\n token: string,\n options: StartEndpointOptions,\n ): Promise<EndpointListener> {\n if (target.kind === 'socket') {\n const server = net.createServer();\n await _listen(server, () => server.listen(target.path));\n const owner = new EndpointListener(formatEndpointUri({ ...target, token: undefined }), server, token, options);\n server.on('connection', socket => {\n const peer = owner._createPeer(() => socket.destroy());\n socket.on('error', error => owner._peerError(peer, error));\n socket.on('close', () => peer.dispose());\n owner._accept(peer, () => connectNdjson({\n input: socket, output: socket,\n onClose: () => peer.dispose(),\n signal: peer.signal,\n initialize: { kind: 'server', isTokenAccepted: async candidate => owner._accepts(candidate) },\n }).then(result => result.transport));\n });\n return owner;\n }\n const url = new URL(target.url);\n if (url.protocol !== 'ws:') throw new Error('Listening WebSockets require ws:; terminate TLS at a reverse proxy.');\n if (url.username || url.password || url.search || url.hash) {\n throw new Error('Listening WebSocket URLs cannot contain credentials, query parameters, or fragments.');\n }\n const { WebSocketServer } = await import('ws');\n const server = http.createServer((_request, response) => {\n response.writeHead(426);\n response.end('WebSocket upgrade required');\n });\n await _listen(server, () => server.listen(Number(url.port || 80), url.hostname.replace(/^\\[|\\]$/g, '')));\n const webSockets = new WebSocketServer({\n server,\n path: url.pathname,\n maxPayload: 16 * 1024 * 1024,\n });\n const address = server.address();\n if (!address || typeof address === 'string') {\n server.close();\n throw new Error('WebSocket listener did not bind a TCP address.');\n }\n url.port = String(address.port);\n const owner = new EndpointListener(url.toString(), server, token, options, webSockets);\n webSockets.on('error', error => {\n owner._report(error);\n owner.dispose();\n });\n webSockets.on('connection', socket => {\n const peer = owner._createPeer(() => socket.terminate());\n socket.on('error', error => owner._peerError(peer, error));\n socket.on('close', () => peer.dispose());\n const transport = new WebSocketTransport(socket, () => peer.dispose());\n peer.setTransport(transport);\n owner._accept(peer, async () => {\n await runInitializeHandshake(transport, {\n kind: 'server', isTokenAccepted: async candidate => owner._accepts(candidate),\n }, { signal: peer.signal });\n return transport;\n });\n });\n return owner;\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n for (const peer of this._peers) peer.dispose();\n for (const socket of this._sockets) socket.destroy();\n const webSocketsClosed = this._webSocketServer\n ? new Promise<void>(resolve => this._webSocketServer!.close(() => resolve()))\n : Promise.resolve();\n this._server.close(() => {\n void Promise.all([...this._tasks, webSocketsClosed]).then(() => this._finish());\n });\n }\n\n private _accepts(candidate: string | undefined): boolean {\n if (typeof candidate !== 'string') return false;\n const expected = Buffer.from(this._token);\n const actual = Buffer.from(candidate);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n }\n\n private _createPeer(closeSocket: () => void): ListenerPeer {\n const peer = new ListenerPeer(closeSocket);\n this._peers.add(peer);\n void peer.closed.then(() => this._peers.delete(peer));\n if (this._disposed) peer.dispose();\n return peer;\n }\n\n private _accept(peer: ListenerPeer, open: () => Promise<IMessageTransport>): void {\n const task = (async () => {\n try {\n const transport = await open();\n peer.setTransport(transport);\n if (this._disposed || peer.signal.aborted) return;\n const connection = peer.connect();\n await this._options.onConnection(connection);\n peer.resumeRequests();\n } catch (error) {\n const report = !this._disposed;\n peer.dispose();\n if (report) this._report(error);\n }\n })();\n this._tasks.add(task);\n void task.then(() => this._tasks.delete(task));\n }\n\n private _peerError(peer: ListenerPeer, error: Error): void {\n if (!peer.signal.aborted && !this._disposed) this._report(error);\n peer.dispose();\n }\n\n private _report(error: unknown): void {\n const report = this._options.onError ?? (error => process.emitWarning(error));\n try {\n report(error instanceof Error ? error : new Error(String(error)));\n } catch (error) {\n process.emitWarning(new Error('startEndpoint onError callback threw', { cause: error }));\n }\n }\n}\n\nclass ListenerPeer implements IDisposable {\n private readonly _abort = new AbortController();\n public readonly signal = this._abort.signal;\n private _finish!: () => void;\n public readonly closed = new Promise<void>(resolve => { this._finish = resolve; });\n private _transport: IMessageTransport | undefined;\n private _closeChannel: (() => void) | undefined;\n private _resumeRequests: (() => void) | undefined;\n\n constructor(private readonly _closeSocket: () => void) {}\n\n public setTransport(transport: IMessageTransport): void {\n this._transport = transport;\n if (this.signal.aborted) transport.dispose();\n }\n\n public connect(): EndpointConnection {\n const rpc = JsonRpcChannel.createWithClose(this._transport!, { deferRequests: true });\n this._closeChannel = rpc.close;\n this._resumeRequests = rpc.resumeRequests;\n return {\n channel: rpc.channel, closed: this.closed, dispose: () => this.dispose(),\n resumeRequests: rpc.resumeRequests,\n };\n }\n\n public resumeRequests(): void {\n this._resumeRequests?.();\n }\n\n public dispose(): void {\n if (this.signal.aborted) return;\n this._abort.abort(new Error('Endpoint connection closed'));\n this._closeChannel?.();\n this._transport?.dispose();\n this._closeSocket();\n this._finish();\n }\n}\n\nfunction _listen(server: net.Server, listen: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const onError = (error: Error) => {\n server.removeListener('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n try {\n listen();\n } catch (error) {\n server.removeListener('error', onError);\n server.removeListener('listening', onListening);\n reject(error);\n }\n });\n}\n","import type { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport type { SignedCapability } from '../identity/capability';\nimport type { SigningCallCtx } from '../identity/signingSender';\nimport type { Keypair, PrincipalId } from '../crypto/cryptoProvider';\nimport { signParams } from '../identity/metaEnvelope';\nimport { KeypairSigningIdentity } from '../identity/identity';\nimport { ErrorCode } from '../protocol/jsonRpc';\nimport {\n connectToHub,\n type HubClientHandle,\n loadOrCreateIdentity,\n loadPersistedRegisterCap,\n persistRegisterCap,\n registerHubPrefix,\n} from './hubClient';\n\nexport interface ServeOverHubIdentityOptions {\n /**\n * Stable slot id for the on-disk keypair. Typically the caller's\n * `import.meta.filename`. Same id always loads the same keypair, so\n * persistent capabilities keep working across runs.\n */\n readonly slot: string;\n\n /**\n * Override the on-disk identity / capability store directory (defaults\n * to a per-user folder, see `loadOrCreateIdentity`).\n */\n readonly storeDir?: string;\n /**\n * Override the form-3 method the helper uses to request a register\n * capability when the hub rejects an unsigned / un-capped register.\n * Defaults to\n * `hub-admin::hub-admin.capabilities::issueRegisterCap`. Setting this\n * to `null` disables the fallback (the helper just propagates the\n * `permissionRequired` error).\n */\n readonly issuerMethod?: string | null;\n /**\n * Optional human-friendly purpose string passed to the issuer service.\n * Surfaced in the user-facing approval prompt.\n */\n readonly purpose?: string;\n}\n\nexport interface ServeOverHubOptions {\n /** Service prefix to register with the hub. */\n readonly prefix: string;\n /**\n * Wires handlers onto the connection (registers interfaces, enables\n * reflection, etc). Called once per successful connection attempt,\n * after the prefix has been registered. Must not retain references to\n * the connection across calls — a fresh connection is passed every\n * reconnect.\n */\n readonly setup: (connection: LinkRpcConnection<undefined, SigningCallCtx>) => void | Promise<void>;\n /**\n * Optional human-readable name used in log lines (defaults to `prefix`).\n */\n readonly name?: string;\n /** When set, prints connect/disconnect/retry lines to this sink. */\n readonly log?: ((line: string) => void) | true;\n /**\n * Initial retry delay in ms (capped doubling on each consecutive\n * failure). Defaults to 200 ms.\n */\n readonly initialBackoffMs?: number;\n /** Cap on backoff in ms. Defaults to 5000 ms. */\n readonly maxBackoffMs?: number;\n /**\n * Abort the loop. When the signal is aborted, the current handle is\n * closed and the loop exits. The returned promise resolves once the\n * loop has finished.\n */\n readonly signal?: AbortSignal;\n /**\n * When set, registration is performed against a secure-mode hub: the\n * caller's `$hubrpc`-signed `hubServiceIdRegistry::registerServiceId` carries a\n * presented capability. The first attempt loads any cached cap from\n * disk; on `permissionRequired` the helper calls the hub-admin issuer\n * service to obtain a fresh cap, persists it, and retries. Subsequent\n * reconnects reuse the cached cap. Omit to use the legacy unsigned\n * path (only works against an openMode hub).\n */\n readonly identity?: ServeOverHubIdentityOptions;\n}\n\nexport interface ServeOverHubController {\n /** Stops the loop and closes the current handle, if any. */\n stop(): void;\n /**\n * Resolves when the loop exits (signal aborted or `stop()` called).\n * Rejects only on programmer errors thrown by `setup`.\n */\n readonly done: Promise<void>;\n}\n\n/**\n * Connect to the hub, register `prefix`, run `setup`, and keep the\n * connection alive across hub restarts. When the socket closes, retries\n * with exponential backoff (re-reading `LINKRPC_ENDPOINT` / `LINKRPC_TOKEN`\n * from `process.env` on each attempt so rotated tokens published by the\n * hub host get picked up if the parent shell re-exports them).\n *\n * The hub keeps recently-rotated tokens accepted for a grace window, so\n * even processes that captured the env at spawn time can usually reconnect\n * after a host reload without the parent re-exporting anything.\n */\nexport function serveOverHubWithReconnect(\n options: ServeOverHubOptions,\n): ServeOverHubController {\n const log = _makeLog(options.log, options.name ?? options.prefix);\n const initial = options.initialBackoffMs ?? 200;\n const max = options.maxBackoffMs ?? 5000;\n let stopped = false;\n let current: HubClientHandle | undefined;\n\n const stop = () => {\n if (stopped) return;\n stopped = true;\n current?.close();\n current = undefined;\n };\n options.signal?.addEventListener('abort', stop, { once: true });\n\n const claimer = options.identity ?\n createHubPrefixClaimer({ prefix: options.prefix, identity: options.identity, log }) :\n undefined;\n\n const done = (async () => {\n let attempt = 0;\n let backoff = initial;\n while (!stopped) {\n try {\n if (attempt > 0) log(`reconnecting (attempt ${attempt + 1})…`);\n const handle = await connectToHub();\n current = handle;\n if (claimer) {\n await claimer.claim(handle);\n } else {\n await registerHubPrefix({ handle, prefix: options.prefix });\n }\n await options.setup(handle.connection);\n log(\n attempt === 0 ?\n `connected to hub at ${handle.endpoint} (prefix \"${options.prefix}\")` :\n `reconnected to hub (prefix \"${options.prefix}\")`,\n );\n attempt = 0;\n backoff = initial;\n await new Promise<void>((resolve) => {\n handle.onClose(() => resolve());\n });\n if (stopped) break;\n log(`disconnected from hub`);\n current = undefined;\n } catch (err) {\n if (stopped) break;\n current?.close();\n current = undefined;\n const msg = err instanceof Error ? err.message : String(err);\n log(`connect failed: ${msg}; retrying in ${backoff} ms`);\n await _delay(backoff, options.signal);\n attempt++;\n backoff = Math.min(max, backoff * 2);\n }\n }\n })();\n\n return { stop, done };\n}\n\nexport interface HubPrefixClaimerOptions {\n /** Service prefix to register with the hub. */\n readonly prefix: string;\n /** Identity + capability-issuance options (see {@link ServeOverHubIdentityOptions}). */\n readonly identity: ServeOverHubIdentityOptions;\n /** When set, prints register/capability lines to this sink. */\n readonly log?: (line: string) => void;\n}\n\nexport interface HubPrefixClaimer {\n /**\n * Register the configured prefix on `handle`'s hub, performing the\n * `$hubrpc`-signed register plus capability dance: presents the cached\n * cap, and on `permissionRequired` mints a fresh one via the hub-admin\n * issuer, persists it, and retries. Call once per (re)connect, before\n * serving handlers. The loaded identity and cap are cached across calls.\n */\n claim(handle: HubClientHandle): Promise<void>;\n}\n\n/**\n * Build a reusable, stateful claimer for the signed register + capability\n * flow. Use this with {@link connectService}'s `reconnecting` connector to\n * claim a prefix on each (re)connect:\n *\n * ```ts\n * const claimer = createHubPrefixClaimer({ prefix, identity: { slot } });\n * connectService({\n * connector: reconnecting(async () => {\n * const handle = await connectToHub();\n * try { await claimer.claim(handle); } catch (e) { handle.close(); throw e; }\n * return handle;\n * }),\n * onConnect: ({ connection }) => registerService(connection),\n * });\n * ```\n */\nexport function createHubPrefixClaimer(opts: HubPrefixClaimerOptions): HubPrefixClaimer {\n const log = opts.log ?? (() => { });\n let identity: { principal: PrincipalId; keypair: Keypair; } | undefined;\n let cachedCap: SignedCapability | undefined;\n let capLoaded = false;\n return {\n async claim(handle) {\n if (!identity) {\n const loaded = await loadOrCreateIdentity({\n id: opts.identity.slot,\n ...(opts.identity.storeDir !== undefined ?\n { storeDir: opts.identity.storeDir } :\n {}),\n });\n identity = { principal: loaded.principal, keypair: loaded.keypair };\n }\n if (!capLoaded) {\n const persisted = await loadPersistedRegisterCap({\n identityId: opts.identity.slot,\n prefix: opts.prefix,\n ...(opts.identity.storeDir !== undefined ?\n { storeDir: opts.identity.storeDir } :\n {}),\n });\n cachedCap = persisted?.capability;\n capLoaded = true;\n }\n cachedCap = await _registerSigned(\n handle,\n opts.prefix,\n identity,\n cachedCap,\n opts.identity,\n log,\n );\n },\n };\n}\n\nconst DEFAULT_ISSUER_METHOD = 'hub-admin::hub-admin.capabilities::issueRegisterCap';\n\n/**\n * Try `registerHubPrefix` with `cachedCap`. On `permissionRequired`, call\n * the hub-admin issuer to mint a fresh cap, persist it, retry. Returns the\n * cap that actually worked (caller stores it for the next reconnect).\n */\nasync function _registerSigned(\n handle: HubClientHandle,\n prefix: string,\n identity: { principal: PrincipalId; keypair: Keypair; },\n cachedCap: SignedCapability | undefined,\n identityOpts: ServeOverHubIdentityOptions,\n log: (line: string) => void,\n): Promise<SignedCapability | undefined> {\n try {\n await registerHubPrefix({\n handle,\n prefix,\n identity,\n ...(cachedCap ? { capabilities: [cachedCap] } : {}),\n });\n return cachedCap;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (!_isPermissionRequired(e) || identityOpts.issuerMethod === null) {\n throw e;\n }\n log(`register denied (${msg}); requesting capability from hub-admin issuer…`);\n }\n\n const issuerMethod = identityOpts.issuerMethod ?? DEFAULT_ISSUER_METHOD;\n const signer = new KeypairSigningIdentity(\n identity.principal,\n identity.keypair.privateKey,\n );\n const signedIssueParams = await signParams({\n method: issuerMethod,\n params: {\n audience: identity.principal,\n prefix,\n ...(identityOpts.purpose !== undefined ? { purpose: identityOpts.purpose } : {}),\n },\n signingIdentity: signer,\n });\n const issueRespRaw = await handle.connection.channel.sendRequest(\n issuerMethod,\n signedIssueParams,\n );\n const issueResp = issueRespRaw as unknown as { capability?: SignedCapability; };\n if (!issueResp?.capability) {\n throw new Error('hub-admin issuer returned no capability');\n }\n const fresh = issueResp.capability;\n await persistRegisterCap({\n identityId: identityOpts.slot,\n prefix,\n capability: fresh,\n ...(identityOpts.storeDir !== undefined ? { storeDir: identityOpts.storeDir } : {}),\n });\n\n await registerHubPrefix({\n handle,\n prefix,\n identity,\n capabilities: [fresh],\n });\n return fresh;\n}\n\nfunction _isPermissionRequired(e: unknown): boolean {\n if (e === null || typeof e !== 'object') return false;\n const rec = e as { code?: unknown; };\n if (typeof rec.code === 'number') return rec.code === ErrorCode.permissionRequired;\n const msg = (e as Error).message ?? '';\n return /permission required/i.test(msg);\n}\n\nfunction _makeLog(\n sink: ((line: string) => void) | true | undefined,\n name: string,\n): (line: string) => void {\n if (!sink) return () => { };\n const write = sink === true ?\n (line: string) => {\n process.stderr.write(line + '\\n');\n } :\n sink;\n return (line) => write(`[linkrpc:${name}] ${line}`);\n}\n\nfunction _delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve();\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n resolve();\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { ManagedIdentityStorage } from '../identity/managedIdentity';\n\n/**\n * A {@link ManagedIdentityStorage} backed by a single JSON file (one object\n * keyed by the storage keys). Suitable for self-managed identities that\n * persist their capability bag locally — e.g. pass it to `CapBag.load`.\n *\n * The file is created (mode 0o600) on first write; reads of a missing file\n * yield an empty store. Not concurrency-safe across processes.\n */\nexport function fileManagedIdentityStorage(file: string): ManagedIdentityStorage {\n const read = async (): Promise<Record<string, unknown>> => {\n try {\n return JSON.parse(await readFile(file, 'utf8')) as Record<string, unknown>;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw e;\n }\n };\n const write = async (data: Record<string, unknown>): Promise<void> => {\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n };\n return {\n get: async <T = unknown>(key: string) => (await read())[key] as T | undefined,\n set: async (key, value) => {\n const data = await read();\n data[key] = value;\n await write(data);\n },\n delete: async (key) => {\n const data = await read();\n const existed = key in data;\n delete data[key];\n await write(data);\n return existed;\n },\n list: async (prefix = '') => Object.keys(await read()).filter((k) => k.startsWith(prefix)),\n };\n}\n","import { Principal } from '../identity/signingSender';\nimport { CapBag } from '../identity/capBag';\nimport { KeypairIdentity } from '../identity/identity';\nimport { loadOrCreateIdentity } from './hubClient';\nimport { fileManagedIdentityStorage } from './fileManagedIdentityStorage';\n\n/**\n * Self-managed principal: a local Ed25519 + X25519 keypair (created/loaded on\n * disk) signs and wraps/unwraps for outbound calls, and granted caps are\n * cached in a sibling file. Purely local — no transport needed — and\n * cheap/idempotent, so it can be re-derived on each reconnect. Used with\n * `--use-non-managed-identity`.\n */\nexport async function createSelfManagedPrincipal(identityKey: string): Promise<Principal> {\n return _selfManagedPrincipal({ id: identityKey });\n}\n\n/**\n * Self-managed principal whose keypair lives at an explicit file path (rather\n * than a slot derived from an id). Caps are cached in a sibling `.caps.json`.\n * Used by callers that want to pin the identity to a specific file, e.g. the\n * CLI's `--principal file:<path>`.\n */\nexport async function createSelfManagedPrincipalFromFile(file: string): Promise<Principal> {\n return _selfManagedPrincipal({ id: `file:${file}`, file });\n}\n\nasync function _selfManagedPrincipal(opts: { id: string; file?: string; }): Promise<Principal> {\n const id = await loadOrCreateIdentity({ id: opts.id, file: opts.file });\n const capsFile = id.file.endsWith('.json') ?\n id.file.replace(/\\.json$/, '.caps.json') :\n `${id.file}.caps.json`;\n const capBag = await CapBag.load({ storage: fileManagedIdentityStorage(capsFile) });\n const identity = new KeypairIdentity(id.principal, id.keypair.privateKey, id.wrapKeypair);\n return new Principal(identity, capBag);\n}\n","import type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport type { IMessageTransport } from '../transport/messageTransport';\n\nconst HEADER_SEPARATOR = Buffer.from('\\r\\n\\r\\n');\nconst DEFAULT_MAX_HEADER_BYTES = 64 * 1024;\nconst DEFAULT_MAX_CONTENT_LENGTH = 64 * 1024 * 1024;\nconst DEFAULT_MAX_PENDING_MESSAGES = 1_024;\n\nexport interface HeaderDelimitedTransportOptions {\n readonly maxHeaderBytes?: number;\n readonly maxContentLength?: number;\n readonly maxPendingMessages?: number;\n}\n\n/**\n * LSP \"base protocol\" framing over a Node Readable/Writable pair.\n *\n * The streams remain owned by the caller: close/dispose detach listeners but\n * never end, destroy, or otherwise take ownership of either stream.\n */\nexport class HeaderDelimitedTransport implements IMessageTransport {\n private _listener: ((message: JsonRpcMessage) => void) | undefined;\n private readonly _pending: JsonRpcMessage[] = [];\n private _residual = Buffer.alloc(0);\n private _expectedLength: number | undefined;\n private _closed = false;\n private _closeReason: string | undefined;\n private readonly _maxHeaderBytes: number;\n private readonly _maxContentLength: number;\n private readonly _maxPendingMessages: number;\n\n private readonly _onDataListener = (chunk: Buffer | string): void => this._onData(chunk);\n private readonly _onEndListener = (): void => this._onEnd();\n private readonly _onInputErrorListener = (error: Error): void =>\n this.close(`Header-delimited input error: ${error.message}`);\n private readonly _onOutputErrorListener = (error: Error): void =>\n this.close(`Header-delimited output error: ${error.message}`);\n\n public constructor(\n private readonly _input: NodeJS.ReadableStream,\n private readonly _output: NodeJS.WritableStream,\n private readonly _onClose?: (reason?: string) => void,\n options: HeaderDelimitedTransportOptions = {},\n ) {\n this._maxHeaderBytes = positiveLimit(\n options.maxHeaderBytes, DEFAULT_MAX_HEADER_BYTES, 'maxHeaderBytes',\n );\n this._maxContentLength = positiveLimit(\n options.maxContentLength, DEFAULT_MAX_CONTENT_LENGTH, 'maxContentLength',\n );\n this._maxPendingMessages = positiveLimit(\n options.maxPendingMessages, DEFAULT_MAX_PENDING_MESSAGES, 'maxPendingMessages',\n );\n _input.on('data', this._onDataListener);\n _input.on('end', this._onEndListener);\n _input.on('close', this._onEndListener);\n _input.on('error', this._onInputErrorListener);\n _output.on('error', this._onOutputErrorListener);\n }\n\n public get closed(): boolean {\n return this._closed;\n }\n\n public get closeReason(): string | undefined {\n return this._closeReason;\n }\n\n public send(message: JsonRpcMessage): Promise<void> {\n if (this._closed) {\n return Promise.reject(new Error(this._closeReason ?? 'Header-delimited transport is closed'));\n }\n const body = Buffer.from(JSON.stringify(message), 'utf8');\n if (body.length > this._maxContentLength) {\n return Promise.reject(new Error(\n `Header-delimited payload exceeds ${this._maxContentLength} bytes`,\n ));\n }\n const wire = Buffer.concat([\n Buffer.from(`Content-Length: ${body.length}\\r\\n\\r\\n`, 'ascii'),\n body,\n ]);\n return new Promise<void>((resolve, reject) => {\n this._output.write(wire, (error?: Error | null) => {\n if (error) reject(error);\n else resolve();\n });\n });\n }\n\n public setListener(listener: ((message: JsonRpcMessage) => void) | undefined): void {\n this._listener = listener;\n while (this._listener && this._pending.length > 0) {\n this._listener(this._pending.shift()!);\n }\n }\n\n public dispose(): void {\n this.close('Header-delimited transport disposed');\n }\n\n public close(reason = 'Header-delimited transport closed'): void {\n if (this._closed) return;\n this._closed = true;\n this._closeReason = reason;\n this._input.off('data', this._onDataListener);\n this._input.off('end', this._onEndListener);\n this._input.off('close', this._onEndListener);\n this._input.off('error', this._onInputErrorListener);\n this._output.off('error', this._onOutputErrorListener);\n this._onClose?.(reason);\n }\n\n private _onData(chunk: Buffer | string): void {\n if (this._closed) return;\n const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;\n this._residual = this._residual.length === 0\n ? Buffer.from(bytes)\n : Buffer.concat([this._residual, bytes]);\n\n while (!this._closed) {\n if (this._expectedLength === undefined) {\n const headerEnd = this._residual.indexOf(HEADER_SEPARATOR);\n if (headerEnd < 0) {\n if (this._residual.length > this._maxHeaderBytes) {\n this.close(`Invalid header-delimited frame: header exceeds ${this._maxHeaderBytes} bytes`);\n }\n return;\n }\n if (headerEnd + HEADER_SEPARATOR.length > this._maxHeaderBytes) {\n this.close(`Invalid header-delimited frame: header exceeds ${this._maxHeaderBytes} bytes`);\n return;\n }\n try {\n this._expectedLength = parseHeaders(\n this._residual.subarray(0, headerEnd),\n this._maxContentLength,\n );\n } catch (error) {\n this.close(`Invalid header-delimited frame: ${\n error instanceof Error ? error.message : String(error)\n }`);\n return;\n }\n this._residual = this._residual.subarray(headerEnd + HEADER_SEPARATOR.length);\n }\n\n if (this._residual.length < this._expectedLength) return;\n const body = this._residual.subarray(0, this._expectedLength);\n this._residual = this._residual.subarray(this._expectedLength);\n this._expectedLength = undefined;\n let parsed: JsonRpcMessage;\n try {\n parsed = JSON.parse(body.toString('utf8')) as JsonRpcMessage;\n } catch (error) {\n this.close(`Invalid header-delimited JSON payload: ${\n error instanceof Error ? error.message : String(error)\n }`);\n return;\n }\n this._deliver(parsed);\n }\n }\n\n private _onEnd(): void {\n if (this._closed) return;\n this.close(this._expectedLength !== undefined || this._residual.length > 0\n ? 'Truncated header-delimited frame'\n : 'Header-delimited input closed');\n }\n\n private _deliver(message: JsonRpcMessage): void {\n if (this._listener) {\n this._listener(message);\n return;\n }\n if (this._pending.length >= this._maxPendingMessages) {\n this.close(`Header-delimited pending message limit ${this._maxPendingMessages} exceeded`);\n return;\n }\n this._pending.push(message);\n }\n}\n\nfunction parseHeaders(headerBytes: Buffer, maxContentLength: number): number {\n const values = new Map<string, string>();\n for (const line of headerBytes.toString('ascii').split('\\r\\n')) {\n const colon = line.indexOf(':');\n if (colon <= 0) throw new Error(`malformed header ${JSON.stringify(line)}`);\n const name = line.slice(0, colon).trim().toLowerCase();\n const value = line.slice(colon + 1).trim();\n if (values.has(name)) throw new Error(`duplicate ${name} header`);\n values.set(name, value);\n }\n const rawLength = values.get('content-length');\n if (rawLength === undefined || !/^(0|[1-9]\\d*)$/.test(rawLength)) {\n throw new Error('missing or invalid Content-Length header');\n }\n const length = Number(rawLength);\n if (!Number.isSafeInteger(length) || length > maxContentLength) {\n throw new Error(`Content-Length exceeds ${maxContentLength} bytes`);\n }\n const contentType = values.get('content-type');\n if (contentType !== undefined && !isSupportedContentType(contentType)) {\n throw new Error(`unsupported Content-Type ${JSON.stringify(contentType)}`);\n }\n return length;\n}\n\nfunction isSupportedContentType(value: string): boolean {\n const parts = value.split(';').map((part) => part.trim().toLowerCase());\n return parts[0] === 'application/vscode-jsonrpc'\n && parts.slice(1).every((part) => /^charset\\s*=\\s*\"?utf-?8\"?$/.test(part));\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number, name: string): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new Error(`${name} must be a positive integer`);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,oBACZ,QACA,WAAoC,UAAS,QAAQ,MAAM,+BAA+B,KAAK,GAChF;CACf,QAAQ,UAAU,aAAa;EAC3B,kBAAuB,UAAU,UAAU,MAAM,CAAC,CAAC,OAAM,UAAS;GAC9D,IAAI,SAAS,WAAW,SAAS,WAAW;GAC5C,QAAQ,KAAK;GACb,IAAI,CAAC,SAAS,aAAa;IACvB,SAAS,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;IACxD,SAAS,IAAI,uBAAuB;GACxC,OAAO,SAAS,QAAQ;EAC5B,CAAC;CACL;AACJ;AAEA,eAAe,kBACX,UAA6B,UAC7B,QACa;CACb,MAAM,QAAQ,IAAI,gBAAgB;CAClC,MAAM,gBAAgB;EAClB,IAAI,CAAC,SAAS,kBAAkB,MAAM,sBAAM,IAAI,MAAM,0BAA0B,CAAC;CACrF;CACA,SAAS,KAAK,WAAW,OAAO;CAChC,SAAS,KAAK,SAAS,OAAO;CAC9B,IA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D,MAAM,SAAS,OAAO,SAAS;CAC/B,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,SAAS,kBAC1C,MAAM,IAAI,MAAM,0BAA0B,iBAAiB,OAAO;CAEtE,MAAM,cAAc,OAAO,IAAI,cAAc;CAC7C,IAAI,gBAAgB,KAAA,KAAa,CAAC,uBAAuB,WAAW,GAChE,MAAM,IAAI,MAAM,4BAA4B,KAAK,UAAU,WAAW,GAAG;CAE7E,OAAO;AACX;AAEA,SAAS,uBAAuB,OAAwB;CACpD,MAAM,QAAQ,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,YAAY,CAAC;CACtE,OAAO,MAAM,OAAO,gCACb,MAAM,MAAM,CAAC,CAAC,CAAC,OAAO,SAAS,6BAA6B,KAAK,IAAI,CAAC;AACjF;AAEA,SAAS,cAAc,OAA2B,UAAkB,MAAsB;CACtF,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC3C,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;CAExD,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"node.js","names":["openNativeWebSocket","crypto.generateX25519Keypair","err","crypto.generateKeypair"],"sources":["../src/node/http.ts","../src/node/ndjsonTransport.ts","../src/node/initialize.ts","../src/node/webSocketClientTransport.ts","../src/node/hubClient.ts","../src/node/stdio.ts","../src/node/endpoint.ts","../src/node/hubReconnect.ts","../src/node/fileManagedIdentityStorage.ts","../src/node/principal.ts","../src/node/headerDelimitedTransport.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse, RequestListener } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { JsonValue } from '../protocol/jsonRpc';\nimport type { HttpHandleOptions } from '../http/server';\n\n/** Shape added by Express/Connect; plain Node requests have none of these. */\ninterface MiddlewareRequest extends IncomingMessage {\n readonly originalUrl?: string;\n readonly body?: unknown;\n}\n\n/**\n * Mount a Web Request/Response handler on Node's HTTP server, or as Express/Connect\n * middleware. Routes are matched against the mount-relative `req.url`; a body already\n * consumed by e.g. `express.json()` is reused instead of re-reading the stream.\n */\nexport function httpRequestListener(\n handle: (request: Request, options: HttpHandleOptions) => Promise<Response>,\n onError: (error: unknown) => void = error => console.error('LinkRPC HTTP request failed', error),\n): RequestListener {\n return (incoming, outgoing) => {\n void handleNodeRequest(incoming, outgoing, handle).catch(error => {\n if (incoming.aborted || outgoing.destroyed) return;\n onError(error);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { 'Content-Type': 'text/plain' });\n outgoing.end('Internal server error');\n } else outgoing.destroy();\n });\n };\n}\n\nasync function handleNodeRequest(\n incoming: MiddlewareRequest, outgoing: ServerResponse,\n handle: (request: Request, options: HttpHandleOptions) => Promise<Response>,\n): Promise<void> {\n const abort = new AbortController();\n const onClose = () => {\n if (!outgoing.writableFinished) abort.abort(new Error('HTTP client disconnected'));\n };\n incoming.once('aborted', onClose);\n outgoing.once('close', onClose);\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(incoming.headers)) {\n if (Array.isArray(value)) for (const item of value) headers.append(name, item);\n else if (value !== undefined) headers.set(name, value);\n }\n const init: RequestInit & { duplex: 'half' } = {\n method: incoming.method, headers, signal: abort.signal, duplex: 'half',\n };\n let parsedBody: JsonValue | undefined;\n if (incoming.method !== 'GET' && incoming.method !== 'HEAD') {\n if (!incoming.readableEnded) {\n init.body = Readable.toWeb(incoming) as ReadableStream<Uint8Array>;\n } else if (incoming.body instanceof Uint8Array) {\n init.body = new Uint8Array(incoming.body);\n } else if (incoming.body !== undefined) {\n // body-parser reports an empty body as `{}`; keep \"no params\" distinct from `{}`.\n if (incoming.headers['content-length'] !== '0') parsedBody = incoming.body as JsonValue;\n } else if (incoming.headers['content-length'] !== '0') {\n throw new Error('Request body was consumed by earlier middleware without exposing req.body');\n }\n }\n const base = `http://${incoming.headers.host ?? 'localhost'}`;\n const request = new Request(new URL(incoming.originalUrl ?? incoming.url ?? '/', base), init);\n const response = await handle(request, { path: new URL(incoming.url ?? '/', base).pathname, parsedBody });\n outgoing.writeHead(response.status, Object.fromEntries(response.headers));\n outgoing.flushHeaders();\n if (response.body) {\n await pipeline(Readable.fromWeb(response.body as import('node:stream/web').ReadableStream<Uint8Array>), outgoing);\n } else outgoing.end();\n } finally {\n incoming.removeListener('aborted', onClose);\n outgoing.removeListener('close', onClose);\n }\n}\n","import type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport type { IMessageTransport } from '../transport/messageTransport';\n\n/**\n * Newline-delimited JSON transport over a Node Readable/Writable pair.\n * One JSON value per line, both directions.\n *\n * Not LSP-style headers — those add no value for a private link between two\n * cooperating processes and require a length-prefixed framer.\n */\nexport class NdjsonTransport implements IMessageTransport {\n private _listener: ((m: JsonRpcMessage) => void) | undefined;\n private readonly _buffer: JsonRpcMessage[] = [];\n private _residual = '';\n private _closed = false;\n private readonly _onDataEvent = (chunk: string) => this._onData(chunk);\n private readonly _onEndEvent = () => this.dispose();\n\n constructor(\n private readonly _input: NodeJS.ReadableStream,\n private readonly _output: NodeJS.WritableStream,\n private readonly _onClose?: () => void,\n ) {\n this._input.setEncoding?.('utf8');\n this._input.on('data', this._onDataEvent);\n this._input.on('end', this._onEndEvent);\n this._input.on('close', this._onEndEvent);\n this._input.on('error', this._onEndEvent);\n if (!Object.is(this._output, this._input)) {\n this._output.on('error', this._onEndEvent);\n }\n }\n\n public send(message: JsonRpcMessage): void {\n if (this._closed) return;\n this._output.write(JSON.stringify(message) + '\\n');\n }\n\n public setListener(listener: ((m: JsonRpcMessage) => void) | undefined): void {\n this._listener = listener;\n if (listener) {\n while (this._buffer.length > 0 && this._listener) {\n const m = this._buffer.shift()!;\n this._listener(m);\n }\n }\n }\n\n public dispose(): void {\n if (this._closed) return;\n this._closed = true;\n this._input.removeListener('data', this._onDataEvent);\n this._input.removeListener('end', this._onEndEvent);\n this._input.removeListener('close', this._onEndEvent);\n this._input.removeListener('error', this._onEndEvent);\n this._output.removeListener('error', this._onEndEvent);\n this._listener = undefined;\n this._buffer.length = 0;\n this._residual = '';\n this._onClose?.();\n }\n\n private _onData(chunk: string): void {\n this._residual += chunk;\n let nl: number;\n while ((nl = this._residual.indexOf('\\n')) >= 0) {\n const line = this._residual.slice(0, nl).trim();\n this._residual = this._residual.slice(nl + 1);\n if (!line) continue;\n let parsed: JsonRpcMessage;\n try {\n parsed = JSON.parse(line) as JsonRpcMessage;\n } catch {\n continue;\n }\n this._deliver(parsed);\n }\n }\n\n private _deliver(m: JsonRpcMessage): void {\n if (this._listener) this._listener(m);\n else this._buffer.push(m);\n }\n}\n","import {\n type IMessageTransport,\n type MessageTransportTrace,\n traceMessageTransport,\n} from '../transport/messageTransport';\nimport { runInitializeHandshake, type InitializeRole } from '../transport/initialize';\nimport { NdjsonTransport } from './ndjsonTransport';\n\nexport * from '../transport/initialize';\n\nexport interface ConnectNdjsonOptions {\n readonly input: NodeJS.ReadableStream;\n readonly output: NodeJS.WritableStream;\n readonly onClose?: () => void;\n /** Complete initialization before exposing the transport. */\n readonly initialize?: InitializeRole;\n /** Includes handshake messages; may contain credentials. */\n readonly trace?: MessageTransportTrace;\n readonly handshakeTimeoutMs?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ConnectedNdjson {\n readonly transport: IMessageTransport;\n readonly token?: string;\n}\n\n/** Construct NDJSON and complete the shared transport initialization handshake. */\nexport async function connectNdjson(opts: ConnectNdjsonOptions): Promise<ConnectedNdjson> {\n const role = opts.initialize;\n const closed = new AbortController();\n const baseTransport = new NdjsonTransport(opts.input, opts.output, () => {\n try {\n opts.onClose?.();\n } finally {\n closed.abort(new Error('hubrpc::initialize: transport closed during handshake'));\n }\n });\n const transport = opts.trace === undefined\n ? baseTransport\n : traceMessageTransport(baseTransport, opts.trace);\n if (!role) return { transport };\n try {\n const { token } = await runInitializeHandshake(transport, role, {\n handshakeTimeoutMs: opts.handshakeTimeoutMs,\n signal: opts.signal ? AbortSignal.any([closed.signal, opts.signal]) : closed.signal,\n });\n return { transport, ...(token !== undefined ? { token } : {}) };\n } catch (err) {\n transport.dispose();\n throw err;\n }\n}\n","export { WebSocketTransport } from '../transport/webSocketTransport';\nimport { openWebSocket as openNativeWebSocket } from '../transport/webSocketTransport';\n\nexport interface OpenWebSocketOptions {\n readonly headers?: Record<string, string>;\n}\n\n/** Node-only header extension. The web entry exposes the standard overload. */\nexport function openWebSocket(url: string, opts: OpenWebSocketOptions = {}): Promise<WebSocket> {\n if (!opts.headers || Object.keys(opts.headers).length === 0) return openNativeWebSocket(url);\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(url, { headers: opts.headers } as unknown as string[]);\n const onOpen = () => {\n ws.removeEventListener('error', onError);\n resolve(ws);\n };\n const onError = () => {\n ws.removeEventListener('open', onOpen);\n reject(new Error('WebSocket connection failed'));\n };\n ws.addEventListener('open', onOpen, { once: true });\n ws.addEventListener('error', onError, { once: true });\n });\n}\n","import * as fs from 'node:fs/promises';\nimport * as net from 'node:net';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { Channel } from '../connection/channel';\nimport { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport {\n OneShotCapStaging,\n Principal, SigningSender,\n type SigningCallCtx,\n type SigningSenderConfig\n} from '../identity/signingSender';\nimport type { SignedCapability } from '../identity/capability';\nimport {\n base64UrlToBytes,\n bytesToBase64Url,\n type Keypair,\n type PrincipalId,\n principalForPublicKey,\n type X25519Keypair,\n} from '../crypto/cryptoProvider';\nimport * as crypto from '../crypto/crypto';\nimport { signParams } from '../identity/metaEnvelope';\nimport { KeypairSigningIdentity } from '../identity/identity';\nimport type { JsonValue } from '../protocol/jsonValue';\nimport type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport { sha256 } from '../crypto/sha256';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport { connectNdjson, runInitializeHandshake } from './initialize';\nimport { openWebSocket, WebSocketTransport } from './webSocketClientTransport';\nimport { IDisposable } from '../disposable';\nimport { Hub, hubFromConnection } from '../hub/client/hubFacade';\n\n/** Env var the hub publishes for its endpoint (named pipe / UDS path). */\nexport const LINKRPC_ENDPOINT_VAR = 'LINKRPC_ENDPOINT';\n/** Env var the hub publishes for its shared attribution token. */\nexport const LINKRPC_TOKEN_VAR = 'LINKRPC_TOKEN';\n\nexport function getHubEnvironment(): { readonly endpoint: string | undefined; readonly token: string | undefined } {\n const endpoint = process.env[LINKRPC_ENDPOINT_VAR];\n if (endpoint !== undefined) return { endpoint, token: process.env[LINKRPC_TOKEN_VAR] };\n const legacyEndpoint = process.env.HUBRPC_ENDPOINT;\n if (legacyEndpoint !== undefined) return { endpoint: legacyEndpoint, token: process.env.HUBRPC_TOKEN };\n return { endpoint: undefined, token: process.env[LINKRPC_TOKEN_VAR] ?? process.env.HUBRPC_TOKEN };\n}\n\nexport function requireHubEndpoint(endpoint: string | undefined = getHubEnvironment().endpoint): string {\n const value = endpoint?.trim();\n if (!value) throw new Error('LINKRPC_ENDPOINT (or HUBRPC_ENDPOINT) is not set; specify an endpoint.');\n return value;\n}\n\nexport interface ConnectToHubOptions {\n /** Defaults to LINKRPC_ENDPOINT, or the legacy HUBRPC_ENDPOINT. */\n readonly endpoint?: string;\n /** Defaults to the token from the selected environment variable family. */\n readonly token?: string;\n /**\n * Initial {@link Principal} (identity + persistent caps) for outbound\n * calls. Stored on the returned handle's {@link HubClientHandle.signing}\n * config; mutate that later to install or swap. `undefined` leaves the\n * connection unsigned (plain JSON-RPC) until a principal is installed.\n */\n readonly principal?: Principal;\n /**\n * Initial one-shot capability staging policy. Same lifecycle as\n * {@link principal}; drained per outbound signed call.\n */\n readonly oneShotCaps?: OneShotCapStaging;\n}\n\n/**\n * Mutable signing config consulted per-call by the {@link SigningSender}\n * wrapping a {@link HubClientHandle.connection}. Mutating either field\n * takes effect on the next outbound call. No setter on the sender\n * itself — it is a plain caller-owned {@link SigningSenderConfig}.\n */\nexport type HubSigningHolder = {\n principal?: Principal;\n capProvider?: SigningSenderConfig['capProvider'];\n oneShotCaps?: OneShotCapStaging;\n};\n\nexport interface HubClientHandle {\n /** Full linkrpc connection wrapping the same transport. */\n readonly connection: LinkRpcConnection<undefined, SigningCallCtx>;\n /**\n * Façade over the hub's own serviceId-routed services (`hubGrantedServiceId`,\n * `hubAccess`, …) on this {@link connection}. Use it to read connection\n * facts ({@link Hub.getConnectionInfo}) or claim this connection's granted\n * serviceId namespace ({@link Hub.claimGrantedServiceIdNamespace}) without\n * hand-routing the interface clients.\n */\n readonly hub: Hub;\n /** Configured endpoint + token (in case the caller defaulted from env). */\n readonly endpoint: string;\n readonly token: string;\n /**\n * Mutable signing config. Starts empty (every call goes out\n * unsigned). `installManagedIdentitySigner` and `setupHubSigning`\n * populate this; user code can also drive it directly.\n */\n readonly signing: HubSigningHolder;\n /**\n * Register a callback that fires when the underlying socket closes\n * (peer end, error, or explicit {@link close}). Fires at most once.\n * Returns an unsubscribe function.\n */\n onClose(listener: () => void): IDisposable;\n /** Close the underlying socket and tear everything down. */\n close(): void;\n}\n\n/**\n * Open a connection to a running linkrpc hub. Reads `LINKRPC_ENDPOINT` and\n * `LINKRPC_TOKEN` (or the legacy HUBRPC pair) from the environment unless overridden. Sends the single-\n * line `{\"hello\":1,\"token\":\"...\"}` preamble that the hub's socket server\n * requires, then wraps the socket in an `LinkRpcConnection`.\n *\n * Throws if env vars are missing, if the socket cannot be opened, or if the\n * hub refuses the preamble (the socket simply closes — callers should treat\n * an immediate close of the channel as an auth failure).\n */\nexport async function connectToHub(options: ConnectToHubOptions = {}): Promise<HubClientHandle> {\n const hubChannel = await openHubChannel(options);\n const signing: HubSigningHolder = {\n principal: options.principal,\n oneShotCaps: options.oneShotCaps,\n };\n const channel = SigningSender.wrapChannel(hubChannel, signing);\n const connection = new LinkRpcConnection(channel);\n return {\n connection,\n hub: hubFromConnection(connection),\n endpoint: hubChannel.endpoint,\n token: hubChannel.token,\n signing,\n onClose: hubChannel.onClose,\n close: () => {\n connection.close();\n hubChannel.close();\n },\n };\n}\n\n/** Options for {@link openHubChannel}. Subset of {@link ConnectToHubOptions}. */\nexport interface OpenHubChannelOptions {\n /** Defaults to LINKRPC_ENDPOINT, or the legacy HUBRPC_ENDPOINT. */\n readonly endpoint?: string;\n /**\n * Defaults to the selected environment family's token, or `''` when unset. The token\n * is sent in the hello preamble; provenance-authenticated hubs (hubv2)\n * ignore it, so an empty token is valid there.\n */\n readonly token?: string;\n /** Queue incoming requests until resumeRequests; outbound responses remain live. */\n readonly deferRequests?: boolean;\n}\n\n/**\n * A raw, unsigned hub channel: the socket transport wrapped only in a\n * {@link JsonRpcChannel}, with no signing applied. It *is* a {@link Channel}\n * (so it plugs straight into {@link SigningSender.wrapChannel} /\n * `new LinkRpcConnection`), augmented with the hub endpoint/token and the\n * socket lifecycle. Identity/signing is composed on top by the caller;\n * {@link connectToHub} is the batteries-included version that adds a\n * mutable signing holder.\n */\nexport type HubChannel = Channel<undefined, unknown> & {\n readonly endpoint: string;\n readonly token: string;\n /**\n * Register a callback that fires when the socket closes. Fires at most\n * once. Returns an unsubscribe function.\n */\n onClose(listener: () => void): IDisposable;\n /** Close the underlying socket. */\n close(): void;\n /** Release incoming requests after installing application handlers. */\n resumeRequests(methods?: readonly string[]): void;\n};\n\n/**\n * Open the hub socket and send the preamble, returning the raw\n * {@link HubChannel} without any signing. Use this when you want to\n * compose identity yourself; otherwise prefer {@link connectToHub}.\n */\nexport async function openHubChannel(\n options: OpenHubChannelOptions = {},\n): Promise<HubChannel> {\n const environment = getHubEnvironment();\n const endpoint = requireHubEndpoint(options.endpoint ?? environment.endpoint);\n const token = options.token ?? environment.token ?? '';\n\n const closeListeners = new Set<() => void>();\n let closed = false;\n let closeChannel: (() => void) | undefined;\n const fireClose = () => {\n if (closed) return;\n closed = true;\n closeChannel?.();\n for (const l of closeListeners) {\n try {\n l();\n } catch { /* ignore */ }\n }\n closeListeners.clear();\n };\n\n const { transport, destroy } = await _openHubTransport(endpoint, token, fireClose);\n const rpc = JsonRpcChannel.createWithClose(transport, { deferRequests: options.deferRequests });\n closeChannel = rpc.close;\n if (closed) rpc.close();\n return Object.assign(rpc.channel, {\n endpoint,\n token,\n resumeRequests: rpc.resumeRequests,\n onClose: (listener: () => void) => {\n if (closed) {\n queueMicrotask(listener);\n return { dispose: () => { } };\n }\n closeListeners.add(listener);\n return { dispose: () => closeListeners.delete(listener) };\n },\n close: () => {\n destroy();\n fireClose();\n },\n });\n}\n\n/** True for `ws://` / `wss://` endpoints (case-insensitive). */\nfunction _isWebSocketEndpoint(endpoint: string): boolean {\n return /^wss?:\\/\\//i.test(endpoint);\n}\n\n/**\n * Open the underlying transport for {@link openHubChannel}, picking the\n * scheme from the endpoint:\n * - `ws://` / `wss://` → WebSocket; the token is presented via the\n * `hubrpc::initialize` handshake (browsers cannot set request headers).\n * - anything else → named pipe / UDS; the token is presented via the\n * `hubrpc::initialize` handshake the socket server requires.\n *\n * `onClose` fires once when the peer ends the transport.\n */\nasync function _openHubTransport(\n endpoint: string,\n token: string,\n onClose: () => void,\n): Promise<{ transport: IMessageTransport<JsonRpcMessage, JsonRpcMessage>; destroy: () => void; }> {\n if (_isWebSocketEndpoint(endpoint)) {\n const ws = await openWebSocket(endpoint);\n const closed = new AbortController();\n const transport = new WebSocketTransport(ws, () => {\n closed.abort(new Error('hubrpc::initialize: transport closed during handshake'));\n onClose();\n });\n const destroy = () => {\n try {\n ws.close();\n } catch { /* ignore */ }\n };\n try {\n await runInitializeHandshake(transport, { kind: 'client', token }, { signal: closed.signal });\n } catch (err) {\n transport.dispose();\n destroy();\n throw err;\n }\n return { transport, destroy };\n }\n const socket = await _openSocket(endpoint);\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => {\n socket.destroy();\n onClose();\n },\n initialize: { kind: 'client', token },\n });\n return { transport, destroy: () => socket.destroy() };\n}\n\n/**\n * Send the `linkrpc.hub::hubServiceIdRegistry::registerServiceId` call on an open\n * hub connection. In `openMode` the hub accepts the unsigned call directly —\n * pass no `identity`. Outside `openMode` the caller must sign the params\n * with their `identity` keypair (via `signParams`) and present a\n * capability that authorizes the claim — unless the signer is already an\n * admin on the hub, in which case `capabilities` may be omitted.\n *\n * Resolves once the hub has registered the prefix; rejects on denial.\n */\nexport interface RegisterHubPrefixOptions {\n readonly handle: HubClientHandle;\n readonly prefix: string;\n /**\n * Caller's signing identity. Required when the hub is not in openMode.\n * The `principal` must encode the `publicKey` (round-tripped through\n * `principalForPublicKey`). Bound to this transport on first successful\n * `register` — subsequent calls on the same socket may not switch\n * identity.\n */\n readonly identity?: { readonly principal: PrincipalId; readonly keypair: Keypair; };\n /**\n * Capabilities to present. Each must be issued (directly or\n * transitively) by an admin and permit\n * `<prefix>::hubServiceIdRegistry::registerServiceId`. Omit when the signer\n * is already an admin.\n */\n readonly capabilities?: readonly SignedCapability[];\n}\n\nexport async function registerHubPrefix(\n opts: RegisterHubPrefixOptions,\n): Promise<void> {\n let params: Record<string, unknown>;\n if (opts.identity) {\n const signer = new KeypairSigningIdentity(\n opts.identity.principal,\n opts.identity.keypair.privateKey,\n );\n params = await signParams({\n method: 'hubServiceIdRegistry::registerServiceId',\n params: { requestedPrefix: opts.prefix },\n signingIdentity: signer,\n ...(opts.capabilities && opts.capabilities.length > 0 ?\n { capabilities: [...opts.capabilities] } :\n {}),\n });\n } else {\n if (opts.capabilities && opts.capabilities.length > 0) {\n throw new Error('registerHubPrefix: capabilities require identity to be set');\n }\n params = { requestedPrefix: opts.prefix };\n }\n await opts.handle.connection.channel.sendRequest(\n 'hubServiceIdRegistry::registerServiceId',\n params as JsonValue,\n );\n}\n\n// ---- Identity persistence -----------------------------------------------\n\nexport interface LoadOrCreateIdentityOptions {\n /**\n * Stable string that identifies this identity slot. Typically the calling\n * module's `import.meta.filename` — each service then automatically gets\n * its own slot.\n */\n readonly id: string;\n /** Override the storage directory (defaults to a per-user folder). */\n readonly storeDir?: string;\n /**\n * Use this exact on-disk path for the keypair file instead of deriving one\n * from `id` (and `storeDir`). Takes precedence over `storeDir`; the parent\n * directory is created if missing.\n */\n readonly file?: string;\n}\n\nexport interface PersistedIdentity {\n readonly principal: PrincipalId;\n readonly keypair: Keypair;\n /** Long-lived X25519 keypair used for HPKE wrap/unwrap. */\n readonly wrapKeypair: X25519Keypair;\n /** Absolute path of the on-disk file. */\n readonly file: string;\n}\n\n/**\n * Load the Ed25519 + X25519 keypairs for `id` from disk, or\n * generate-and-persist them on first call. The slot is keyed by SHA-256 of\n * `id` so callers can pass any stable string (e.g. `import.meta.filename`)\n * without worrying about filesystem-safe characters.\n *\n * Identity files written before wrapping support carried only the Ed25519\n * keypair; on load they are transparently migrated — the Ed25519 keypair\n * (and therefore the `nodeId`) is preserved and a fresh X25519 wrap keypair\n * is generated and written back.\n *\n * NOTE: keys are stored unencrypted. Only suitable for local development\n * identities — not for anything that must resist file-system attackers.\n */\nexport async function loadOrCreateIdentity(\n opts: LoadOrCreateIdentityOptions,\n): Promise<PersistedIdentity> {\n const file = identityFilePath(opts);\n await fs.mkdir(path.dirname(file), { recursive: true });\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as {\n privateKey?: string;\n publicKey?: string;\n wrapPrivateKey?: string;\n wrapPublicKey?: string;\n };\n if (typeof parsed.privateKey !== 'string' || typeof parsed.publicKey !== 'string') {\n throw new Error('malformed identity file');\n }\n const privateKey = base64UrlToBytes(parsed.privateKey);\n const publicKey = base64UrlToBytes(parsed.publicKey);\n const keypair: Keypair = { privateKey, publicKey };\n let wrapKeypair: X25519Keypair;\n if (typeof parsed.wrapPrivateKey === 'string' && typeof parsed.wrapPublicKey === 'string') {\n wrapKeypair = {\n privateKey: base64UrlToBytes(parsed.wrapPrivateKey),\n publicKey: base64UrlToBytes(parsed.wrapPublicKey),\n };\n } else {\n // Pre-wrapping identity file: keep the Ed25519 keypair (stable\n // principal) and add a fresh X25519 wrap keypair, written back.\n wrapKeypair = await crypto.generateX25519Keypair();\n await _writeIdentityFile(file, keypair, wrapKeypair, opts.id);\n }\n return { keypair, wrapKeypair, principal: principalForPublicKey(publicKey), file };\n } catch (e: unknown) {\n const err = e as NodeJS.ErrnoException;\n if (err.code !== 'ENOENT') throw e;\n }\n const keypair = await crypto.generateKeypair();\n const wrapKeypair = await crypto.generateX25519Keypair();\n await _writeIdentityFile(file, keypair, wrapKeypair, opts.id);\n return { keypair, wrapKeypair, principal: principalForPublicKey(keypair.publicKey), file };\n}\n\n/** The on-disk file {@link loadOrCreateIdentity} uses for `opts`, without reading or creating it. */\nexport function identityFilePath(opts: LoadOrCreateIdentityOptions): string {\n return opts.file ?? path.join(opts.storeDir ?? _defaultStoreDir(), `${_slotName(opts.id)}.json`);\n}\n\nasync function _writeIdentityFile(\n file: string,\n keypair: Keypair,\n wrapKeypair: X25519Keypair,\n id: string,\n): Promise<void> {\n const payload = {\n privateKey: bytesToBase64Url(keypair.privateKey),\n publicKey: bytesToBase64Url(keypair.publicKey),\n wrapPrivateKey: bytesToBase64Url(wrapKeypair.privateKey),\n wrapPublicKey: bytesToBase64Url(wrapKeypair.publicKey),\n id,\n };\n await fs.writeFile(file, JSON.stringify(payload, null, 2), { mode: 0o600 });\n}\n\nfunction _defaultStoreDir(): string {\n const home = os.homedir();\n if (process.platform === 'win32') {\n const appdata = process.env.APPDATA;\n if (appdata) return path.join(appdata, 'hubrpc', 'identities');\n return path.join(home, 'AppData', 'Roaming', 'hubrpc', 'identities');\n }\n if (process.platform === 'darwin') {\n return path.join(home, 'Library', 'Application Support', 'hubrpc', 'identities');\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n if (xdg) return path.join(xdg, 'hubrpc', 'identities');\n return path.join(home, '.config', 'hubrpc', 'identities');\n}\n\nfunction _slotName(id: string): string {\n const digest = sha256(new TextEncoder().encode(id));\n let out = '';\n for (let i = 0; i < 16; i++) {\n out += digest[i].toString(16).padStart(2, '0');\n }\n return out;\n}\n\n// ---- Capability persistence ---------------------------------------------\n\n/**\n * On-disk capability cache, keyed by `(identity slot, prefix)`. Lives next\n * to the identity files so the lifecycle is the same: lose the dir, get a\n * fresh prompt next time. Caps are not secret; the cache is read/write\n * mode 0o600 anyway for consistency.\n */\nexport interface PersistedRegisterCap {\n readonly capability: SignedCapability;\n /** Absolute path of the on-disk file. */\n readonly file: string;\n}\n\nexport async function loadPersistedRegisterCap(args: {\n readonly identityId: string;\n readonly prefix: string;\n readonly storeDir?: string;\n}): Promise<PersistedRegisterCap | undefined> {\n const file = _capFilePath(args.identityId, args.prefix, args.storeDir);\n try {\n const raw = await fs.readFile(file, 'utf8');\n const parsed = JSON.parse(raw) as { capability?: SignedCapability; };\n if (!parsed.capability) return undefined;\n // Drop the cap if it expired so the caller re-acquires.\n if (\n parsed.capability.expiresAtMs !== undefined &&\n parsed.capability.expiresAtMs < Date.now()\n ) {\n return undefined;\n }\n return { capability: parsed.capability, file };\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;\n return undefined;\n }\n}\n\nexport async function persistRegisterCap(args: {\n readonly identityId: string;\n readonly prefix: string;\n readonly capability: SignedCapability;\n readonly storeDir?: string;\n}): Promise<string> {\n const file = _capFilePath(args.identityId, args.prefix, args.storeDir);\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.writeFile(\n file,\n JSON.stringify({ capability: args.capability }, null, 2),\n { mode: 0o600 },\n );\n return file;\n}\n\nfunction _capFilePath(\n identityId: string,\n prefix: string,\n storeDir: string | undefined,\n): string {\n const dir = storeDir ?? _defaultStoreDir();\n const slot = _slotName(identityId);\n return path.join(dir, `${slot}-cap-${_slotName(prefix)}.json`);\n}\n\nfunction _openSocket(endpoint: string): Promise<net.Socket> {\n return new Promise((resolve, reject) => {\n const socket = net.createConnection(endpoint);\n const onError = (err: Error) => {\n socket.removeListener('connect', onConnect);\n reject(err);\n };\n const onConnect = () => {\n socket.removeListener('error', onError);\n resolve(socket);\n };\n socket.once('error', onError);\n socket.once('connect', onConnect);\n });\n}\n","import { type ChildProcess, spawn } from 'node:child_process';\nimport { connectNdjson } from './initialize';\nimport type { Channel } from '../connection/channel';\nimport type { IDisposable } from '../disposable';\nimport { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\n\n/**\n * Spawn a child process and connect to its stdio as a linkrpc connection.\n *\n * Pass a single command line (split on whitespace) or an array `[cmd, ...args]`.\n * The child's stderr is piped to the parent's stderr so logs surface naturally.\n *\n * @example\n * const c = await connectToCmdStdio(\"node ./ghConnector.js\");\n * const gh = c.get(ghInterface);\n * await gh.createIssue({ title: \"...\" });\n */\nexport async function connectToCmdStdio(cmd: string | readonly string[]): Promise<LinkRpcConnection> {\n const parts = typeof cmd === 'string' ? cmd.split(/\\s+/).filter(Boolean) : [...cmd];\n if (parts.length === 0) throw new Error('connectToCmdStdio: empty command');\n const [bin, ...args] = parts;\n const child: ChildProcess = spawn(bin, args, {\n stdio: ['pipe', 'pipe', 'inherit'],\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connectToCmdStdio: child has no stdio');\n }\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => {\n if (!child.killed) child.kill();\n },\n });\n return LinkRpcConnection.fromTransport(transport);\n}\n\n/**\n * For the child side: a linkrpc connection over this process's stdin/stdout.\n * The child MUST NOT write user output to stdout — only RPC messages — or\n * the parent's parser will choke.\n */\nexport async function serveOnStdio(): Promise<LinkRpcConnection> {\n const { transport } = await connectNdjson({ input: process.stdin, output: process.stdout });\n return LinkRpcConnection.fromTransport(transport);\n}\n\n/**\n * A raw, unsigned channel over this process's stdin/stdout — the stdio\n * counterpart to `openHubChannel`. It *is* a {@link Channel} (so it plugs\n * straight into {@link SigningSender.wrapChannel} / `new LinkRpcConnection`),\n * augmented with a close signal for stdin end. Use {@link serveOnStdio}\n * instead when no signing is needed.\n */\nexport type StdioChannel = Channel<undefined, unknown> & {\n /** Fires once when stdin ends/closes. Returns a disposable to unsubscribe. */\n onClose(listener: () => void): IDisposable;\n /** Detach from stdin/stdout without closing these process-owned streams. */\n close(): void;\n /** Release incoming requests after installing application handlers. */\n resumeRequests(methods?: readonly string[]): void;\n};\n\nexport async function openStdioChannel(options: { readonly deferRequests?: boolean } = {}): Promise<StdioChannel> {\n const closeListeners = new Set<() => void>();\n let closed = false;\n let closeChannel: (() => void) | undefined;\n const fireClose = () => {\n if (closed) return;\n closed = true;\n closeChannel?.();\n if (process.stdin.listenerCount('data') === 0) process.stdin.pause();\n for (const l of closeListeners) {\n try {\n l();\n } catch { /* ignore */ }\n }\n closeListeners.clear();\n };\n const { transport } = await connectNdjson({\n input: process.stdin, output: process.stdout, onClose: fireClose,\n });\n const rpc = JsonRpcChannel.createWithClose(transport, options);\n closeChannel = rpc.close;\n if (closed) rpc.close();\n\n return Object.assign(rpc.channel, {\n resumeRequests: rpc.resumeRequests,\n close: fireClose,\n onClose: (listener: () => void) => {\n if (closed) {\n queueMicrotask(listener);\n return { dispose: () => { } };\n }\n closeListeners.add(listener);\n return { dispose: () => closeListeners.delete(listener) };\n },\n });\n}\n","import { timingSafeEqual } from 'node:crypto';\nimport * as http from 'node:http';\nimport * as net from 'node:net';\nimport type { WebSocketServer } from 'ws';\nimport type { Channel } from '../connection/channel';\nimport { formatEndpointUri, parseEndpointUri, type SocketEndpoint, type WsEndpoint } from '../connection/endpointUri';\nimport { JsonRpcChannel } from '../connection/jsonRpcChannel';\nimport type { IDisposable } from '../disposable';\nimport type { IMessageTransport } from '../transport/messageTransport';\nimport { getHubEnvironment, requireHubEndpoint, openHubChannel } from './hubClient';\nimport { connectNdjson, runInitializeHandshake } from './initialize';\nimport { openStdioChannel } from './stdio';\nimport { WebSocketTransport } from './webSocketClientTransport';\n\nexport interface StartEndpointOptions {\n /** Overrides LINKRPC_ENDPOINT / HUBRPC_ENDPOINT. Use `listen:` to accept rather than dial. */\n readonly endpoint?: string;\n /** Overrides the URI token, then the selected environment token. Required for listeners. */\n readonly token?: string;\n /** Install services/signing. Inbound requests wait for completion; outbound calls remain live. */\n readonly onConnection: (connection: EndpointConnection) => void | Promise<void>;\n /** Listener peer/transport failures. Defaults to process.emitWarning. Must not throw. */\n readonly onError?: (error: Error) => void;\n}\n\nexport interface EndpointConnection extends IDisposable {\n readonly channel: Channel<undefined, unknown>;\n /** Resolves on peer disconnect or disposal; pending RPC calls are rejected. */\n readonly closed: Promise<void>;\n /**\n * Release selected non-streaming bootstrap requests during onConnection.\n * Without arguments, release all requests. Notifications and input streams\n * remain queued until all requests are released.\n */\n resumeRequests(methods?: readonly string[]): void;\n}\n\nexport interface StartedEndpoint extends IDisposable {\n /** Dialable bound address (including the assigned port), without credentials; or `stdio:`. */\n readonly endpoint: string;\n /** Resolves after shutdown. Listeners stay open until disposed or a server error. */\n readonly closed: Promise<void>;\n}\n\n/**\n * Start a Node application's RPC endpoint without imposing argument parsing,\n * signing, service registration, signal handlers, or process-exit policy.\n * Startup and initial onConnection failures reject. A listener isolates failed\n * peers, reports them via onError, and continues accepting other connections.\n */\nexport async function startEndpoint(options: StartEndpointOptions): Promise<StartedEndpoint> {\n const environment = getHubEnvironment();\n const configured = requireHubEndpoint(options.endpoint ?? environment.endpoint);\n if (configured === 'stdio' || configured === 'stdio:') {\n return _startSingle('stdio:', await openStdioChannel({ deferRequests: true }), options);\n }\n const listening = configured.startsWith('listen:');\n const target = parseEndpointUri(listening ? configured.slice('listen:'.length) : configured);\n if (target.kind !== 'socket' && target.kind !== 'ws') {\n throw new Error('startEndpoint supports stdio, socket, and LinkRPC WebSocket endpoints only.');\n }\n const token = options.token ?? target.token ?? environment.token ?? '';\n const endpoint = formatEndpointUri({ ...target, token: undefined });\n if (!listening) {\n const channel = await openHubChannel({\n endpoint: target.kind === 'socket' ? target.path : target.url, token, deferRequests: true,\n });\n return _startSingle(endpoint, channel, options);\n }\n if (!token) throw new Error('Listening endpoints require a nonempty token.');\n return EndpointListener.start(target, token, options);\n}\n\nasync function _startSingle(\n endpoint: string,\n source: Channel<undefined, unknown> & {\n close(): void;\n resumeRequests(methods?: readonly string[]): void;\n onClose(listener: () => void): IDisposable;\n },\n options: StartEndpointOptions,\n): Promise<StartedEndpoint> {\n let finish!: () => void;\n const closed = new Promise<void>(resolve => { finish = resolve; });\n const subscription = source.onClose(finish);\n void closed.then(() => subscription.dispose());\n const connection: EndpointConnection = {\n channel: source, closed, dispose: () => source.close(), resumeRequests: source.resumeRequests,\n };\n try {\n await options.onConnection(connection);\n source.resumeRequests();\n return { endpoint, closed, dispose: connection.dispose };\n } catch (error) {\n connection.dispose();\n await closed;\n throw error;\n }\n}\n\nclass EndpointListener implements StartedEndpoint {\n private readonly _peers = new Set<ListenerPeer>();\n private readonly _tasks = new Set<Promise<void>>();\n private readonly _sockets = new Set<net.Socket>();\n private _disposed = false;\n private _finish!: () => void;\n public readonly closed = new Promise<void>(resolve => { this._finish = resolve; });\n\n private constructor(\n public readonly endpoint: string,\n private readonly _server: net.Server,\n private readonly _token: string,\n private readonly _options: StartEndpointOptions,\n private readonly _webSocketServer?: WebSocketServer,\n ) {\n _server.on('connection', socket => {\n this._sockets.add(socket);\n socket.on('close', () => this._sockets.delete(socket));\n if (this._disposed) socket.destroy();\n });\n _server.on('error', error => {\n this._report(error);\n this.dispose();\n });\n }\n\n public static async start(\n target: SocketEndpoint | WsEndpoint,\n token: string,\n options: StartEndpointOptions,\n ): Promise<EndpointListener> {\n if (target.kind === 'socket') {\n const server = net.createServer();\n await _listen(server, () => server.listen(target.path));\n const owner = new EndpointListener(formatEndpointUri({ ...target, token: undefined }), server, token, options);\n server.on('connection', socket => {\n const peer = owner._createPeer(() => socket.destroy());\n socket.on('error', error => owner._peerError(peer, error));\n socket.on('close', () => peer.dispose());\n owner._accept(peer, () => connectNdjson({\n input: socket, output: socket,\n onClose: () => peer.dispose(),\n signal: peer.signal,\n initialize: { kind: 'server', isTokenAccepted: async candidate => owner._accepts(candidate) },\n }).then(result => result.transport));\n });\n return owner;\n }\n const url = new URL(target.url);\n if (url.protocol !== 'ws:') throw new Error('Listening WebSockets require ws:; terminate TLS at a reverse proxy.');\n if (url.username || url.password || url.search || url.hash) {\n throw new Error('Listening WebSocket URLs cannot contain credentials, query parameters, or fragments.');\n }\n const { WebSocketServer } = await import('ws');\n const server = http.createServer((_request, response) => {\n response.writeHead(426);\n response.end('WebSocket upgrade required');\n });\n await _listen(server, () => server.listen(Number(url.port || 80), url.hostname.replace(/^\\[|\\]$/g, '')));\n const webSockets = new WebSocketServer({\n server,\n path: url.pathname,\n maxPayload: 16 * 1024 * 1024,\n });\n const address = server.address();\n if (!address || typeof address === 'string') {\n server.close();\n throw new Error('WebSocket listener did not bind a TCP address.');\n }\n url.port = String(address.port);\n const owner = new EndpointListener(url.toString(), server, token, options, webSockets);\n webSockets.on('error', error => {\n owner._report(error);\n owner.dispose();\n });\n webSockets.on('connection', socket => {\n const peer = owner._createPeer(() => socket.terminate());\n socket.on('error', error => owner._peerError(peer, error));\n socket.on('close', () => peer.dispose());\n const transport = new WebSocketTransport(socket, () => peer.dispose());\n peer.setTransport(transport);\n owner._accept(peer, async () => {\n await runInitializeHandshake(transport, {\n kind: 'server', isTokenAccepted: async candidate => owner._accepts(candidate),\n }, { signal: peer.signal });\n return transport;\n });\n });\n return owner;\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n for (const peer of this._peers) peer.dispose();\n for (const socket of this._sockets) socket.destroy();\n const webSocketsClosed = this._webSocketServer\n ? new Promise<void>(resolve => this._webSocketServer!.close(() => resolve()))\n : Promise.resolve();\n this._server.close(() => {\n void Promise.all([...this._tasks, webSocketsClosed]).then(() => this._finish());\n });\n }\n\n private _accepts(candidate: string | undefined): boolean {\n if (typeof candidate !== 'string') return false;\n const expected = Buffer.from(this._token);\n const actual = Buffer.from(candidate);\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n }\n\n private _createPeer(closeSocket: () => void): ListenerPeer {\n const peer = new ListenerPeer(closeSocket);\n this._peers.add(peer);\n void peer.closed.then(() => this._peers.delete(peer));\n if (this._disposed) peer.dispose();\n return peer;\n }\n\n private _accept(peer: ListenerPeer, open: () => Promise<IMessageTransport>): void {\n const task = (async () => {\n try {\n const transport = await open();\n peer.setTransport(transport);\n if (this._disposed || peer.signal.aborted) return;\n const connection = peer.connect();\n await this._options.onConnection(connection);\n peer.resumeRequests();\n } catch (error) {\n const report = !this._disposed;\n peer.dispose();\n if (report) this._report(error);\n }\n })();\n this._tasks.add(task);\n void task.then(() => this._tasks.delete(task));\n }\n\n private _peerError(peer: ListenerPeer, error: Error): void {\n if (!peer.signal.aborted && !this._disposed) this._report(error);\n peer.dispose();\n }\n\n private _report(error: unknown): void {\n const report = this._options.onError ?? (error => process.emitWarning(error));\n try {\n report(error instanceof Error ? error : new Error(String(error)));\n } catch (error) {\n process.emitWarning(new Error('startEndpoint onError callback threw', { cause: error }));\n }\n }\n}\n\nclass ListenerPeer implements IDisposable {\n private readonly _abort = new AbortController();\n public readonly signal = this._abort.signal;\n private _finish!: () => void;\n public readonly closed = new Promise<void>(resolve => { this._finish = resolve; });\n private _transport: IMessageTransport | undefined;\n private _closeChannel: (() => void) | undefined;\n private _resumeRequests: (() => void) | undefined;\n\n constructor(private readonly _closeSocket: () => void) {}\n\n public setTransport(transport: IMessageTransport): void {\n this._transport = transport;\n if (this.signal.aborted) transport.dispose();\n }\n\n public connect(): EndpointConnection {\n const rpc = JsonRpcChannel.createWithClose(this._transport!, { deferRequests: true });\n this._closeChannel = rpc.close;\n this._resumeRequests = rpc.resumeRequests;\n return {\n channel: rpc.channel, closed: this.closed, dispose: () => this.dispose(),\n resumeRequests: rpc.resumeRequests,\n };\n }\n\n public resumeRequests(): void {\n this._resumeRequests?.();\n }\n\n public dispose(): void {\n if (this.signal.aborted) return;\n this._abort.abort(new Error('Endpoint connection closed'));\n this._closeChannel?.();\n this._transport?.dispose();\n this._closeSocket();\n this._finish();\n }\n}\n\nfunction _listen(server: net.Server, listen: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const onError = (error: Error) => {\n server.removeListener('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n try {\n listen();\n } catch (error) {\n server.removeListener('error', onError);\n server.removeListener('listening', onListening);\n reject(error);\n }\n });\n}\n","import type { LinkRpcConnection } from '../connection/linkRpcConnection';\nimport type { SignedCapability } from '../identity/capability';\nimport type { SigningCallCtx } from '../identity/signingSender';\nimport type { Keypair, PrincipalId } from '../crypto/cryptoProvider';\nimport { signParams } from '../identity/metaEnvelope';\nimport { KeypairSigningIdentity } from '../identity/identity';\nimport { ErrorCode } from '../protocol/jsonRpc';\nimport {\n connectToHub,\n type HubClientHandle,\n loadOrCreateIdentity,\n loadPersistedRegisterCap,\n persistRegisterCap,\n registerHubPrefix,\n} from './hubClient';\n\nexport interface ServeOverHubIdentityOptions {\n /**\n * Stable slot id for the on-disk keypair. Typically the caller's\n * `import.meta.filename`. Same id always loads the same keypair, so\n * persistent capabilities keep working across runs.\n */\n readonly slot: string;\n\n /**\n * Override the on-disk identity / capability store directory (defaults\n * to a per-user folder, see `loadOrCreateIdentity`).\n */\n readonly storeDir?: string;\n /**\n * Override the form-3 method the helper uses to request a register\n * capability when the hub rejects an unsigned / un-capped register.\n * Defaults to\n * `hub-admin::hub-admin.capabilities::issueRegisterCap`. Setting this\n * to `null` disables the fallback (the helper just propagates the\n * `permissionRequired` error).\n */\n readonly issuerMethod?: string | null;\n /**\n * Optional human-friendly purpose string passed to the issuer service.\n * Surfaced in the user-facing approval prompt.\n */\n readonly purpose?: string;\n}\n\nexport interface ServeOverHubOptions {\n /** Service prefix to register with the hub. */\n readonly prefix: string;\n /**\n * Wires handlers onto the connection (registers interfaces, enables\n * reflection, etc). Called once per successful connection attempt,\n * after the prefix has been registered. Must not retain references to\n * the connection across calls — a fresh connection is passed every\n * reconnect.\n */\n readonly setup: (connection: LinkRpcConnection<undefined, SigningCallCtx>) => void | Promise<void>;\n /**\n * Optional human-readable name used in log lines (defaults to `prefix`).\n */\n readonly name?: string;\n /** When set, prints connect/disconnect/retry lines to this sink. */\n readonly log?: ((line: string) => void) | true;\n /**\n * Initial retry delay in ms (capped doubling on each consecutive\n * failure). Defaults to 200 ms.\n */\n readonly initialBackoffMs?: number;\n /** Cap on backoff in ms. Defaults to 5000 ms. */\n readonly maxBackoffMs?: number;\n /**\n * Abort the loop. When the signal is aborted, the current handle is\n * closed and the loop exits. The returned promise resolves once the\n * loop has finished.\n */\n readonly signal?: AbortSignal;\n /**\n * When set, registration is performed against a secure-mode hub: the\n * caller's `$hubrpc`-signed `hubServiceIdRegistry::registerServiceId` carries a\n * presented capability. The first attempt loads any cached cap from\n * disk; on `permissionRequired` the helper calls the hub-admin issuer\n * service to obtain a fresh cap, persists it, and retries. Subsequent\n * reconnects reuse the cached cap. Omit to use the legacy unsigned\n * path (only works against an openMode hub).\n */\n readonly identity?: ServeOverHubIdentityOptions;\n}\n\nexport interface ServeOverHubController {\n /** Stops the loop and closes the current handle, if any. */\n stop(): void;\n /**\n * Resolves when the loop exits (signal aborted or `stop()` called).\n * Rejects only on programmer errors thrown by `setup`.\n */\n readonly done: Promise<void>;\n}\n\n/**\n * Connect to the hub, register `prefix`, run `setup`, and keep the\n * connection alive across hub restarts. When the socket closes, retries\n * with exponential backoff (re-reading `LINKRPC_ENDPOINT` / `LINKRPC_TOKEN`\n * from `process.env` on each attempt so rotated tokens published by the\n * hub host get picked up if the parent shell re-exports them).\n *\n * The hub keeps recently-rotated tokens accepted for a grace window, so\n * even processes that captured the env at spawn time can usually reconnect\n * after a host reload without the parent re-exporting anything.\n */\nexport function serveOverHubWithReconnect(\n options: ServeOverHubOptions,\n): ServeOverHubController {\n const log = _makeLog(options.log, options.name ?? options.prefix);\n const initial = options.initialBackoffMs ?? 200;\n const max = options.maxBackoffMs ?? 5000;\n let stopped = false;\n let current: HubClientHandle | undefined;\n\n const stop = () => {\n if (stopped) return;\n stopped = true;\n current?.close();\n current = undefined;\n };\n options.signal?.addEventListener('abort', stop, { once: true });\n\n const claimer = options.identity ?\n createHubPrefixClaimer({ prefix: options.prefix, identity: options.identity, log }) :\n undefined;\n\n const done = (async () => {\n let attempt = 0;\n let backoff = initial;\n while (!stopped) {\n try {\n if (attempt > 0) log(`reconnecting (attempt ${attempt + 1})…`);\n const handle = await connectToHub();\n current = handle;\n if (claimer) {\n await claimer.claim(handle);\n } else {\n await registerHubPrefix({ handle, prefix: options.prefix });\n }\n await options.setup(handle.connection);\n log(\n attempt === 0 ?\n `connected to hub at ${handle.endpoint} (prefix \"${options.prefix}\")` :\n `reconnected to hub (prefix \"${options.prefix}\")`,\n );\n attempt = 0;\n backoff = initial;\n await new Promise<void>((resolve) => {\n handle.onClose(() => resolve());\n });\n if (stopped) break;\n log(`disconnected from hub`);\n current = undefined;\n } catch (err) {\n if (stopped) break;\n current?.close();\n current = undefined;\n const msg = err instanceof Error ? err.message : String(err);\n log(`connect failed: ${msg}; retrying in ${backoff} ms`);\n await _delay(backoff, options.signal);\n attempt++;\n backoff = Math.min(max, backoff * 2);\n }\n }\n })();\n\n return { stop, done };\n}\n\nexport interface HubPrefixClaimerOptions {\n /** Service prefix to register with the hub. */\n readonly prefix: string;\n /** Identity + capability-issuance options (see {@link ServeOverHubIdentityOptions}). */\n readonly identity: ServeOverHubIdentityOptions;\n /** When set, prints register/capability lines to this sink. */\n readonly log?: (line: string) => void;\n}\n\nexport interface HubPrefixClaimer {\n /**\n * Register the configured prefix on `handle`'s hub, performing the\n * `$hubrpc`-signed register plus capability dance: presents the cached\n * cap, and on `permissionRequired` mints a fresh one via the hub-admin\n * issuer, persists it, and retries. Call once per (re)connect, before\n * serving handlers. The loaded identity and cap are cached across calls.\n */\n claim(handle: HubClientHandle): Promise<void>;\n}\n\n/**\n * Build a reusable, stateful claimer for the signed register + capability\n * flow. Use this with {@link connectService}'s `reconnecting` connector to\n * claim a prefix on each (re)connect:\n *\n * ```ts\n * const claimer = createHubPrefixClaimer({ prefix, identity: { slot } });\n * connectService({\n * connector: reconnecting(async () => {\n * const handle = await connectToHub();\n * try { await claimer.claim(handle); } catch (e) { handle.close(); throw e; }\n * return handle;\n * }),\n * onConnect: ({ connection }) => registerService(connection),\n * });\n * ```\n */\nexport function createHubPrefixClaimer(opts: HubPrefixClaimerOptions): HubPrefixClaimer {\n const log = opts.log ?? (() => { });\n let identity: { principal: PrincipalId; keypair: Keypair; } | undefined;\n let cachedCap: SignedCapability | undefined;\n let capLoaded = false;\n return {\n async claim(handle) {\n if (!identity) {\n const loaded = await loadOrCreateIdentity({\n id: opts.identity.slot,\n ...(opts.identity.storeDir !== undefined ?\n { storeDir: opts.identity.storeDir } :\n {}),\n });\n identity = { principal: loaded.principal, keypair: loaded.keypair };\n }\n if (!capLoaded) {\n const persisted = await loadPersistedRegisterCap({\n identityId: opts.identity.slot,\n prefix: opts.prefix,\n ...(opts.identity.storeDir !== undefined ?\n { storeDir: opts.identity.storeDir } :\n {}),\n });\n cachedCap = persisted?.capability;\n capLoaded = true;\n }\n cachedCap = await _registerSigned(\n handle,\n opts.prefix,\n identity,\n cachedCap,\n opts.identity,\n log,\n );\n },\n };\n}\n\nconst DEFAULT_ISSUER_METHOD = 'hub-admin::hub-admin.capabilities::issueRegisterCap';\n\n/**\n * Try `registerHubPrefix` with `cachedCap`. On `permissionRequired`, call\n * the hub-admin issuer to mint a fresh cap, persist it, retry. Returns the\n * cap that actually worked (caller stores it for the next reconnect).\n */\nasync function _registerSigned(\n handle: HubClientHandle,\n prefix: string,\n identity: { principal: PrincipalId; keypair: Keypair; },\n cachedCap: SignedCapability | undefined,\n identityOpts: ServeOverHubIdentityOptions,\n log: (line: string) => void,\n): Promise<SignedCapability | undefined> {\n try {\n await registerHubPrefix({\n handle,\n prefix,\n identity,\n ...(cachedCap ? { capabilities: [cachedCap] } : {}),\n });\n return cachedCap;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (!_isPermissionRequired(e) || identityOpts.issuerMethod === null) {\n throw e;\n }\n log(`register denied (${msg}); requesting capability from hub-admin issuer…`);\n }\n\n const issuerMethod = identityOpts.issuerMethod ?? DEFAULT_ISSUER_METHOD;\n const signer = new KeypairSigningIdentity(\n identity.principal,\n identity.keypair.privateKey,\n );\n const signedIssueParams = await signParams({\n method: issuerMethod,\n params: {\n audience: identity.principal,\n prefix,\n ...(identityOpts.purpose !== undefined ? { purpose: identityOpts.purpose } : {}),\n },\n signingIdentity: signer,\n });\n const issueRespRaw = await handle.connection.channel.sendRequest(\n issuerMethod,\n signedIssueParams,\n );\n const issueResp = issueRespRaw as unknown as { capability?: SignedCapability; };\n if (!issueResp?.capability) {\n throw new Error('hub-admin issuer returned no capability');\n }\n const fresh = issueResp.capability;\n await persistRegisterCap({\n identityId: identityOpts.slot,\n prefix,\n capability: fresh,\n ...(identityOpts.storeDir !== undefined ? { storeDir: identityOpts.storeDir } : {}),\n });\n\n await registerHubPrefix({\n handle,\n prefix,\n identity,\n capabilities: [fresh],\n });\n return fresh;\n}\n\nfunction _isPermissionRequired(e: unknown): boolean {\n if (e === null || typeof e !== 'object') return false;\n const rec = e as { code?: unknown; };\n if (typeof rec.code === 'number') return rec.code === ErrorCode.permissionRequired;\n const msg = (e as Error).message ?? '';\n return /permission required/i.test(msg);\n}\n\nfunction _makeLog(\n sink: ((line: string) => void) | true | undefined,\n name: string,\n): (line: string) => void {\n if (!sink) return () => { };\n const write = sink === true ?\n (line: string) => {\n process.stderr.write(line + '\\n');\n } :\n sink;\n return (line) => write(`[linkrpc:${name}] ${line}`);\n}\n\nfunction _delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve();\n return;\n }\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n resolve();\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { ManagedIdentityStorage } from '../identity/managedIdentity';\n\n/**\n * A {@link ManagedIdentityStorage} backed by a single JSON file (one object\n * keyed by the storage keys). Suitable for self-managed identities that\n * persist their capability bag locally — e.g. pass it to `CapBag.load`.\n *\n * The file is created (mode 0o600) on first write; reads of a missing file\n * yield an empty store. Not concurrency-safe across processes.\n */\nexport function fileManagedIdentityStorage(file: string): ManagedIdentityStorage {\n const read = async (): Promise<Record<string, unknown>> => {\n try {\n return JSON.parse(await readFile(file, 'utf8')) as Record<string, unknown>;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw e;\n }\n };\n const write = async (data: Record<string, unknown>): Promise<void> => {\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, JSON.stringify(data, null, 2), { mode: 0o600 });\n };\n return {\n get: async <T = unknown>(key: string) => (await read())[key] as T | undefined,\n set: async (key, value) => {\n const data = await read();\n data[key] = value;\n await write(data);\n },\n delete: async (key) => {\n const data = await read();\n const existed = key in data;\n delete data[key];\n await write(data);\n return existed;\n },\n list: async (prefix = '') => Object.keys(await read()).filter((k) => k.startsWith(prefix)),\n };\n}\n","import { Principal } from '../identity/signingSender';\nimport { CapBag } from '../identity/capBag';\nimport { KeypairIdentity } from '../identity/identity';\nimport { loadOrCreateIdentity } from './hubClient';\nimport { fileManagedIdentityStorage } from './fileManagedIdentityStorage';\n\n/**\n * Self-managed principal: a local Ed25519 + X25519 keypair (created/loaded on\n * disk) signs and wraps/unwraps for outbound calls, and granted caps are\n * cached in a sibling file. Purely local — no transport needed — and\n * cheap/idempotent, so it can be re-derived on each reconnect. Used with\n * `--use-non-managed-identity`.\n */\nexport async function createSelfManagedPrincipal(identityKey: string): Promise<Principal> {\n return _selfManagedPrincipal({ id: identityKey });\n}\n\n/**\n * Self-managed principal whose keypair lives at an explicit file path (rather\n * than a slot derived from an id). Caps are cached in a sibling `.caps.json`.\n * Used by callers that want to pin the identity to a specific file, e.g. the\n * CLI's `--principal file:<path>`.\n */\nexport async function createSelfManagedPrincipalFromFile(file: string): Promise<Principal> {\n return _selfManagedPrincipal({ id: `file:${file}`, file });\n}\n\nasync function _selfManagedPrincipal(opts: { id: string; file?: string; }): Promise<Principal> {\n const id = await loadOrCreateIdentity({ id: opts.id, file: opts.file });\n const capsFile = id.file.endsWith('.json') ?\n id.file.replace(/\\.json$/, '.caps.json') :\n `${id.file}.caps.json`;\n const capBag = await CapBag.load({ storage: fileManagedIdentityStorage(capsFile) });\n const identity = new KeypairIdentity(id.principal, id.keypair.privateKey, id.wrapKeypair);\n return new Principal(identity, capBag);\n}\n","import type { JsonRpcMessage } from '../protocol/jsonRpc';\nimport type { IMessageTransport } from '../transport/messageTransport';\n\nconst HEADER_SEPARATOR = Buffer.from('\\r\\n\\r\\n');\nconst DEFAULT_MAX_HEADER_BYTES = 64 * 1024;\nconst DEFAULT_MAX_CONTENT_LENGTH = 64 * 1024 * 1024;\nconst DEFAULT_MAX_PENDING_MESSAGES = 1_024;\n\nexport interface HeaderDelimitedTransportOptions {\n readonly maxHeaderBytes?: number;\n readonly maxContentLength?: number;\n readonly maxPendingMessages?: number;\n}\n\n/**\n * LSP \"base protocol\" framing over a Node Readable/Writable pair.\n *\n * The streams remain owned by the caller: close/dispose detach listeners but\n * never end, destroy, or otherwise take ownership of either stream.\n */\nexport class HeaderDelimitedTransport implements IMessageTransport {\n private _listener: ((message: JsonRpcMessage) => void) | undefined;\n private readonly _pending: JsonRpcMessage[] = [];\n private _residual = Buffer.alloc(0);\n private _expectedLength: number | undefined;\n private _closed = false;\n private _closeReason: string | undefined;\n private readonly _maxHeaderBytes: number;\n private readonly _maxContentLength: number;\n private readonly _maxPendingMessages: number;\n\n private readonly _onDataListener = (chunk: Buffer | string): void => this._onData(chunk);\n private readonly _onEndListener = (): void => this._onEnd();\n private readonly _onInputErrorListener = (error: Error): void =>\n this.close(`Header-delimited input error: ${error.message}`);\n private readonly _onOutputErrorListener = (error: Error): void =>\n this.close(`Header-delimited output error: ${error.message}`);\n\n public constructor(\n private readonly _input: NodeJS.ReadableStream,\n private readonly _output: NodeJS.WritableStream,\n private readonly _onClose?: (reason?: string) => void,\n options: HeaderDelimitedTransportOptions = {},\n ) {\n this._maxHeaderBytes = positiveLimit(\n options.maxHeaderBytes, DEFAULT_MAX_HEADER_BYTES, 'maxHeaderBytes',\n );\n this._maxContentLength = positiveLimit(\n options.maxContentLength, DEFAULT_MAX_CONTENT_LENGTH, 'maxContentLength',\n );\n this._maxPendingMessages = positiveLimit(\n options.maxPendingMessages, DEFAULT_MAX_PENDING_MESSAGES, 'maxPendingMessages',\n );\n _input.on('data', this._onDataListener);\n _input.on('end', this._onEndListener);\n _input.on('close', this._onEndListener);\n _input.on('error', this._onInputErrorListener);\n _output.on('error', this._onOutputErrorListener);\n }\n\n public get closed(): boolean {\n return this._closed;\n }\n\n public get closeReason(): string | undefined {\n return this._closeReason;\n }\n\n public send(message: JsonRpcMessage): Promise<void> {\n if (this._closed) {\n return Promise.reject(new Error(this._closeReason ?? 'Header-delimited transport is closed'));\n }\n const body = Buffer.from(JSON.stringify(message), 'utf8');\n if (body.length > this._maxContentLength) {\n return Promise.reject(new Error(\n `Header-delimited payload exceeds ${this._maxContentLength} bytes`,\n ));\n }\n const wire = Buffer.concat([\n Buffer.from(`Content-Length: ${body.length}\\r\\n\\r\\n`, 'ascii'),\n body,\n ]);\n return new Promise<void>((resolve, reject) => {\n this._output.write(wire, (error?: Error | null) => {\n if (error) reject(error);\n else resolve();\n });\n });\n }\n\n public setListener(listener: ((message: JsonRpcMessage) => void) | undefined): void {\n this._listener = listener;\n while (this._listener && this._pending.length > 0) {\n this._listener(this._pending.shift()!);\n }\n }\n\n public dispose(): void {\n this.close('Header-delimited transport disposed');\n }\n\n public close(reason = 'Header-delimited transport closed'): void {\n if (this._closed) return;\n this._closed = true;\n this._closeReason = reason;\n this._input.off('data', this._onDataListener);\n this._input.off('end', this._onEndListener);\n this._input.off('close', this._onEndListener);\n this._input.off('error', this._onInputErrorListener);\n this._output.off('error', this._onOutputErrorListener);\n this._onClose?.(reason);\n }\n\n private _onData(chunk: Buffer | string): void {\n if (this._closed) return;\n const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;\n this._residual = this._residual.length === 0\n ? Buffer.from(bytes)\n : Buffer.concat([this._residual, bytes]);\n\n while (!this._closed) {\n if (this._expectedLength === undefined) {\n const headerEnd = this._residual.indexOf(HEADER_SEPARATOR);\n if (headerEnd < 0) {\n if (this._residual.length > this._maxHeaderBytes) {\n this.close(`Invalid header-delimited frame: header exceeds ${this._maxHeaderBytes} bytes`);\n }\n return;\n }\n if (headerEnd + HEADER_SEPARATOR.length > this._maxHeaderBytes) {\n this.close(`Invalid header-delimited frame: header exceeds ${this._maxHeaderBytes} bytes`);\n return;\n }\n try {\n this._expectedLength = parseHeaders(\n this._residual.subarray(0, headerEnd),\n this._maxContentLength,\n );\n } catch (error) {\n this.close(`Invalid header-delimited frame: ${\n error instanceof Error ? error.message : String(error)\n }`);\n return;\n }\n this._residual = this._residual.subarray(headerEnd + HEADER_SEPARATOR.length);\n }\n\n if (this._residual.length < this._expectedLength) return;\n const body = this._residual.subarray(0, this._expectedLength);\n this._residual = this._residual.subarray(this._expectedLength);\n this._expectedLength = undefined;\n let parsed: JsonRpcMessage;\n try {\n parsed = JSON.parse(body.toString('utf8')) as JsonRpcMessage;\n } catch (error) {\n this.close(`Invalid header-delimited JSON payload: ${\n error instanceof Error ? error.message : String(error)\n }`);\n return;\n }\n this._deliver(parsed);\n }\n }\n\n private _onEnd(): void {\n if (this._closed) return;\n this.close(this._expectedLength !== undefined || this._residual.length > 0\n ? 'Truncated header-delimited frame'\n : 'Header-delimited input closed');\n }\n\n private _deliver(message: JsonRpcMessage): void {\n if (this._listener) {\n this._listener(message);\n return;\n }\n if (this._pending.length >= this._maxPendingMessages) {\n this.close(`Header-delimited pending message limit ${this._maxPendingMessages} exceeded`);\n return;\n }\n this._pending.push(message);\n }\n}\n\nfunction parseHeaders(headerBytes: Buffer, maxContentLength: number): number {\n const values = new Map<string, string>();\n for (const line of headerBytes.toString('ascii').split('\\r\\n')) {\n const colon = line.indexOf(':');\n if (colon <= 0) throw new Error(`malformed header ${JSON.stringify(line)}`);\n const name = line.slice(0, colon).trim().toLowerCase();\n const value = line.slice(colon + 1).trim();\n if (values.has(name)) throw new Error(`duplicate ${name} header`);\n values.set(name, value);\n }\n const rawLength = values.get('content-length');\n if (rawLength === undefined || !/^(0|[1-9]\\d*)$/.test(rawLength)) {\n throw new Error('missing or invalid Content-Length header');\n }\n const length = Number(rawLength);\n if (!Number.isSafeInteger(length) || length > maxContentLength) {\n throw new Error(`Content-Length exceeds ${maxContentLength} bytes`);\n }\n const contentType = values.get('content-type');\n if (contentType !== undefined && !isSupportedContentType(contentType)) {\n throw new Error(`unsupported Content-Type ${JSON.stringify(contentType)}`);\n }\n return length;\n}\n\nfunction isSupportedContentType(value: string): boolean {\n const parts = value.split(';').map((part) => part.trim().toLowerCase());\n return parts[0] === 'application/vscode-jsonrpc'\n && parts.slice(1).every((part) => /^charset\\s*=\\s*\"?utf-?8\"?$/.test(part));\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number, name: string): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new Error(`${name} must be a positive integer`);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,oBACZ,QACA,WAAoC,UAAS,QAAQ,MAAM,+BAA+B,KAAK,GAChF;CACf,QAAQ,UAAU,aAAa;EAC3B,kBAAuB,UAAU,UAAU,MAAM,CAAC,CAAC,OAAM,UAAS;GAC9D,IAAI,SAAS,WAAW,SAAS,WAAW;GAC5C,QAAQ,KAAK;GACb,IAAI,CAAC,SAAS,aAAa;IACvB,SAAS,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;IACxD,SAAS,IAAI,uBAAuB;GACxC,OAAO,SAAS,QAAQ;EAC5B,CAAC;CACL;AACJ;AAEA,eAAe,kBACX,UAA6B,U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AAQ,CAAC,CAAC,CAAC,KAAK;EACzC,IAAI,OAAO,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,aAAa,KAAK,QAAQ;EAChE,OAAO,IAAI,MAAM,KAAK;CAC1B;CACA,MAAM,YAAY,OAAO,IAAI,gBAAgB;CAC7C,IAAI,cAAc,KAAA,KAAa,CAAC,iBAAiB,KAAK,SAAS,GAC3D,MAAM,IAAI,MAAM,0CAA0C;CAE9D,MAAM,SAAS,OAAO,SAAS;CAC/B,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,SAAS,kBAC1C,MAAM,IAAI,MAAM,0BAA0B,iBAAiB,OAAO;CAEtE,MAAM,cAAc,OAAO,IAAI,cAAc;CAC7C,IAAI,gBAAgB,KAAA,KAAa,CAAC,uBAAuB,WAAW,GAChE,MAAM,IAAI,MAAM,4BAA4B,KAAK,UAAU,WAAW,GAAG;CAE7E,OAAO;AACX;AAEA,SAAS,uBAAuB,OAAwB;CACpD,MAAM,QAAQ,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,YAAY,CAAC;CACtE,OAAO,MAAM,OAAO,gCACb,MAAM,MAAM,CAAC,CAAC,CAAC,OAAO,SAAS,6BAA6B,KAAK,IAAI,CAAC;AACjF;AAEA,SAAS,cAAc,OAA2B,UAAkB,MAAsB;CACtF,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC3C,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;CAExD,OAAO;AACX"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hediet/linkrpc",
|
|
3
|
-
"version": "0.0.3-next.
|
|
3
|
+
"version": "0.0.3-next.20261025.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"test": "vitest --run",
|
|
60
60
|
"test:watch": "vitest"
|
|
61
61
|
},
|
|
62
|
-
"gitHead": "
|
|
62
|
+
"gitHead": "9f4c0dd7f1cb792ba10a967e111a975ef8f65ecc",
|
|
63
63
|
"gitDirty": false,
|
|
64
64
|
"publishConfig": {
|
|
65
65
|
"tag": "next"
|