@milaboratories/pl-client 3.14.7 → 3.16.0
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/core/PromiseTracker.d.ts +1 -2
- package/dist/core/PromiseTracker.d.ts.map +1 -1
- package/dist/core/abstract_stream.d.ts +2 -3
- package/dist/core/abstract_stream.d.ts.map +1 -1
- package/dist/core/auth.d.ts +2 -4
- package/dist/core/auth.d.ts.map +1 -1
- package/dist/core/cache.d.ts +1 -3
- package/dist/core/cache.d.ts.map +1 -1
- package/dist/core/capabilities.d.ts +2 -3
- package/dist/core/capabilities.d.ts.map +1 -1
- package/dist/core/client.cjs +7 -0
- package/dist/core/client.cjs.map +1 -1
- package/dist/core/client.d.ts +8 -5
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +7 -0
- package/dist/core/client.js.map +1 -1
- package/dist/core/config.d.ts +29 -31
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/default_client.d.ts +2 -4
- package/dist/core/default_client.d.ts.map +1 -1
- package/dist/core/driver.d.ts +4 -6
- package/dist/core/driver.d.ts.map +1 -1
- package/dist/core/errors.d.ts +20 -22
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/final.d.ts +4 -5
- package/dist/core/final.d.ts.map +1 -1
- package/dist/core/ll_client.cjs +45 -18
- package/dist/core/ll_client.cjs.map +1 -1
- package/dist/core/ll_client.d.ts +21 -10
- package/dist/core/ll_client.d.ts.map +1 -1
- package/dist/core/ll_client.js +45 -18
- package/dist/core/ll_client.js.map +1 -1
- package/dist/core/ll_transaction.d.ts +4 -6
- package/dist/core/ll_transaction.d.ts.map +1 -1
- package/dist/core/stat.d.ts +2 -3
- package/dist/core/stat.d.ts.map +1 -1
- package/dist/core/transaction.cjs +2 -1
- package/dist/core/transaction.cjs.map +1 -1
- package/dist/core/transaction.d.ts +30 -32
- package/dist/core/transaction.d.ts.map +1 -1
- package/dist/core/transaction.js +2 -1
- package/dist/core/transaction.js.map +1 -1
- package/dist/core/tree_filter.d.ts +14 -10
- package/dist/core/tree_filter.d.ts.map +1 -1
- package/dist/core/types.d.ts +54 -55
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/unauth_client.cjs +79 -32
- package/dist/core/unauth_client.cjs.map +1 -1
- package/dist/core/unauth_client.d.ts +53 -20
- package/dist/core/unauth_client.d.ts.map +1 -1
- package/dist/core/unauth_client.js +79 -32
- package/dist/core/unauth_client.js.map +1 -1
- package/dist/core/user_resources.cjs +23 -0
- package/dist/core/user_resources.cjs.map +1 -1
- package/dist/core/user_resources.d.ts +33 -7
- package/dist/core/user_resources.d.ts.map +1 -1
- package/dist/core/user_resources.js +23 -0
- package/dist/core/user_resources.js.map +1 -1
- package/dist/core/wire.d.ts +5 -7
- package/dist/core/wire.d.ts.map +1 -1
- package/dist/helpers/pl.d.ts +32 -34
- package/dist/helpers/pl.d.ts.map +1 -1
- package/dist/helpers/poll.d.ts +8 -9
- package/dist/helpers/poll.d.ts.map +1 -1
- package/dist/helpers/tx_helpers.d.ts +2 -4
- package/dist/helpers/tx_helpers.d.ts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts +2 -4
- package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +310 -15
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs +19 -3
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts +29 -5
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js +19 -3
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +2336 -429
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js +309 -16
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts +51 -30
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts +7 -9
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts +6 -8
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/any.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/any.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/duration.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/duration.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/timestamp.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/timestamp.d.ts.map +1 -1
- package/dist/proto-grpc/google/rpc/code.d.ts +1 -2
- package/dist/proto-grpc/google/rpc/code.d.ts.map +1 -1
- package/dist/proto-rest/index.d.ts +6 -8
- package/dist/proto-rest/index.d.ts.map +1 -1
- package/dist/proto-rest/plapi.d.ts +248 -123
- package/dist/proto-rest/plapi.d.ts.map +1 -1
- package/dist/test/tcp-proxy.d.ts +3 -5
- package/dist/test/tcp-proxy.d.ts.map +1 -1
- package/dist/test/test_config.d.ts +13 -14
- package/dist/test/test_config.d.ts.map +1 -1
- package/package.json +6 -6
- package/src/core/client.ts +9 -0
- package/src/core/ll_client.ts +40 -13
- package/src/core/transaction.ts +2 -0
- package/src/core/unauth_client.test.ts +69 -1
- package/src/core/unauth_client.ts +108 -34
- package/src/core/unauth_client_branch.test.ts +416 -5
- package/src/core/user_resources.ts +39 -0
- package/src/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.ts +34 -3
- package/src/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.ts +431 -15
- package/src/proto-rest/plapi.ts +8 -2
package/dist/core/driver.d.ts
CHANGED
|
@@ -3,26 +3,24 @@ import { WireClientProviderFactory } from "./wire.js";
|
|
|
3
3
|
import { PlClient } from "./client.js";
|
|
4
4
|
import { RpcOptions } from "@protobuf-ts/runtime-rpc";
|
|
5
5
|
import { Dispatcher } from "undici";
|
|
6
|
-
|
|
7
6
|
//#region src/core/driver.d.ts
|
|
8
7
|
/** Drivers must implement this interface */
|
|
9
|
-
interface PlDriver {
|
|
8
|
+
export interface PlDriver {
|
|
10
9
|
close(): void;
|
|
11
10
|
}
|
|
12
11
|
/** Definition to use driver via {@link PlClient} */
|
|
13
|
-
interface PlDriverDefinition<Drv extends PlDriver> {
|
|
12
|
+
export interface PlDriverDefinition<Drv extends PlDriver> {
|
|
14
13
|
/** Used as key to only once instantiate specific drivers */
|
|
15
14
|
readonly name: string;
|
|
16
15
|
/** Initialization routine, will be executed only once for each driver in a specific client */
|
|
17
16
|
init(pl: PlClient, wireClientFactory: WireClientProviderFactory, httpDispatcher: Dispatcher): Drv;
|
|
18
17
|
}
|
|
19
|
-
declare function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions): RpcOptions;
|
|
18
|
+
export declare function addRTypeToMetadata(rType: ResourceType, options?: RpcOptions): RpcOptions;
|
|
20
19
|
/**
|
|
21
20
|
* addRTypeToHeaders adds a header that helps to route request to the right resource and controller.
|
|
22
21
|
* Without this header, API router on server side cannot route request to proper controller in internal
|
|
23
22
|
* RPC proxy.
|
|
24
23
|
*/
|
|
25
|
-
declare function createRTypeRoutingHeader(rType: ResourceType): Record<string, string>;
|
|
24
|
+
export declare function createRTypeRoutingHeader(rType: ResourceType): Record<string, string>;
|
|
26
25
|
//#endregion
|
|
27
|
-
export { PlDriver, PlDriverDefinition, addRTypeToMetadata, createRTypeRoutingHeader };
|
|
28
26
|
//# sourceMappingURL=driver.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver.d.ts","names":[],"sources":["../../src/core/driver.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"driver.d.ts","names":[],"sources":["../../src/core/driver.ts"],"mappings":";;;;;;;iBAOiB;EACf;;;iBAIe,mBAAmB,YAAY;;WAErC;;EAGT,KAAK,IAAI,UAAU,mBAAmB,2BAA2B,gBAAgB,aAAa;;wBAMhF,mBAAmB,OAAO,cAAc,UAAU,aAAU;;;;;;wBAa5D,yBAAyB,OAAO,eAAe"}
|
package/dist/core/errors.d.ts
CHANGED
|
@@ -1,51 +1,49 @@
|
|
|
1
1
|
import { Status } from "../proto-grpc/github.com/googleapis/googleapis/google/rpc/status.js";
|
|
2
|
-
|
|
3
2
|
//#region src/core/errors.d.ts
|
|
4
|
-
declare function isConnectionProblem(err: unknown, nested?: boolean): boolean;
|
|
5
|
-
declare function isUnauthenticated(err: unknown, nested?: boolean): boolean;
|
|
6
|
-
declare function isPermissionDenied(err: unknown, nested?: boolean): boolean;
|
|
7
|
-
declare function isTimeoutError(err: unknown, nested?: boolean): boolean;
|
|
8
|
-
declare function isCancelError(err: unknown, nested?: boolean): boolean;
|
|
9
|
-
declare function isAbortedError(err: unknown, nested?: boolean): boolean;
|
|
10
|
-
declare function isTimeoutOrCancelError(err: unknown, nested?: boolean): boolean;
|
|
3
|
+
export declare function isConnectionProblem(err: unknown, nested?: boolean): boolean;
|
|
4
|
+
export declare function isUnauthenticated(err: unknown, nested?: boolean): boolean;
|
|
5
|
+
export declare function isPermissionDenied(err: unknown, nested?: boolean): boolean;
|
|
6
|
+
export declare function isTimeoutError(err: unknown, nested?: boolean): boolean;
|
|
7
|
+
export declare function isCancelError(err: unknown, nested?: boolean): boolean;
|
|
8
|
+
export declare function isAbortedError(err: unknown, nested?: boolean): boolean;
|
|
9
|
+
export declare function isTimeoutOrCancelError(err: unknown, nested?: boolean): boolean;
|
|
11
10
|
/** Failures worth another attempt on an idempotent call: the peer was unreachable, or the
|
|
12
11
|
* deadline elapsed. Everything else (auth, permission, not-found, unimplemented) is a real
|
|
13
12
|
* answer from the server, and retrying it only wastes the caller's time. */
|
|
14
|
-
declare function isTransientCallFailure(err: unknown): boolean;
|
|
15
|
-
declare function isUnimplementedError(err: unknown, nested?: boolean): boolean;
|
|
16
|
-
declare function isNotFoundError(err: unknown, nested?: boolean): boolean;
|
|
17
|
-
declare const PlErrorCodeNotFound: number;
|
|
18
|
-
declare class PlError extends Error {
|
|
13
|
+
export declare function isTransientCallFailure(err: unknown): boolean;
|
|
14
|
+
export declare function isUnimplementedError(err: unknown, nested?: boolean): boolean;
|
|
15
|
+
export declare function isNotFoundError(err: unknown, nested?: boolean): boolean;
|
|
16
|
+
export declare const PlErrorCodeNotFound: number;
|
|
17
|
+
export declare class PlError extends Error {
|
|
19
18
|
readonly status: Status;
|
|
20
19
|
name: string;
|
|
21
20
|
constructor(status: Status, opts?: ErrorOptions);
|
|
22
21
|
}
|
|
23
|
-
declare function throwPlNotFoundError(message: string): never;
|
|
24
|
-
declare class RecoverablePlError extends PlError {
|
|
22
|
+
export declare function throwPlNotFoundError(message: string): never;
|
|
23
|
+
export declare class RecoverablePlError extends PlError {
|
|
25
24
|
name: string;
|
|
26
25
|
constructor(status: Status);
|
|
27
26
|
}
|
|
28
|
-
declare class UnrecoverablePlError extends PlError {
|
|
27
|
+
export declare class UnrecoverablePlError extends PlError {
|
|
29
28
|
name: string;
|
|
30
29
|
constructor(status: Status);
|
|
31
30
|
}
|
|
32
|
-
declare class UnauthenticatedError extends Error {
|
|
31
|
+
export declare class UnauthenticatedError extends Error {
|
|
33
32
|
name: string;
|
|
34
33
|
constructor(message: string);
|
|
35
34
|
}
|
|
36
|
-
declare class PermissionDeniedError extends Error {
|
|
35
|
+
export declare class PermissionDeniedError extends Error {
|
|
37
36
|
name: string;
|
|
38
37
|
constructor(message: string);
|
|
39
38
|
}
|
|
40
|
-
declare class DisconnectedError extends Error {
|
|
39
|
+
export declare class DisconnectedError extends Error {
|
|
41
40
|
name: string;
|
|
42
41
|
constructor(message: string);
|
|
43
42
|
}
|
|
44
|
-
declare class RESTError extends PlError {
|
|
43
|
+
export declare class RESTError extends PlError {
|
|
45
44
|
name: string;
|
|
46
45
|
constructor(status: Status, opts?: ErrorOptions);
|
|
47
46
|
}
|
|
48
|
-
declare function rethrowMeaningfulError(error: any, wrapIfUnknown?: boolean): never;
|
|
47
|
+
export declare function rethrowMeaningfulError(error: any, wrapIfUnknown?: boolean): never;
|
|
49
48
|
//#endregion
|
|
50
|
-
export { DisconnectedError, PermissionDeniedError, PlError, PlErrorCodeNotFound, RESTError, RecoverablePlError, UnauthenticatedError, UnrecoverablePlError, isAbortedError, isCancelError, isConnectionProblem, isNotFoundError, isPermissionDenied, isTimeoutError, isTimeoutOrCancelError, isTransientCallFailure, isUnauthenticated, isUnimplementedError, rethrowMeaningfulError, throwPlNotFoundError };
|
|
51
49
|
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/core/errors.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/core/errors.ts"],"mappings":";;wBAIgB,oBAAoB,cAAc;wBAWlC,kBAAkB,cAAc;wBAchC,mBAAmB,cAAc;wBAYjC,eAAe,cAAc;wBAW7B,cAAc,cAAc;wBAS5B,eAAe,cAAc;wBAY7B,uBAAuB,cAAc;;;;wBAcrC,uBAAuB;wBAIvB,qBAAqB,cAAc;wBAanC,gBAAgB,cAAc;qBASjC;qBAEA,gBAAgB;WAGT,QAAQ;EAF1B;EACA,YACkB,QAAQ,QACxB,OAAO;;wBAMK,qBAAqB;qBAIxB,2BAA2B;EACtC;EACA,YAAY,QAAQ;;qBAKT,6BAA6B;EACxC;EACA,YAAY,QAAQ;;qBAKT,6BAA6B;EACxC;EACA,YAAY;;qBAKD,8BAA8B;EACzC;EACA,YAAY;;qBAKD,0BAA0B;EACrC;EACA,YAAY;;qBAKD,kBAAkB;EAC7B;EACA,YAAY,QAAQ,QAAQ,OAAO;;wBAKrB,uBAAuB,YAAY"}
|
package/dist/core/final.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { BasicResourceData, ResourceData } from "./types.js";
|
|
2
2
|
import { ResourceTypeName, ResourceTypePrefix } from "@milaboratories/pl-model-common";
|
|
3
3
|
import { Optional } from "utility-types";
|
|
4
|
-
|
|
5
4
|
//#region src/core/final.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Function is used to guide multiple layers of caching in pl-client and derived pl-tree.
|
|
@@ -12,10 +11,10 @@ import { Optional } from "utility-types";
|
|
|
12
11
|
* If resource data contain information about fields, if should be taken into account, fields are undefined,
|
|
13
12
|
* "final" state should be calculated for "basic" part of resource data only.
|
|
14
13
|
*/
|
|
15
|
-
type FinalResourceDataPredicate = (resourceData: Optional<ResourceData, "fields">) => boolean;
|
|
16
|
-
declare function readyOrDuplicateOrError(r: ResourceData | BasicResourceData): boolean;
|
|
14
|
+
export type FinalResourceDataPredicate = (resourceData: Optional<ResourceData, "fields">) => boolean;
|
|
15
|
+
export declare function readyOrDuplicateOrError(r: ResourceData | BasicResourceData): boolean;
|
|
17
16
|
/** Default implementation, defining behaviour for built-in resource types. */
|
|
18
|
-
declare const DefaultFinalResourceDataPredicate: FinalResourceDataPredicate;
|
|
17
|
+
export declare const DefaultFinalResourceDataPredicate: FinalResourceDataPredicate;
|
|
19
18
|
//#endregion
|
|
20
|
-
export {
|
|
19
|
+
export { ResourceTypeName, ResourceTypePrefix };
|
|
21
20
|
//# sourceMappingURL=final.d.ts.map
|
package/dist/core/final.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"final.d.ts","names":[],"sources":["../../src/core/final.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"final.d.ts","names":[],"sources":["../../src/core/final.ts"],"mappings":";;;;;;;;;;;;;YAeY,8BACV,cAAc,SAAS;wBAGT,wBAAwB,GAAG,eAAe;;qBAsB7C,mCAAmC"}
|
package/dist/core/ll_client.cjs
CHANGED
|
@@ -436,18 +436,25 @@ var LLPlClient = class LLPlClient {
|
|
|
436
436
|
})).data, "REST: empty response for JWT token request").token;
|
|
437
437
|
}
|
|
438
438
|
}
|
|
439
|
-
/** Login via username/password. Returns a fresh JWT. Backend creates a new session per call.
|
|
439
|
+
/** Login via username/password. Returns a fresh JWT. Backend creates a new session per call.
|
|
440
|
+
* `opts.idP` names the advertised login method to route to; omitted, the backend keeps its
|
|
441
|
+
* current first-match behaviour. */
|
|
440
442
|
async loginBasic(user, password, opts = {}) {
|
|
441
443
|
const cl = this.clientProvider.get();
|
|
442
444
|
const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);
|
|
443
445
|
const role = opts.role ?? 0;
|
|
446
|
+
const basic = opts.idP === void 0 ? {
|
|
447
|
+
login: user,
|
|
448
|
+
password
|
|
449
|
+
} : {
|
|
450
|
+
login: user,
|
|
451
|
+
password,
|
|
452
|
+
idp: opts.idP
|
|
453
|
+
};
|
|
444
454
|
if (cl instanceof require_api_client.PlatformClient) return (await cl.login({
|
|
445
455
|
credentials: {
|
|
446
456
|
oneofKind: "basic",
|
|
447
|
-
basic
|
|
448
|
-
login: user,
|
|
449
|
-
password
|
|
450
|
-
}
|
|
457
|
+
basic
|
|
451
458
|
},
|
|
452
459
|
expiration: {
|
|
453
460
|
seconds: ttl,
|
|
@@ -456,10 +463,7 @@ var LLPlClient = class LLPlClient {
|
|
|
456
463
|
requestedRole: role
|
|
457
464
|
}, { timeout: require_config.DEFAULT_LOGIN_TIMEOUT }).response).token;
|
|
458
465
|
else return (0, _milaboratories_ts_helpers.notEmpty)((await cl.POST("/v1/auth/login", { body: {
|
|
459
|
-
basic
|
|
460
|
-
login: user,
|
|
461
|
-
password
|
|
462
|
-
},
|
|
466
|
+
basic,
|
|
463
467
|
expiration: `${ttl}s`,
|
|
464
468
|
requestedRole: role
|
|
465
469
|
} })).data, "REST: empty response for login request").token;
|
|
@@ -489,22 +493,34 @@ var LLPlClient = class LLPlClient {
|
|
|
489
493
|
} })).data, "REST: empty response for login request").token;
|
|
490
494
|
}
|
|
491
495
|
/** Login via SSO: forwards the raw IdP /token JSON body to the backend.
|
|
492
|
-
* Backend validates signature + nonce + audience and mints a Platforma JWT.
|
|
493
|
-
|
|
496
|
+
* Backend validates signature + nonce + audience and mints a Platforma JWT. `idP` names the
|
|
497
|
+
* advertised login method to route to; omitted, the backend keeps its current first-match
|
|
498
|
+
* behaviour. */
|
|
499
|
+
async loginSSO(tokenResponse, idP) {
|
|
494
500
|
const cl = this.clientProvider.get();
|
|
501
|
+
const sso = idP === void 0 ? { tokenResponse } : {
|
|
502
|
+
tokenResponse,
|
|
503
|
+
idp: idP
|
|
504
|
+
};
|
|
495
505
|
if (cl instanceof require_api_client.PlatformClient) return (await cl.login({ credentials: {
|
|
496
506
|
oneofKind: "sso",
|
|
497
|
-
sso
|
|
507
|
+
sso
|
|
498
508
|
} }, { timeout: require_config.DEFAULT_LOGIN_TIMEOUT }).response).token;
|
|
499
|
-
else return (0, _milaboratories_ts_helpers.notEmpty)((await cl.POST("/v1/auth/login", { body: { sso: {
|
|
509
|
+
else return (0, _milaboratories_ts_helpers.notEmpty)((await cl.POST("/v1/auth/login", { body: { sso: {
|
|
510
|
+
...sso,
|
|
511
|
+
tokenResponse: Buffer.from(tokenResponse).toString("base64")
|
|
512
|
+
} } })).data, "REST: empty response for SSO login request").token;
|
|
500
513
|
}
|
|
501
514
|
/** Request a one-time PKCE nonce + its expiry from the backend. The desktop is
|
|
502
515
|
* expected to place the nonce verbatim into the OIDC auth-request before
|
|
503
|
-
* redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}.
|
|
504
|
-
|
|
516
|
+
* redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. `idP` names the
|
|
517
|
+
* advertised login method to route to; omitted, the backend keeps its current first-match
|
|
518
|
+
* behaviour. */
|
|
519
|
+
async beginSSOLogin(idP) {
|
|
505
520
|
const cl = this.clientProvider.get();
|
|
521
|
+
const request = idP === void 0 ? {} : { idp: idP };
|
|
506
522
|
if (cl instanceof require_api_client.PlatformClient) {
|
|
507
|
-
const resp = (await cl.beginSSOLogin(
|
|
523
|
+
const resp = (await cl.beginSSOLogin(request).response).flow;
|
|
508
524
|
if (resp.oneofKind !== "publicPkce") throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);
|
|
509
525
|
const exp = (0, _milaboratories_ts_helpers.notEmpty)(resp.publicPkce.expiresAt, "beginSSOLogin: missing expiresAt");
|
|
510
526
|
return {
|
|
@@ -513,7 +529,7 @@ var LLPlClient = class LLPlClient {
|
|
|
513
529
|
clientSecret: resp.publicPkce.clientSecret
|
|
514
530
|
};
|
|
515
531
|
} else {
|
|
516
|
-
const pkce = (0, _milaboratories_ts_helpers.notEmpty)((0, _milaboratories_ts_helpers.notEmpty)((await cl.POST("/v1/auth/sso/begin-login", { body:
|
|
532
|
+
const pkce = (0, _milaboratories_ts_helpers.notEmpty)((0, _milaboratories_ts_helpers.notEmpty)((await cl.POST("/v1/auth/sso/begin-login", { body: request })).data, "REST: empty response for beginSSOLogin request").publicPkce, "REST: missing publicPkce in beginSSOLogin");
|
|
517
533
|
return {
|
|
518
534
|
nonce: pkce.nonce,
|
|
519
535
|
expiresAt: new Date(pkce.expiresAt),
|
|
@@ -638,7 +654,8 @@ var LLPlClient = class LLPlClient {
|
|
|
638
654
|
else resp = { methods: ((0, _milaboratories_ts_helpers.notEmpty)((await cl.GET("/v1/auth/methods")).data, "REST: empty response for auth methods request").methods ?? []).map((m) => {
|
|
639
655
|
const base = {
|
|
640
656
|
id: m.id,
|
|
641
|
-
description: m.description
|
|
657
|
+
description: m.description,
|
|
658
|
+
title: m.title
|
|
642
659
|
};
|
|
643
660
|
if (m.basic !== void 0) return {
|
|
644
661
|
...base,
|
|
@@ -726,6 +743,16 @@ var LLPlClient = class LLPlClient {
|
|
|
726
743
|
if (!(cl instanceof require_api_client.PlatformClient)) throw new Error("ListUsers requires gRPC wire protocol; REST is not supported");
|
|
727
744
|
return (await cl.listUsers({})).response.users;
|
|
728
745
|
}
|
|
746
|
+
/** Deletes a user account: the record, its identity-index entries (login, email and any
|
|
747
|
+
* alternative of either), its grants, and its root resource with everything still attached
|
|
748
|
+
* under it. Admin/controller credentials only, and irreversible — re-attach anything worth
|
|
749
|
+
* keeping to another user's root first.
|
|
750
|
+
* gRPC-only (unary, no REST binding), like {@link listUsers}. */
|
|
751
|
+
async deleteUser(login) {
|
|
752
|
+
const cl = this.clientProvider.get();
|
|
753
|
+
if (!(cl instanceof require_api_client.PlatformClient)) throw new Error("DeleteUser requires gRPC wire protocol; REST is not supported");
|
|
754
|
+
return (await cl.deleteUser({ login })).response;
|
|
755
|
+
}
|
|
729
756
|
async txSync(txId) {
|
|
730
757
|
const cl = this.clientProvider.get();
|
|
731
758
|
if (cl instanceof require_api_client.PlatformClient) await cl.txSync({ txId: BigInt(txId) });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ll_client.cjs","names":["plAddressToConfig","inferAuthRefreshTime","interceptors","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","GrpcTransport","deriveUnaryDeadline","smoothRtt","isTransientCallFailure","parsePlJwt","isUnauthenticated","parseResponseError","InterceptingCall","GrpcStatus","DEFAULT_LOGIN_TIMEOUT","Timestamp","hasCapability","isAbortedError","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport {\n plAddressToConfig,\n type wireProtocol,\n SUPPORTED_WIRE_PROTOCOLS,\n DEFAULT_LOGIN_TIMEOUT,\n deriveUnaryDeadline,\n smoothRtt,\n} from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isTransientCallFailure, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n/** Bounded retry for idempotent unary calls. Deliberately short: these calls sit on the\n * connect path and gate the UI, so a few quick attempts beat a long grind. */\nconst IDEMPOTENT_RETRY_OPTIONS: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 4,\n initialDelay: 200,\n backoffMultiplier: 2,\n jitter: 0.3,\n maxDelay: 2_000,\n};\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n /** The live GrpcOptions object handed to GrpcTransport. The transport keeps it by\n * reference and re-reads it on every call, so mutating `timeout` here retunes\n * subsequent deadlines without tearing down the connection. */\n private _grpcOptions?: GrpcOptions;\n\n /** Smoothed round-trip estimate in ms, from ping timings. Undefined until the first\n * successful ping, in which case the configured deadline is used as-is. */\n private _rttMs?: number;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n // Retried, not bare: this ping is the first contact with the server, so DNS and LB\n // warm-up land here. A single transient failure must not fail the whole connect.\n // (Not inside ping() itself: the autodetect path already wraps it in its own retry.)\n if (!pl._serverInfo) await pl.withIdempotentRetry(\"ping\", () => pl.ping());\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.unaryDeadline(),\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._grpcOptions = grpcOptions;\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n /** Unary deadline derived from the observed RTT, floored by the configured value so\n * a fast link behaves exactly as before, and capped by\n * {@link MAX_ADAPTIVE_REQUEST_TIMEOUT}. */\n private unaryDeadline(): number {\n return deriveUnaryDeadline(this.conf.defaultRequestTimeout, this._rttMs);\n }\n\n /** Folds a fresh round-trip sample into the estimate and retunes the live unary\n * deadline. Called after every successful ping. */\n private recordRtt(sampleMs: number): void {\n this._rttMs = smoothRtt(this._rttMs, sampleMs);\n\n if (this._grpcOptions) {\n const next = this.unaryDeadline();\n if (next !== this._grpcOptions.timeout) {\n this.ops.logger?.info(\n `Unary deadline retuned to ${next}ms (rtt estimate ${Math.round(this._rttMs)}ms)`,\n );\n this._grpcOptions.timeout = next;\n }\n }\n }\n\n /** Smoothed round-trip estimate in ms, or undefined before the first ping. */\n public get rttEstimateMs(): number | undefined {\n return this._rttMs;\n }\n\n /** Runs an idempotent unary call with a bounded retry on transient transport failures.\n * Safe only for calls with no side effects, since a retry may duplicate the request. */\n private async withIdempotentRetry<T>(name: string, cb: () => Promise<T>): Promise<T> {\n return await retry(cb, IDEMPOTENT_RETRY_OPTIONS, (e: unknown) => {\n if (!isTransientCallFailure(e)) return false;\n this.ops.logger?.info(`${name}: transient failure, retrying. err=${String(e)}`);\n return true;\n });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta, timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken(\n {\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n // Ping is the cheapest call we make, so its duration is our best RTT proxy.\n const startedAt = performance.now();\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this.recordRtt(performance.now() - startedAt);\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n // Retryable even with createIfNotExists: the call is get-or-create keyed on login, so a\n // second attempt returns the existing root rather than making another one.\n return await this.withIdempotentRetry(\"getUserRoot\", () => this.getUserRootOnce(opts));\n }\n\n private async getUserRootOnce(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,2BAAyC;CAC7C,MAAM;CACN,aAAa;CACb,cAAc;CACd,mBAAmB;CACnB,QAAQ;CACR,UAAU;AACZ;AAKA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CACA;CAJnB,SAAqC,KAAA;CAErC,YACE,UACA,mBACA;EAFiB,KAAA,WAAA;EACA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BAAiB;KAChC,YAAY,SAAS;KAErB,YAAY,OAAO,WACjB,OAAO,SAAS,KAAK;MAEnB,WAAW;MACX,SAAS;OAAE,WAAW;OAAe,aAAa,CAAC;MAAE;KACvD,CAAC;IACL,CACF;GACF;GAEA,MAAM,IAAI,MAAM,oDAAoD,KAAK,YAAY;EACvF,CAAC;CACH;;CAGA,MAAa,QAAQ;EACnB,IAAI,KAAK,eAAe,SAAS,QAC/B,KAAK,eAAe,UAAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"ll_client.cjs","names":["plAddressToConfig","inferAuthRefreshTime","interceptors","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","GrpcTransport","deriveUnaryDeadline","smoothRtt","isTransientCallFailure","parsePlJwt","isUnauthenticated","parseResponseError","InterceptingCall","GrpcStatus","DEFAULT_LOGIN_TIMEOUT","Timestamp","hasCapability","isAbortedError","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport {\n plAddressToConfig,\n type wireProtocol,\n SUPPORTED_WIRE_PROTOCOLS,\n DEFAULT_LOGIN_TIMEOUT,\n deriveUnaryDeadline,\n smoothRtt,\n} from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isTransientCallFailure, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n/** Bounded retry for idempotent unary calls. Deliberately short: these calls sit on the\n * connect path and gate the UI, so a few quick attempts beat a long grind. */\nconst IDEMPOTENT_RETRY_OPTIONS: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 4,\n initialDelay: 200,\n backoffMultiplier: 2,\n jitter: 0.3,\n maxDelay: 2_000,\n};\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n /** The live GrpcOptions object handed to GrpcTransport. The transport keeps it by\n * reference and re-reads it on every call, so mutating `timeout` here retunes\n * subsequent deadlines without tearing down the connection. */\n private _grpcOptions?: GrpcOptions;\n\n /** Smoothed round-trip estimate in ms, from ping timings. Undefined until the first\n * successful ping, in which case the configured deadline is used as-is. */\n private _rttMs?: number;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n // Retried, not bare: this ping is the first contact with the server, so DNS and LB\n // warm-up land here. A single transient failure must not fail the whole connect.\n // (Not inside ping() itself: the autodetect path already wraps it in its own retry.)\n if (!pl._serverInfo) await pl.withIdempotentRetry(\"ping\", () => pl.ping());\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.unaryDeadline(),\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._grpcOptions = grpcOptions;\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n /** Unary deadline derived from the observed RTT, floored by the configured value so\n * a fast link behaves exactly as before, and capped by\n * {@link MAX_ADAPTIVE_REQUEST_TIMEOUT}. */\n private unaryDeadline(): number {\n return deriveUnaryDeadline(this.conf.defaultRequestTimeout, this._rttMs);\n }\n\n /** Folds a fresh round-trip sample into the estimate and retunes the live unary\n * deadline. Called after every successful ping. */\n private recordRtt(sampleMs: number): void {\n this._rttMs = smoothRtt(this._rttMs, sampleMs);\n\n if (this._grpcOptions) {\n const next = this.unaryDeadline();\n if (next !== this._grpcOptions.timeout) {\n this.ops.logger?.info(\n `Unary deadline retuned to ${next}ms (rtt estimate ${Math.round(this._rttMs)}ms)`,\n );\n this._grpcOptions.timeout = next;\n }\n }\n }\n\n /** Smoothed round-trip estimate in ms, or undefined before the first ping. */\n public get rttEstimateMs(): number | undefined {\n return this._rttMs;\n }\n\n /** Runs an idempotent unary call with a bounded retry on transient transport failures.\n * Safe only for calls with no side effects, since a retry may duplicate the request. */\n private async withIdempotentRetry<T>(name: string, cb: () => Promise<T>): Promise<T> {\n return await retry(cb, IDEMPOTENT_RETRY_OPTIONS, (e: unknown) => {\n if (!isTransientCallFailure(e)) return false;\n this.ops.logger?.info(`${name}: transient failure, retrying. err=${String(e)}`);\n return true;\n });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta, timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call.\n * `opts.idP` names the advertised login method to route to; omitted, the backend keeps its\n * current first-match behaviour. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role; idP?: string } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const basic =\n opts.idP === undefined ? { login: user, password } : { login: user, password, idp: opts.idP };\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"basic\",\n basic,\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic,\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. `idP` names the\n * advertised login method to route to; omitted, the backend keeps its current first-match\n * behaviour. */\n public async loginSSO(tokenResponse: Uint8Array, idP?: string): Promise<string> {\n const cl = this.clientProvider.get();\n const sso = idP === undefined ? { tokenResponse } : { tokenResponse, idp: idP };\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"sso\",\n sso,\n },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { ...sso, tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. `idP` names the\n * advertised login method to route to; omitted, the backend keeps its current first-match\n * behaviour. */\n public async beginSSOLogin(\n idP?: string,\n ): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n const request = idP === undefined ? {} : { idp: idP };\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin(request).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: request as any })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken(\n {\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n // Ping is the cheapest call we make, so its duration is our best RTT proxy.\n const startedAt = performance.now();\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this.recordRtt(performance.now() - startedAt);\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description, title: m.title };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n // Retryable even with createIfNotExists: the call is get-or-create keyed on login, so a\n // second attempt returns the existing root rather than making another one.\n return await this.withIdempotentRetry(\"getUserRoot\", () => this.getUserRootOnce(opts));\n }\n\n private async getUserRootOnce(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n /** Deletes a user account: the record, its identity-index entries (login, email and any\n * alternative of either), its grants, and its root resource with everything still attached\n * under it. Admin/controller credentials only, and irreversible — re-attach anything worth\n * keeping to another user's root first.\n * gRPC-only (unary, no REST binding), like {@link listUsers}. */\n public async deleteUser(login: string): Promise<grpcTypes.AuthAPI_DeleteUser_Response> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"DeleteUser requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.deleteUser({ login })).response;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,2BAAyC;CAC7C,MAAM;CACN,aAAa;CACb,cAAc;CACd,mBAAmB;CACnB,QAAQ;CACR,UAAU;AACZ;AAKA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CAC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