@btps/sdk 0.0.0-stage → 1.1.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/CHANGELOG.md +149 -0
- package/LICENSE +190 -0
- package/NOTICE +25 -0
- package/README.md +261 -2
- package/dist/client/btpsAgent.d.ts +20 -0
- package/dist/client/btpsAgent.js +172 -0
- package/dist/client/btpsClient.d.ts +202 -0
- package/dist/client/btpsClient.js +602 -0
- package/dist/client/btpsTransporter.d.ts +52 -0
- package/dist/client/btpsTransporter.js +249 -0
- package/dist/client/constants.ts/index.d.ts +11 -0
- package/dist/client/constants.ts/index.js +20 -0
- package/dist/client/index.d.ts +12 -0
- package/dist/client/index.js +27 -0
- package/dist/client/libs/schema.d.ts +27604 -0
- package/dist/client/libs/schema.js +56 -0
- package/dist/client/libs/timeouts.d.ts +22 -0
- package/dist/client/libs/timeouts.js +19 -0
- package/dist/client/types/index.d.ts +155 -0
- package/dist/client/types/index.js +7 -0
- package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
- package/dist/core/authentication/BtpsAuthentication.js +293 -0
- package/dist/core/authentication/index.d.ts +11 -0
- package/dist/core/authentication/index.js +12 -0
- package/dist/core/authentication/keyProof.d.ts +18 -0
- package/dist/core/authentication/keyProof.js +16 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
- package/dist/core/authentication/types.d.ts +135 -0
- package/dist/core/authentication/types.js +7 -0
- package/dist/core/crypto/decryptVerify.d.ts +9 -0
- package/dist/core/crypto/decryptVerify.js +45 -0
- package/dist/core/crypto/decrypter-interface.d.ts +25 -0
- package/dist/core/crypto/decrypter-interface.js +7 -0
- package/dist/core/crypto/index.d.ts +77 -0
- package/dist/core/crypto/index.js +210 -0
- package/dist/core/crypto/jcs.d.ts +28 -0
- package/dist/core/crypto/jcs.js +60 -0
- package/dist/core/crypto/keygen.d.ts +9 -0
- package/dist/core/crypto/keygen.js +35 -0
- package/dist/core/crypto/pem-decrypter.d.ts +26 -0
- package/dist/core/crypto/pem-decrypter.js +52 -0
- package/dist/core/crypto/pem-signer.d.ts +21 -0
- package/dist/core/crypto/pem-signer.js +34 -0
- package/dist/core/crypto/signEncrypt.d.ts +34 -0
- package/dist/core/crypto/signEncrypt.js +75 -0
- package/dist/core/crypto/signer-interface.d.ts +22 -0
- package/dist/core/crypto/signer-interface.js +7 -0
- package/dist/core/crypto/types.d.ts +79 -0
- package/dist/core/crypto/types.js +7 -0
- package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
- package/dist/core/delegation/BtpsDelegator.js +118 -0
- package/dist/core/delegation/index.d.ts +7 -0
- package/dist/core/delegation/index.js +8 -0
- package/dist/core/error/constant.d.ts +66 -0
- package/dist/core/error/constant.js +194 -0
- package/dist/core/error/index.d.ts +35 -0
- package/dist/core/error/index.js +52 -0
- package/dist/core/error/types.d.ts +16 -0
- package/dist/core/error/types.js +7 -0
- package/dist/core/server/constants/btps-protocol.d.ts +17 -0
- package/dist/core/server/constants/btps-protocol.js +25 -0
- package/dist/core/server/constants/control.d.ts +7 -0
- package/dist/core/server/constants/control.js +11 -0
- package/dist/core/server/constants/currency.d.ts +7 -0
- package/dist/core/server/constants/currency.js +332 -0
- package/dist/core/server/constants/index.d.ts +26 -0
- package/dist/core/server/constants/index.js +61 -0
- package/dist/core/server/constants/limits.d.ts +50 -0
- package/dist/core/server/constants/limits.js +50 -0
- package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
- package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
- package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
- package/dist/core/server/helpers/InMemoryQueue.js +35 -0
- package/dist/core/server/helpers/index.d.ts +8 -0
- package/dist/core/server/helpers/index.js +9 -0
- package/dist/core/server/schemas/artifacts/agentSchema.d.ts +4565 -0
- package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
- package/dist/core/server/schemas/artifacts/artifacts.d.ts +4920 -0
- package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
- package/dist/core/server/schemas/artifacts/controlSchema.d.ts +23 -0
- package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
- package/dist/core/server/schemas/artifacts/identityLookupSchema.d.ts +32 -0
- package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
- package/dist/core/server/schemas/artifacts/transporterSchema.d.ts +553 -0
- package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
- package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
- package/dist/core/server/schemas/helpers.d.ts +1612 -0
- package/dist/core/server/schemas/helpers.js +87 -0
- package/dist/core/server/schemas/responseSchema.d.ts +6918 -0
- package/dist/core/server/schemas/responseSchema.js +86 -0
- package/dist/core/server/schemas/schema.d.ts +4916 -0
- package/dist/core/server/schemas/schema.js +70 -0
- package/dist/core/server/schemas/shared.d.ts +21 -0
- package/dist/core/server/schemas/shared.js +18 -0
- package/dist/core/server/types.d.ts +172 -0
- package/dist/core/server/types.js +7 -0
- package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
- package/dist/core/storage/AbstractIdentityStore.js +13 -0
- package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
- package/dist/core/storage/AbstractStorageStore.js +17 -0
- package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
- package/dist/core/storage/JsonIdentityStore.js +39 -0
- package/dist/core/storage/JsonStorageStore.d.ts +59 -0
- package/dist/core/storage/JsonStorageStore.js +110 -0
- package/dist/core/storage/index.d.ts +11 -0
- package/dist/core/storage/index.js +18 -0
- package/dist/core/storage/types.d.ts +28 -0
- package/dist/core/storage/types.js +7 -0
- package/dist/core/trust/index.d.ts +10 -0
- package/dist/core/trust/index.js +15 -0
- package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
- package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
- package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
- package/dist/core/trust/storage/JsonTrustStore.js +42 -0
- package/dist/core/trust/trustUtils.d.ts +78 -0
- package/dist/core/trust/trustUtils.js +41 -0
- package/dist/core/trust/types.d.ts +53 -0
- package/dist/core/trust/types.js +7 -0
- package/dist/core/utils/identity.d.ts +20 -0
- package/dist/core/utils/identity.js +22 -0
- package/dist/core/utils/index.d.ts +70 -0
- package/dist/core/utils/index.js +124 -0
- package/dist/core/utils/types.d.ts +10 -0
- package/dist/core/utils/types.js +7 -0
- package/dist/core/utils/validation.d.ts +14 -0
- package/dist/core/utils/validation.js +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/server/btpsServer.d.ts +292 -0
- package/dist/server/btpsServer.js +827 -0
- package/dist/server/index.d.ts +11 -0
- package/dist/server/index.js +15 -0
- package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
- package/dist/server/libs/abstractRateLimiter.js +15 -0
- package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
- package/dist/server/libs/artifactSizeGuard.js +44 -0
- package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
- package/dist/server/libs/artifactTimeWindow.js +30 -0
- package/dist/server/libs/btpsFactory.d.ts +29 -0
- package/dist/server/libs/btpsFactory.js +49 -0
- package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
- package/dist/server/libs/btpsLightweightFactory.js +37 -0
- package/dist/server/libs/btpsRegistry.d.ts +14 -0
- package/dist/server/libs/btpsRegistry.js +16 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
- package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
- package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
- package/dist/server/libs/connectionTimeout.d.ts +16 -0
- package/dist/server/libs/connectionTimeout.js +14 -0
- package/dist/server/libs/defaultMiddleware.d.ts +8 -0
- package/dist/server/libs/defaultMiddleware.js +128 -0
- package/dist/server/libs/inFlightLimit.d.ts +18 -0
- package/dist/server/libs/inFlightLimit.js +17 -0
- package/dist/server/libs/index.d.ts +18 -0
- package/dist/server/libs/index.js +34 -0
- package/dist/server/libs/middlewareManager.d.ts +59 -0
- package/dist/server/libs/middlewareManager.js +126 -0
- package/dist/server/libs/type.d.ts +22 -0
- package/dist/server/libs/type.js +7 -0
- package/dist/server/types.d.ts +236 -0
- package/dist/server/types.js +7 -0
- package/package.json +126 -4
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import {
|
|
10
|
+
BtpAgentQuerySchema,
|
|
11
|
+
BtpAgentMutationSchema,
|
|
12
|
+
BtpIdsPayloadSchema,
|
|
13
|
+
BtpAgentCreateSchema,
|
|
14
|
+
BtpCryptoOptionsSchema,
|
|
15
|
+
BtpsAgentActionTypeSchema
|
|
16
|
+
} from "../../core/server/schemas/schema.js";
|
|
17
|
+
import { identitySchema } from "../../core/server/schemas/shared.js";
|
|
18
|
+
import { validateAgentDocument } from "../../core/server/schemas/helpers.js";
|
|
19
|
+
import {
|
|
20
|
+
BtpAuthReqDocSchema,
|
|
21
|
+
BtpDocumentSchema,
|
|
22
|
+
BtpLifecycleEventSchema,
|
|
23
|
+
BtpTrustReqDocSchema,
|
|
24
|
+
BtpTrustResDocSchema
|
|
25
|
+
} from "../../core/server/schemas/btpsDocsSchema.js";
|
|
26
|
+
const BtpsAgentOptionsSchema = BtpCryptoOptionsSchema.optional(), BtpsAgentCommandDocumentSchema = z.union([
|
|
27
|
+
BtpTrustReqDocSchema,
|
|
28
|
+
BtpTrustResDocSchema,
|
|
29
|
+
BtpDocumentSchema,
|
|
30
|
+
BtpLifecycleEventSchema,
|
|
31
|
+
BtpAuthReqDocSchema,
|
|
32
|
+
BtpAgentQuerySchema,
|
|
33
|
+
BtpAgentMutationSchema,
|
|
34
|
+
BtpIdsPayloadSchema,
|
|
35
|
+
BtpAgentCreateSchema
|
|
36
|
+
]).optional(), BtpsAgentCommandSchema = z.object({
|
|
37
|
+
actionType: BtpsAgentActionTypeSchema,
|
|
38
|
+
to: identitySchema,
|
|
39
|
+
document: BtpsAgentCommandDocumentSchema.optional(),
|
|
40
|
+
options: BtpCryptoOptionsSchema.extend({ relatesTo: z.string().min(1).optional() }).optional()
|
|
41
|
+
}), BtpsAgentCommandCallSchema = BtpsAgentCommandSchema.refine(
|
|
42
|
+
(data) => validateAgentDocument(data.actionType, null, data.document),
|
|
43
|
+
{
|
|
44
|
+
message: "Document is required for this action type or document format is invalid",
|
|
45
|
+
path: ["document"]
|
|
46
|
+
}
|
|
47
|
+
).refine((data) => data.actionType === "event.send" == (data.options?.relatesTo !== void 0), {
|
|
48
|
+
message: "options.relatesTo is required on event.send and only there",
|
|
49
|
+
path: ["options", "relatesTo"]
|
|
50
|
+
});
|
|
51
|
+
export {
|
|
52
|
+
BtpsAgentCommandCallSchema,
|
|
53
|
+
BtpsAgentCommandDocumentSchema,
|
|
54
|
+
BtpsAgentCommandSchema,
|
|
55
|
+
BtpsAgentOptionsSchema
|
|
56
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
/** How long a sender waits to connect to a receiver, at least and by default: 5 seconds. */
|
|
8
|
+
export declare const MIN_CONNECT_TIMEOUT_MS = 5000;
|
|
9
|
+
export declare const DEFAULT_CONNECT_TIMEOUT_MS = 5000;
|
|
10
|
+
/**
|
|
11
|
+
* How long a sender waits for the answer once it has sent: at least 10 seconds,
|
|
12
|
+
* 20 by default. Every receiver can count on that long to answer normally,
|
|
13
|
+
* rather than answer "try again" during a slow moment.
|
|
14
|
+
*/
|
|
15
|
+
export declare const MIN_REPLY_TIMEOUT_MS = 10000;
|
|
16
|
+
export declare const DEFAULT_REPLY_TIMEOUT_MS = 20000;
|
|
17
|
+
/**
|
|
18
|
+
* A wait the client uses, in milliseconds. One it cannot use as given never
|
|
19
|
+
* stops the client: it is warned about and replaced by the minimum (when too
|
|
20
|
+
* short) or the default (when not a number of milliseconds at all).
|
|
21
|
+
*/
|
|
22
|
+
export declare const resolveTimeoutMs: (name: "connectTimeoutMs" | "replyTimeoutMs", configured: number | undefined, minimum: number, fallback: number) => number;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const MIN_CONNECT_TIMEOUT_MS = 5e3, DEFAULT_CONNECT_TIMEOUT_MS = 5e3, MIN_REPLY_TIMEOUT_MS = 1e4, DEFAULT_REPLY_TIMEOUT_MS = 2e4, resolveTimeoutMs = (name, configured, minimum, fallback) => configured === void 0 ? fallback : !Number.isFinite(configured) || configured <= 0 ? (console.warn(
|
|
9
|
+
`[BtpsClient] ${name} ${configured} is not a usable time; using the default ${fallback} ms`
|
|
10
|
+
), fallback) : configured < minimum ? (console.warn(
|
|
11
|
+
`[BtpsClient] ${name} ${configured} is below the ${minimum} ms minimum; using ${minimum} ms`
|
|
12
|
+
), minimum) : configured;
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_CONNECT_TIMEOUT_MS,
|
|
15
|
+
DEFAULT_REPLY_TIMEOUT_MS,
|
|
16
|
+
MIN_CONNECT_TIMEOUT_MS,
|
|
17
|
+
MIN_REPLY_TIMEOUT_MS,
|
|
18
|
+
resolveTimeoutMs
|
|
19
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
import type { BTPCryptoOptions } from '../../core/crypto/types.js';
|
|
8
|
+
import type { Signer } from '../../core/crypto/signer-interface.js';
|
|
9
|
+
import type { Decrypter } from '../../core/crypto/decrypter-interface.js';
|
|
10
|
+
import type { BTPErrorException } from '../../core/error/index.js';
|
|
11
|
+
import type { BtpsClient } from '../../client/btpsClient.js';
|
|
12
|
+
import type { BTPAgentMutation, BTPAgentQuery, BTPDocType, BTPIdsPayload, BTPAuthReqDoc, BTPServerResponse, AgentAction } from '../../server/index.js';
|
|
13
|
+
import type { ConnectionOptions, TLSSocket } from 'tls';
|
|
14
|
+
export interface BTPTransporterMetrics {
|
|
15
|
+
totalConnections: number;
|
|
16
|
+
activeConnections: number;
|
|
17
|
+
}
|
|
18
|
+
export interface BTPClientOptions {
|
|
19
|
+
to: string;
|
|
20
|
+
maxRetries?: number;
|
|
21
|
+
retryDelayMs?: number;
|
|
22
|
+
/** How long to wait to connect, in ms: at least 5000, 5000 by default */
|
|
23
|
+
connectTimeoutMs?: number;
|
|
24
|
+
/** How long `send()` waits for the answer, in ms: at least 10000, 20000 by default */
|
|
25
|
+
replyTimeoutMs?: number;
|
|
26
|
+
/** Closes the connection after this long with no artifact waiting for an answer, in ms; reconnects on the next send. Off when not set */
|
|
27
|
+
connectionTimeoutMs?: number;
|
|
28
|
+
btpMtsOptions?: Omit<ConnectionOptions, 'port' | 'host'>;
|
|
29
|
+
host?: string;
|
|
30
|
+
hostSelector?: string;
|
|
31
|
+
/** With `host`: the identity operating that host, which signs its lookup answers. Otherwise read from DNS (`op`). */
|
|
32
|
+
hostOperator?: string;
|
|
33
|
+
version?: string;
|
|
34
|
+
port?: number;
|
|
35
|
+
maxQueue?: number;
|
|
36
|
+
}
|
|
37
|
+
/** An agent and its device key: a PEM key pair, or a Signer (and Decrypter) holding it elsewhere, such as the device's own keystore. */
|
|
38
|
+
export type BTPAgent = {
|
|
39
|
+
id: string;
|
|
40
|
+
identityKey: string;
|
|
41
|
+
identityCert: string;
|
|
42
|
+
} | {
|
|
43
|
+
id: string;
|
|
44
|
+
signer: Signer;
|
|
45
|
+
decrypter?: Decrypter;
|
|
46
|
+
};
|
|
47
|
+
export interface BTPAgentOptions extends Omit<BTPClientOptions, 'to'> {
|
|
48
|
+
agent: BTPAgent;
|
|
49
|
+
btpIdentity: string;
|
|
50
|
+
}
|
|
51
|
+
export interface BTPTransporterOptions extends Omit<BTPClientOptions, 'to'> {
|
|
52
|
+
maxConnections?: number;
|
|
53
|
+
connectionTTLSeconds?: number;
|
|
54
|
+
}
|
|
55
|
+
export type BtpsAgentDoc = BTPDocType | BTPAuthReqDoc | BTPAgentMutation | BTPIdsPayload | BTPAgentQuery;
|
|
56
|
+
export type BtpsAgentCommandOptions = BTPCryptoOptions & {
|
|
57
|
+
/** Required on `event.send`, refused elsewhere: the id of the `BTPS_DOC` artifact that delivered the invoice. */
|
|
58
|
+
relatesTo?: string;
|
|
59
|
+
};
|
|
60
|
+
export type BtpsAgentCommandParams = {
|
|
61
|
+
actionType: AgentAction;
|
|
62
|
+
to: string;
|
|
63
|
+
document?: BtpsAgentDoc;
|
|
64
|
+
options?: BtpsAgentCommandOptions;
|
|
65
|
+
};
|
|
66
|
+
export interface ConnectionStates {
|
|
67
|
+
isConnecting: boolean;
|
|
68
|
+
isConnected: boolean;
|
|
69
|
+
isDraining: boolean;
|
|
70
|
+
isDestroyed: boolean;
|
|
71
|
+
shouldRetry: boolean;
|
|
72
|
+
}
|
|
73
|
+
export interface BTPSRetryInfo {
|
|
74
|
+
willRetry: boolean;
|
|
75
|
+
retriesLeft: number;
|
|
76
|
+
attempt: number;
|
|
77
|
+
}
|
|
78
|
+
export type BtpsClientErrorInfo = BTPSRetryInfo & {
|
|
79
|
+
error: BTPErrorException;
|
|
80
|
+
};
|
|
81
|
+
export interface UpdateBTPClientOptions {
|
|
82
|
+
maxRetries?: number;
|
|
83
|
+
retryDelayMs?: number;
|
|
84
|
+
connectTimeoutMs?: number;
|
|
85
|
+
replyTimeoutMs?: number;
|
|
86
|
+
connectionTimeoutMs?: number;
|
|
87
|
+
maxQueue?: number;
|
|
88
|
+
}
|
|
89
|
+
/** What the client emits on `connected`. */
|
|
90
|
+
export type BtpsClientConnectedInfo = {
|
|
91
|
+
identity: string;
|
|
92
|
+
retries: number;
|
|
93
|
+
states: ConnectionStates;
|
|
94
|
+
socket: TLSSocket;
|
|
95
|
+
};
|
|
96
|
+
export type BtpsClientEvents = {
|
|
97
|
+
connected: (connectedInfo: BtpsClientConnectedInfo) => void;
|
|
98
|
+
end: (endInfo: BtpsClientErrorInfo) => void;
|
|
99
|
+
error: (errorInfo: BtpsClientErrorInfo) => void;
|
|
100
|
+
message: (msg: BTPClientResponse & {
|
|
101
|
+
validSignature: boolean;
|
|
102
|
+
}) => void;
|
|
103
|
+
close: (closeInfo: BtpsClientErrorInfo) => void;
|
|
104
|
+
};
|
|
105
|
+
export type BTPConnectionInternal = BTPConnection & {
|
|
106
|
+
timeout: NodeJS.Timeout;
|
|
107
|
+
listeners?: BtpsClientEvents;
|
|
108
|
+
/** Sends waiting for their answer: the connection is never closed while any are */
|
|
109
|
+
inFlight: number;
|
|
110
|
+
/** Set by updateConnection; the transporter's own TTL otherwise */
|
|
111
|
+
ttlSeconds?: number;
|
|
112
|
+
};
|
|
113
|
+
export type BTPConnection = {
|
|
114
|
+
id: string;
|
|
115
|
+
client: BtpsClient;
|
|
116
|
+
createdAt: string;
|
|
117
|
+
updatedAt: string;
|
|
118
|
+
lastUsedAt: string;
|
|
119
|
+
isActive: boolean;
|
|
120
|
+
clientOptions: BTPClientOptions;
|
|
121
|
+
getStatus: () => ConnectionStates;
|
|
122
|
+
};
|
|
123
|
+
export type BTPConnectionUpdate = {
|
|
124
|
+
clientOptions?: BTPClientOptions;
|
|
125
|
+
ttl?: number;
|
|
126
|
+
maxQueue?: number;
|
|
127
|
+
};
|
|
128
|
+
export type BtpsTransporterEvents = {
|
|
129
|
+
connectionCreated: (connectionId: string) => void;
|
|
130
|
+
connectionUpdated: (connectionId: string) => void;
|
|
131
|
+
connectionDestroyed: (connectionId: string) => void;
|
|
132
|
+
connectionError: (connectionId: string, errorInfo: BtpsClientErrorInfo) => void;
|
|
133
|
+
connectionEnd: (connectionId: string, endInfo: BtpsClientErrorInfo) => void;
|
|
134
|
+
connectionConnected: (connectionId: string) => void;
|
|
135
|
+
connectionClose: (connectionId: string, closeInfo: BtpsClientErrorInfo) => void;
|
|
136
|
+
connectionMessage: (connectionId: string, message: BTPClientResponse & {
|
|
137
|
+
validSignature: boolean;
|
|
138
|
+
}) => void;
|
|
139
|
+
};
|
|
140
|
+
export type TypedEventEmitter<T = BtpsClientEvents> = {
|
|
141
|
+
on<K extends keyof T>(event: K, listener: T[K]): void;
|
|
142
|
+
off<K extends keyof T>(event: K, listener: T[K]): void;
|
|
143
|
+
};
|
|
144
|
+
export interface BTPClientResponse {
|
|
145
|
+
response?: BTPServerResponse;
|
|
146
|
+
error?: BTPErrorException;
|
|
147
|
+
}
|
|
148
|
+
export type BtpsHostDnsTxt = {
|
|
149
|
+
version: string;
|
|
150
|
+
hostname: string;
|
|
151
|
+
selector: string;
|
|
152
|
+
port: number;
|
|
153
|
+
/** The identity operating the host (`op`), when declared */
|
|
154
|
+
operator?: string;
|
|
155
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
import type { BTPAuthResDoc } from '../server/types.js';
|
|
8
|
+
import { generateUserToken, type BTPSigningKey } from '../crypto/index.js';
|
|
9
|
+
import type { ServerAuthConfig, AuthRequestResponse, AuthValidationResult, CreateAgentOptions, AuthAgentOptions } from './types.js';
|
|
10
|
+
import { BTPErrorException } from '../error/index.js';
|
|
11
|
+
export declare class BtpsAuthentication {
|
|
12
|
+
private readonly tokenConfig;
|
|
13
|
+
private readonly trustStore;
|
|
14
|
+
private readonly tokenStore;
|
|
15
|
+
/**
|
|
16
|
+
* Private constructor - use factory methods instead
|
|
17
|
+
*/
|
|
18
|
+
constructor(config: ServerAuthConfig);
|
|
19
|
+
/**
|
|
20
|
+
* Create an agent trust record
|
|
21
|
+
* @param options - Agent creation options
|
|
22
|
+
* @returns Created trust record
|
|
23
|
+
*/
|
|
24
|
+
private createAgentTrustRecord;
|
|
25
|
+
/**
|
|
26
|
+
* Fetch an authentication session
|
|
27
|
+
* @param agentId - The agent ID
|
|
28
|
+
* @param payload - The payload to send to the server
|
|
29
|
+
* @param type - The type of session to fetch
|
|
30
|
+
* @param agentOptions - The agent options
|
|
31
|
+
* @returns The authentication session
|
|
32
|
+
*/
|
|
33
|
+
private static _fetchAuthSession;
|
|
34
|
+
/**
|
|
35
|
+
* Generate a unique agent ID
|
|
36
|
+
* @returns Generated agent ID
|
|
37
|
+
*/
|
|
38
|
+
static generateAgentId(prefix?: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Generate a refresh token
|
|
41
|
+
* @returns Generated refresh token
|
|
42
|
+
*/
|
|
43
|
+
static generateRefreshToken(size?: number): string;
|
|
44
|
+
/**
|
|
45
|
+
* Generate a user authentication token (server-side)
|
|
46
|
+
* @param userIdentity - User identity to generate token for
|
|
47
|
+
* @returns Generated authentication token
|
|
48
|
+
*/
|
|
49
|
+
static generateAuthToken: typeof generateUserToken;
|
|
50
|
+
/**
|
|
51
|
+
* Store an authentication token (server-side)
|
|
52
|
+
* @param token - The auth token to store
|
|
53
|
+
* @param userIdentity - User identity associated with the token
|
|
54
|
+
* @param metadata - Optional metadata to store with the token
|
|
55
|
+
*/
|
|
56
|
+
storeAuthToken(token: string, userIdentity: string, decryptBy: string, metadata?: Record<string, unknown>): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Validate an authentication token (server-side)
|
|
59
|
+
* @param token - The auth token to validate
|
|
60
|
+
* @param identity - The identity to validate the token for
|
|
61
|
+
* @returns Validation result with user identity if valid
|
|
62
|
+
*/
|
|
63
|
+
validateAuthToken(userIdentity: string, token: string): Promise<AuthValidationResult>;
|
|
64
|
+
/**
|
|
65
|
+
* Validate a refresh token and reissue a new refresh token
|
|
66
|
+
* @param agentId - The agent ID
|
|
67
|
+
* @param refreshToken - The refresh token to validate
|
|
68
|
+
* @param options - Optional agent options
|
|
69
|
+
* @returns New authentication response with agent ID and refresh token
|
|
70
|
+
*/
|
|
71
|
+
validateAndReissueRefreshToken(agentId: string, refreshToken: string, options: Omit<CreateAgentOptions, 'userIdentity' | 'publicKey'> & {
|
|
72
|
+
publicKey?: string;
|
|
73
|
+
decryptBy: string;
|
|
74
|
+
}): Promise<{
|
|
75
|
+
data?: BTPAuthResDoc;
|
|
76
|
+
error?: BTPErrorException;
|
|
77
|
+
}>;
|
|
78
|
+
/**
|
|
79
|
+
* Create an agent and trust record (server-side)
|
|
80
|
+
* @param options - Agent creation options
|
|
81
|
+
* @returns Generated authentication response with agent ID and refresh token
|
|
82
|
+
*/
|
|
83
|
+
createAgent(options: CreateAgentOptions, decryptBy: string): Promise<BTPAuthResDoc>;
|
|
84
|
+
/**
|
|
85
|
+
* Authenticate using an auth token (client-side)
|
|
86
|
+
* @param authToken - The authentication token from the server
|
|
87
|
+
* @param keyPair - Generated key pair for this device, or a Signer holding its key in the device's keystore
|
|
88
|
+
* @param agentInfo - Optional agent information
|
|
89
|
+
* @returns NewAuthentication result with session details
|
|
90
|
+
*/
|
|
91
|
+
static authenticate(identity: string, authToken: string, keyPair: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
|
|
92
|
+
/**
|
|
93
|
+
* Refresh an authentication session (client-side)
|
|
94
|
+
* @param refreshToken - The refresh token to use
|
|
95
|
+
* @param agentInfo - Optional agent information
|
|
96
|
+
* @param agentOptions - Optional agent options
|
|
97
|
+
* @returns renewed authentication session or error
|
|
98
|
+
*/
|
|
99
|
+
static refreshSession(agentId: string, identity: string, refreshToken: string, keyPair: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
|
|
100
|
+
/**
|
|
101
|
+
* Refresh an authentication session and move the device to a new key (client-side).
|
|
102
|
+
* The refresh is signed by the current key and carries a proof signed by the new
|
|
103
|
+
* key, so the server accepts the new key only from the device that holds both.
|
|
104
|
+
* After it succeeds, the device signs with the new key.
|
|
105
|
+
* @param currentKey - The key the server holds for this device today
|
|
106
|
+
* @param newKey - The key to move to: a PEM key pair, or a Signer holding it
|
|
107
|
+
* @returns renewed authentication session or error
|
|
108
|
+
*/
|
|
109
|
+
static rotateKey(agentId: string, identity: string, refreshToken: string, currentKey: BTPSigningKey, newKey: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
|
|
110
|
+
/**
|
|
111
|
+
* Validate a refresh token (server-side)
|
|
112
|
+
* @param agentId - The agent ID
|
|
113
|
+
* @param refreshToken - The refresh token to validate
|
|
114
|
+
* @returns Validation result with agent details if valid
|
|
115
|
+
*/
|
|
116
|
+
validateRefreshToken(agentId: string, refreshToken: string): Promise<{
|
|
117
|
+
isValid: false;
|
|
118
|
+
error?: Error;
|
|
119
|
+
} | {
|
|
120
|
+
isValid: true;
|
|
121
|
+
agentId: string;
|
|
122
|
+
userIdentity: string;
|
|
123
|
+
}>;
|
|
124
|
+
/**
|
|
125
|
+
* Clean up expired tokens and sessions
|
|
126
|
+
*/
|
|
127
|
+
cleanup(): Promise<void>;
|
|
128
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID, randomBytes } from "crypto";
|
|
9
|
+
import { BtpsAgent } from "../../client/btpsAgent.js";
|
|
10
|
+
import { computeAgentTrustId } from "../trust/trustUtils.js";
|
|
11
|
+
import {
|
|
12
|
+
generateUserToken,
|
|
13
|
+
getFingerprintFromPem,
|
|
14
|
+
DEFAULT_ALPHABET,
|
|
15
|
+
signBtpPayload,
|
|
16
|
+
signBtpPayloadWithSigner
|
|
17
|
+
} from "../crypto/index.js";
|
|
18
|
+
import { keyProofPayload } from "./keyProof.js";
|
|
19
|
+
import { isValidIdentity, pemToBase64 } from "../utils/index.js";
|
|
20
|
+
import { BTP_ERROR_AUTHENTICATION_INVALID, BTP_ERROR_IDENTITY } from "../error/constant.js";
|
|
21
|
+
import { BTPErrorException, transformToBTPErrorException } from "../error/index.js";
|
|
22
|
+
const DEFAULT_TOKEN_CONFIG = {
|
|
23
|
+
authTokenLength: 12,
|
|
24
|
+
authTokenAlphabet: DEFAULT_ALPHABET,
|
|
25
|
+
authTokenExpiryMs: 15 * 60 * 1e3,
|
|
26
|
+
|
|
27
|
+
refreshTokenExpiryMs: 7 * 24 * 60 * 60 * 1e3
|
|
28
|
+
|
|
29
|
+
};
|
|
30
|
+
class BtpsAuthentication {
|
|
31
|
+
tokenConfig;
|
|
32
|
+
trustStore;
|
|
33
|
+
tokenStore;
|
|
34
|
+
constructor(config) {
|
|
35
|
+
this.tokenConfig = {
|
|
36
|
+
...DEFAULT_TOKEN_CONFIG,
|
|
37
|
+
...config.tokenConfig ?? {}
|
|
38
|
+
}, this.trustStore = config.trustStore, this.tokenStore = config.tokenStore;
|
|
39
|
+
}
|
|
40
|
+
async createAgentTrustRecord(options) {
|
|
41
|
+
const { userIdentity, publicKey, agentInfo, decidedBy, privacyType, trustExpiryMs } = options, now = new Date(), agentId = BtpsAuthentication.generateAgentId(), trustRecord = {
|
|
42
|
+
senderId: agentId,
|
|
43
|
+
receiverId: userIdentity,
|
|
44
|
+
status: "accepted",
|
|
45
|
+
createdAt: now.toISOString(),
|
|
46
|
+
decidedBy,
|
|
47
|
+
decidedAt: now.toISOString(),
|
|
48
|
+
expiresAt: trustExpiryMs ? new Date(now.getTime() + trustExpiryMs).toISOString() : new Date(now.getTime() + this.tokenConfig.refreshTokenExpiryMs).toISOString(),
|
|
49
|
+
publicKeyBase64: pemToBase64(publicKey),
|
|
50
|
+
publicKeyFingerprint: getFingerprintFromPem(publicKey, "sha256"),
|
|
51
|
+
keyHistory: [],
|
|
52
|
+
privacyType: privacyType ?? "encrypted",
|
|
53
|
+
metadata: {
|
|
54
|
+
agentInfo: agentInfo ?? {}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
...await this.trustStore.create(trustRecord, computeAgentTrustId(agentId, userIdentity)),
|
|
59
|
+
expiresAt: trustRecord.expiresAt
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
static async _fetchAuthSession(agentId, payload, type = "auth", agentOptions) {
|
|
63
|
+
const { keyPair, newKey, identity, authToken, agentInfo } = payload, commandAction = type === "refresh" ? "auth.refresh" : "auth.request";
|
|
64
|
+
try {
|
|
65
|
+
const options = {
|
|
66
|
+
...agentOptions,
|
|
67
|
+
agent: "sign" in keyPair ? { id: agentId, signer: keyPair } : {
|
|
68
|
+
id: agentId,
|
|
69
|
+
identityKey: keyPair.privateKey,
|
|
70
|
+
identityCert: keyPair.publicKey
|
|
71
|
+
},
|
|
72
|
+
btpIdentity: identity
|
|
73
|
+
}, agent = new BtpsAgent(options), announcedKey = newKey ?? keyPair, publicKey = "sign" in announcedKey ? (await announcedKey.getPublicKey()).publicKey : announcedKey.publicKey, authRequest = {
|
|
74
|
+
identity,
|
|
75
|
+
authToken,
|
|
76
|
+
publicKey,
|
|
77
|
+
agentInfo
|
|
78
|
+
};
|
|
79
|
+
if (newKey) {
|
|
80
|
+
const proofPayload = keyProofPayload(agentId, identity, publicKey);
|
|
81
|
+
authRequest.keyProof = "sign" in newKey ? await signBtpPayloadWithSigner(proofPayload, newKey) : signBtpPayload(proofPayload, newKey);
|
|
82
|
+
}
|
|
83
|
+
const { response, error } = await agent.command(commandAction, identity, authRequest);
|
|
84
|
+
if (error) return { success: !1, error };
|
|
85
|
+
if (!response || !response.status.ok || !response.document || response.type === "btps_error")
|
|
86
|
+
return {
|
|
87
|
+
success: !1,
|
|
88
|
+
error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
|
|
89
|
+
cause: "Invalid authentication response",
|
|
90
|
+
meta: { agentId, identity, authToken, agentInfo, response }
|
|
91
|
+
})
|
|
92
|
+
};
|
|
93
|
+
const authResponse = response.document;
|
|
94
|
+
if (!authResponse.agentId || !authResponse.refreshToken)
|
|
95
|
+
return {
|
|
96
|
+
success: !1,
|
|
97
|
+
error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
|
|
98
|
+
cause: "Invalid authentication response format",
|
|
99
|
+
meta: { agentId, identity, authToken, agentInfo, response }
|
|
100
|
+
})
|
|
101
|
+
};
|
|
102
|
+
const { type: type2, ...restResponse } = response;
|
|
103
|
+
return {
|
|
104
|
+
success: !0,
|
|
105
|
+
response: {
|
|
106
|
+
...restResponse,
|
|
107
|
+
document: authResponse
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return {
|
|
112
|
+
success: !1,
|
|
113
|
+
error: transformToBTPErrorException(error)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
static generateAgentId(prefix = "btps_ag") {
|
|
118
|
+
return `${prefix}_${randomUUID()}`;
|
|
119
|
+
}
|
|
120
|
+
static generateRefreshToken(size = 32) {
|
|
121
|
+
return randomBytes(size).toString("base64url");
|
|
122
|
+
}
|
|
123
|
+
static generateAuthToken = generateUserToken;
|
|
124
|
+
async storeAuthToken(token, userIdentity, decryptBy, metadata) {
|
|
125
|
+
await this.tokenStore.store(
|
|
126
|
+
token,
|
|
127
|
+
null,
|
|
128
|
+
userIdentity,
|
|
129
|
+
this.tokenConfig.authTokenExpiryMs,
|
|
130
|
+
decryptBy,
|
|
131
|
+
metadata
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
async validateAuthToken(userIdentity, token) {
|
|
135
|
+
try {
|
|
136
|
+
const storedToken = await this.tokenStore.consume(userIdentity, token);
|
|
137
|
+
return storedToken ? {
|
|
138
|
+
isValid: !0,
|
|
139
|
+
userIdentity: storedToken.userIdentity
|
|
140
|
+
} : {
|
|
141
|
+
isValid: !1,
|
|
142
|
+
error: new BTPErrorException({ message: "Invalid or expired auth token" })
|
|
143
|
+
};
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return {
|
|
146
|
+
isValid: !1,
|
|
147
|
+
error: error instanceof Error ? error : new BTPErrorException({ message: "Token validation failed" })
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async validateAndReissueRefreshToken(agentId, refreshToken, options) {
|
|
152
|
+
const storedToken = await this.tokenStore.consume(agentId, refreshToken);
|
|
153
|
+
if (!storedToken)
|
|
154
|
+
return {
|
|
155
|
+
data: void 0,
|
|
156
|
+
error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
|
|
157
|
+
cause: "Invalid or expired refresh token",
|
|
158
|
+
meta: { agentId, refreshToken }
|
|
159
|
+
})
|
|
160
|
+
};
|
|
161
|
+
const { userIdentity } = storedToken, computedId = computeAgentTrustId(agentId, userIdentity), trustRecord = await this.trustStore.getById(computedId);
|
|
162
|
+
if (!trustRecord)
|
|
163
|
+
return {
|
|
164
|
+
data: void 0,
|
|
165
|
+
error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
|
|
166
|
+
cause: `Trust record not found for ${agentId} \u2192 ${userIdentity}`,
|
|
167
|
+
meta: { agentId, userIdentity, refreshToken }
|
|
168
|
+
})
|
|
169
|
+
};
|
|
170
|
+
const patch = {
|
|
171
|
+
...trustRecord,
|
|
172
|
+
expiresAt: new Date(
|
|
173
|
+
Date.now() + (options.trustExpiryMs ?? this.tokenConfig.refreshTokenExpiryMs)
|
|
174
|
+
).toISOString()
|
|
175
|
+
}, { agentInfo, decidedBy, privacyType, publicKey } = options;
|
|
176
|
+
if (patch.metadata = {
|
|
177
|
+
agentInfo: agentInfo ?? trustRecord.metadata?.agentInfo ?? {}
|
|
178
|
+
}, publicKey) {
|
|
179
|
+
const previousFingerprint = trustRecord.publicKeyFingerprint, currentFingerprint = getFingerprintFromPem(publicKey, "sha256");
|
|
180
|
+
previousFingerprint !== currentFingerprint && (patch.keyHistory = trustRecord.keyHistory || [], patch.keyHistory.push({
|
|
181
|
+
fingerprint: previousFingerprint,
|
|
182
|
+
firstSeen: trustRecord.decidedAt,
|
|
183
|
+
lastSeen: ( new Date()).toISOString()
|
|
184
|
+
}), patch.publicKeyBase64 = pemToBase64(publicKey), patch.publicKeyFingerprint = currentFingerprint);
|
|
185
|
+
}
|
|
186
|
+
patch.decidedBy = decidedBy, patch.privacyType = privacyType ?? patch.privacyType, patch.status = "accepted", patch.decidedAt = ( new Date()).toISOString();
|
|
187
|
+
try {
|
|
188
|
+
await this.trustStore.update(computedId, patch);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
const remainingMs = new Date(storedToken.expiresAt).getTime() - Date.now();
|
|
191
|
+
return remainingMs > 0 && await this.tokenStore.store(
|
|
192
|
+
refreshToken,
|
|
193
|
+
agentId,
|
|
194
|
+
userIdentity,
|
|
195
|
+
remainingMs,
|
|
196
|
+
storedToken.decryptBy,
|
|
197
|
+
storedToken.metadata
|
|
198
|
+
), {
|
|
199
|
+
data: void 0,
|
|
200
|
+
error: transformToBTPErrorException(error)
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const newRefreshToken = BtpsAuthentication.generateRefreshToken();
|
|
204
|
+
return await this.tokenStore.store(
|
|
205
|
+
newRefreshToken,
|
|
206
|
+
agentId,
|
|
207
|
+
userIdentity,
|
|
208
|
+
this.tokenConfig.refreshTokenExpiryMs,
|
|
209
|
+
options.decryptBy,
|
|
210
|
+
{ agentInfo }
|
|
211
|
+
), {
|
|
212
|
+
data: {
|
|
213
|
+
agentId,
|
|
214
|
+
refreshToken: newRefreshToken,
|
|
215
|
+
expiresAt: patch.expiresAt,
|
|
216
|
+
decryptBy: options.decryptBy
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async createAgent(options, decryptBy) {
|
|
221
|
+
const expiry = options.trustExpiryMs ?? this.tokenConfig.refreshTokenExpiryMs, trustRecord = await this.createAgentTrustRecord({ ...options, trustExpiryMs: expiry }), { senderId: agentId, receiverId: userIdentity, metadata, expiresAt } = trustRecord, agentInfo = metadata?.agentInfo, refreshToken = BtpsAuthentication.generateRefreshToken();
|
|
222
|
+
return await this.tokenStore.store(
|
|
223
|
+
refreshToken,
|
|
224
|
+
agentId,
|
|
225
|
+
userIdentity,
|
|
226
|
+
this.tokenConfig.refreshTokenExpiryMs,
|
|
227
|
+
decryptBy,
|
|
228
|
+
{ agentInfo }
|
|
229
|
+
), {
|
|
230
|
+
agentId,
|
|
231
|
+
refreshToken,
|
|
232
|
+
expiresAt,
|
|
233
|
+
decryptBy
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
static async authenticate(identity, authToken, keyPair, agentInfo, agentOptions) {
|
|
237
|
+
return isValidIdentity(identity) ? await this._fetchAuthSession(
|
|
238
|
+
"temp",
|
|
239
|
+
{ keyPair, identity, authToken, agentInfo },
|
|
240
|
+
"auth",
|
|
241
|
+
agentOptions
|
|
242
|
+
) : {
|
|
243
|
+
success: !1,
|
|
244
|
+
error: new BTPErrorException(BTP_ERROR_IDENTITY)
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
static async refreshSession(agentId, identity, refreshToken, keyPair, agentInfo, agentOptions) {
|
|
248
|
+
return isValidIdentity(identity) ? await this._fetchAuthSession(
|
|
249
|
+
agentId,
|
|
250
|
+
{ keyPair, identity, authToken: refreshToken, agentInfo },
|
|
251
|
+
"refresh",
|
|
252
|
+
agentOptions
|
|
253
|
+
) : {
|
|
254
|
+
success: !1,
|
|
255
|
+
error: new BTPErrorException(BTP_ERROR_IDENTITY)
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
static async rotateKey(agentId, identity, refreshToken, currentKey, newKey, agentInfo, agentOptions) {
|
|
259
|
+
return isValidIdentity(identity) ? await this._fetchAuthSession(
|
|
260
|
+
agentId,
|
|
261
|
+
{ keyPair: currentKey, newKey, identity, authToken: refreshToken, agentInfo },
|
|
262
|
+
"refresh",
|
|
263
|
+
agentOptions
|
|
264
|
+
) : {
|
|
265
|
+
success: !1,
|
|
266
|
+
error: new BTPErrorException(BTP_ERROR_IDENTITY)
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
async validateRefreshToken(agentId, refreshToken) {
|
|
270
|
+
try {
|
|
271
|
+
const storedToken = await this.tokenStore.get(agentId, refreshToken);
|
|
272
|
+
return storedToken ? {
|
|
273
|
+
isValid: !0,
|
|
274
|
+
agentId: storedToken.agentId,
|
|
275
|
+
userIdentity: storedToken.userIdentity
|
|
276
|
+
} : {
|
|
277
|
+
isValid: !1,
|
|
278
|
+
error: new BTPErrorException({ message: "Invalid or expired refresh token" })
|
|
279
|
+
};
|
|
280
|
+
} catch (error) {
|
|
281
|
+
return {
|
|
282
|
+
isValid: !1,
|
|
283
|
+
error: transformToBTPErrorException(error)
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async cleanup() {
|
|
288
|
+
await this.tokenStore.cleanup(), await this.tokenStore.cleanup();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
export {
|
|
292
|
+
BtpsAuthentication
|
|
293
|
+
};
|