@btps/sdk 1.1.3 → 1.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +461 -0
  2. package/bin/verify-evidence-bundle.mjs +96 -0
  3. package/dist/client/btpsAgent.d.ts +10 -1
  4. package/dist/client/btpsAgent.js +116 -18
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +265 -147
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +3 -1
  9. package/dist/client/libs/schema.js +78 -13
  10. package/dist/client/libs/timeouts.d.ts +6 -0
  11. package/dist/client/libs/timeouts.js +2 -1
  12. package/dist/client/types/index.d.ts +54 -2
  13. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  14. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  15. package/dist/core/authentication/refreshSuccessor.js +47 -0
  16. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  17. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  18. package/dist/core/authentication/types.d.ts +82 -0
  19. package/dist/core/crypto/contentKey.d.ts +34 -0
  20. package/dist/core/crypto/contentKey.js +64 -0
  21. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  22. package/dist/core/crypto/decryptVerify.js +23 -5
  23. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  24. package/dist/core/crypto/index.d.ts +12 -0
  25. package/dist/core/crypto/index.js +7 -1
  26. package/dist/core/crypto/keyResolver.d.ts +48 -0
  27. package/dist/core/crypto/keyResolver.js +46 -0
  28. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  29. package/dist/core/crypto/pem-decrypter.js +13 -8
  30. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  31. package/dist/core/crypto/signEncrypt.js +20 -5
  32. package/dist/core/crypto/types.d.ts +8 -1
  33. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  34. package/dist/core/delegation/BtpsDelegator.js +3 -2
  35. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  36. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  37. package/dist/core/error/constant.d.ts +39 -0
  38. package/dist/core/error/constant.js +55 -0
  39. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  40. package/dist/core/server/constants/btps-protocol.js +46 -8
  41. package/dist/core/server/constants/index.d.ts +7 -3
  42. package/dist/core/server/constants/index.js +19 -4
  43. package/dist/core/server/constants/limits.d.ts +18 -0
  44. package/dist/core/server/constants/limits.js +19 -1
  45. package/dist/core/server/constants/permissions.d.ts +38 -0
  46. package/dist/core/server/constants/permissions.js +38 -0
  47. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  48. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  49. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  50. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  51. package/dist/core/server/schemas/artifacts/transporterSchema.js +99 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +36009 -1083
  54. package/dist/core/server/schemas/btpsDocsSchema.js +305 -42
  55. package/dist/core/server/schemas/helpers.d.ts +10090 -0
  56. package/dist/core/server/schemas/helpers.js +76 -12
  57. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  58. package/dist/core/server/schemas/responseSchema.js +52 -9
  59. package/dist/core/server/schemas/schema.js +3 -1
  60. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  61. package/dist/core/server/schemas/trustValues.js +117 -0
  62. package/dist/core/server/types.d.ts +104 -6
  63. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  64. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  65. package/dist/core/storage/JsonIdentityStore.js +3 -0
  66. package/dist/core/storage/types.d.ts +2 -0
  67. package/dist/core/trust/agreements.d.ts +107 -0
  68. package/dist/core/trust/agreements.js +116 -0
  69. package/dist/core/trust/evidence.d.ts +220 -0
  70. package/dist/core/trust/evidence.js +334 -0
  71. package/dist/core/trust/index.d.ts +10 -0
  72. package/dist/core/trust/index.js +14 -1
  73. package/dist/core/trust/keyRotation.d.ts +148 -0
  74. package/dist/core/trust/keyRotation.js +267 -0
  75. package/dist/core/trust/permissions.d.ts +114 -0
  76. package/dist/core/trust/permissions.js +115 -0
  77. package/dist/core/trust/shaping.d.ts +42 -0
  78. package/dist/core/trust/shaping.js +47 -0
  79. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  80. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  81. package/dist/core/trust/timestamps.d.ts +49 -0
  82. package/dist/core/trust/timestamps.js +78 -0
  83. package/dist/core/trust/trustUtils.d.ts +13 -2
  84. package/dist/core/trust/trustUtils.js +28 -3
  85. package/dist/core/trust/types.d.ts +312 -2
  86. package/dist/core/trust/verification.d.ts +52 -0
  87. package/dist/core/trust/verification.js +55 -0
  88. package/dist/server/btpsServer.d.ts +79 -5
  89. package/dist/server/btpsServer.js +297 -145
  90. package/dist/server/index.d.ts +3 -0
  91. package/dist/server/index.js +17 -1
  92. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  93. package/dist/server/libs/agreementOrderCheck.js +29 -0
  94. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  95. package/dist/server/libs/artifactTimeWindow.js +2 -1
  96. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  97. package/dist/server/libs/detailsRequestLimit.js +28 -0
  98. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  99. package/dist/server/libs/detailsResponseCheck.js +27 -0
  100. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  101. package/dist/server/libs/eventChainCheck.js +39 -0
  102. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  103. package/dist/server/libs/inFlightLimit.js +7 -1
  104. package/dist/server/libs/index.d.ts +5 -0
  105. package/dist/server/libs/index.js +10 -0
  106. package/dist/server/libs/keyChains.d.ts +14 -0
  107. package/dist/server/libs/keyChains.js +17 -0
  108. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  109. package/dist/server/libs/wrapForAgent.js +36 -0
  110. package/dist/server/types.d.ts +103 -9
  111. package/package.json +12 -3
@@ -18,42 +18,107 @@ import { identitySchema } from "../../core/server/schemas/shared.js";
18
18
  import { validateAgentDocument } from "../../core/server/schemas/helpers.js";
19
19
  import {
20
20
  BtpAuthReqDocSchema,
21
- BtpDocumentSchema,
22
- BtpLifecycleEventSchema,
23
- BtpTrustReqDocSchema,
24
- BtpTrustResDocSchema
21
+ BtpDetailsNoteDocSchema,
22
+ BtpDocSchema
25
23
  } from "../../core/server/schemas/btpsDocsSchema.js";
24
+ import { BtpDetailsResDocSchema } from "../../core/server/schemas/trustValues.js";
25
+ import {
26
+ BtpSyncOfSchema,
27
+ BtpTrustPermissionsSchema
28
+ } from "../../core/server/schemas/artifacts/transporterSchema.js";
29
+ import {
30
+ DETAIL_PERMISSIONS,
31
+ DOCUMENT_TYPES,
32
+ ENTITY_TYPES
33
+ } from "../../core/server/constants/permissions.js";
26
34
  const BtpsAgentOptionsSchema = BtpCryptoOptionsSchema.optional(), BtpsAgentCommandDocumentSchema = z.union([
27
- BtpTrustReqDocSchema,
28
- BtpTrustResDocSchema,
29
- BtpDocumentSchema,
30
- BtpLifecycleEventSchema,
35
+ BtpDocSchema,
31
36
  BtpAuthReqDocSchema,
32
37
  BtpAgentQuerySchema,
33
38
  BtpAgentMutationSchema,
34
39
  BtpIdsPayloadSchema,
35
- BtpAgentCreateSchema
40
+ BtpAgentCreateSchema,
41
+ BtpDetailsNoteDocSchema,
42
+ BtpDetailsResDocSchema
36
43
  ]).optional(), BtpsAgentCommandSchema = z.object({
37
44
  actionType: BtpsAgentActionTypeSchema,
38
45
  to: identitySchema,
39
46
  document: BtpsAgentCommandDocumentSchema.optional(),
40
47
  options: BtpCryptoOptionsSchema.extend({
41
48
  relatesTo: z.string().min(1).optional(),
42
- id: z.string().uuid().optional()
49
+ id: z.string().uuid().optional(),
50
+ syncOf: BtpSyncOfSchema.optional(),
51
+ documentType: z.enum(DOCUMENT_TYPES).optional(),
52
+ details: z.array(
53
+ z.custom(
54
+ (name) => typeof name == "string" && DETAIL_PERMISSIONS.includes(name)
55
+ )
56
+ ).min(1).optional(),
57
+
58
+ permissions: BtpTrustPermissionsSchema.optional(),
59
+ entityType: z.enum(ENTITY_TYPES).optional(),
60
+ given: z.array(z.string()).optional(),
61
+ change: z.literal(!0).optional(),
62
+ granted: z.array(z.string()).optional()
43
63
  }).optional()
44
- }), BtpsAgentCommandCallSchema = BtpsAgentCommandSchema.refine(
64
+ }), TRUST_OPTION_ACTIONS = {
65
+ permissions: ["trust.request"],
66
+ given: ["trust.request"],
67
+ change: ["trust.request"],
68
+ granted: ["trust.respond"],
69
+ entityType: ["trust.request", "trust.respond"]
70
+ }, DETAILS_ACTIONS = [
71
+ "details.changed",
72
+ "details.request",
73
+ "details.respond"
74
+ ], relatesToOn = (actionType) => actionType === "event.send" || actionType === "details.respond" ? "required" : actionType === "details.request" ? "allowed" : "refused", BtpsAgentCommandCallSchema = BtpsAgentCommandSchema.refine(
45
75
  (data) => validateAgentDocument(data.actionType, null, data.document),
46
76
  {
47
77
  message: "Document is required for this action type or document format is invalid",
48
78
  path: ["document"]
49
79
  }
50
80
  ).refine(
51
- (data) => data.actionType === "event.send" == (data.options?.relatesTo !== void 0),
81
+ (data) => {
82
+ const on = relatesToOn(data.actionType), has = data.options?.relatesTo !== void 0;
83
+ return on === "allowed" || on === "required" === has;
84
+ },
52
85
  {
53
- message: "options.relatesTo is required on event.send and only there",
86
+ message: "options.relatesTo is required on event.send and details.respond, allowed on details.request, and refused elsewhere",
54
87
  path: ["options", "relatesTo"]
55
88
  }
56
89
  ).refine(
90
+ (data) => DETAILS_ACTIONS.includes(data.actionType) === (data.options?.details !== void 0),
91
+ {
92
+ message: "options.details is required on the details actions and only there",
93
+ path: ["options", "details"]
94
+ }
95
+ ).refine(
96
+ (data) => Object.entries(TRUST_OPTION_ACTIONS).every(
97
+ ([option, actions]) => data.options?.[option] === void 0 || actions.includes(data.actionType)
98
+ ),
99
+ {
100
+ message: "options.permissions, given and change are only on trust.request, granted only on trust.respond, and entityType on either",
101
+ path: ["options"]
102
+ }
103
+ ).refine(
104
+ (data) => data.options?.permissions === void 0 && data.options?.granted === void 0 || data.options?.entityType !== void 0,
105
+ {
106
+ message: "options.entityType comes with permissions and with granted",
107
+ path: ["options", "entityType"]
108
+ }
109
+ ).refine((data) => data.actionType !== "details.respond" || data.options?.encryption, {
110
+ message: "details.respond is always encrypted to the requester: options.encryption is required",
111
+ path: ["options", "encryption"]
112
+ }).refine(
113
+ (data) => data.options?.documentType === void 0 || data.actionType === "artifact.send" && data.document?.type === data.options.documentType,
114
+ {
115
+ message: "options.documentType is only on artifact.send, and is the document's own type",
116
+ path: ["options", "documentType"]
117
+ }
118
+ ).refine((data) => data.options?.syncOf === void 0 || data.actionType === "artifact.send", {
119
+ message: "options.syncOf is only on artifact.send",
120
+ path: ["options", "syncOf"]
121
+ }).refine(
57
122
  (data) => data.actionType !== "event.send" || data.options?.id === void 0 || data.options.id === data.document?.id,
58
123
  {
59
124
  message: "an event travels under its own id: options.id may only be that id",
@@ -14,6 +14,12 @@ export declare const DEFAULT_CONNECT_TIMEOUT_MS = 5000;
14
14
  */
15
15
  export declare const MIN_REPLY_TIMEOUT_MS = 10000;
16
16
  export declare const DEFAULT_REPLY_TIMEOUT_MS = 20000;
17
+ /**
18
+ * Since 1.2: how long a key chain lookup waits for its answer once connected:
19
+ * 5 seconds. It holds an arriving artifact until it is answered, so a host
20
+ * that cannot answer is given up on soon, and its keys left to DNS.
21
+ */
22
+ export declare const KEY_CHAIN_REPLY_TIMEOUT_MS = 5000;
17
23
  /**
18
24
  * A wait the client uses, in milliseconds. One it cannot use as given never
19
25
  * stops the client: it is warned about and replaced by the minimum (when too
@@ -5,7 +5,7 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
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(
8
+ const MIN_CONNECT_TIMEOUT_MS = 5e3, DEFAULT_CONNECT_TIMEOUT_MS = 5e3, MIN_REPLY_TIMEOUT_MS = 1e4, DEFAULT_REPLY_TIMEOUT_MS = 2e4, KEY_CHAIN_REPLY_TIMEOUT_MS = 5e3, resolveTimeoutMs = (name, configured, minimum, fallback) => configured === void 0 ? fallback : !Number.isFinite(configured) || configured <= 0 ? (console.warn(
9
9
  `[BtpsClient] ${name} ${configured} is not a usable time; using the default ${fallback} ms`
10
10
  ), fallback) : configured < minimum ? (console.warn(
11
11
  `[BtpsClient] ${name} ${configured} is below the ${minimum} ms minimum; using ${minimum} ms`
@@ -13,6 +13,7 @@ const MIN_CONNECT_TIMEOUT_MS = 5e3, DEFAULT_CONNECT_TIMEOUT_MS = 5e3, MIN_REPLY_
13
13
  export {
14
14
  DEFAULT_CONNECT_TIMEOUT_MS,
15
15
  DEFAULT_REPLY_TIMEOUT_MS,
16
+ KEY_CHAIN_REPLY_TIMEOUT_MS,
16
17
  MIN_CONNECT_TIMEOUT_MS,
17
18
  MIN_REPLY_TIMEOUT_MS,
18
19
  resolveTimeoutMs
@@ -7,9 +7,10 @@
7
7
  import type { BTPCryptoOptions } from '../../core/crypto/types.js';
8
8
  import type { Signer } from '../../core/crypto/signer-interface.js';
9
9
  import type { Decrypter } from '../../core/crypto/decrypter-interface.js';
10
+ import type { BtpsKeyResolver } from '../../core/crypto/keyResolver.js';
10
11
  import type { BTPErrorException } from '../../core/error/index.js';
11
12
  import type { BtpsClient } from '../../client/btpsClient.js';
12
- import type { BTPAgentMutation, BTPAgentQuery, BTPDocType, BTPIdsPayload, BTPAuthReqDoc, BTPServerResponse, AgentAction } from '../../server/index.js';
13
+ import type { BTPAgentMutation, BTPAgentQuery, BTPDocType, BTPIdsPayload, BTPAuthReqDoc, BTPServerResponse, BTPSyncOf, BTPDocumentType, BTPDetailPermission, BTPEntityType, BTPPermissionName, BTPTrustPermissions, BTPShaped, AgentAction } from '../../server/index.js';
13
14
  import type { ConnectionOptions, TLSSocket } from 'tls';
14
15
  export interface BTPTransporterMetrics {
15
16
  totalConnections: number;
@@ -30,6 +31,21 @@ export interface BTPClientOptions {
30
31
  hostSelector?: string;
31
32
  /** With `host`: the identity operating that host, which signs its lookup answers. Otherwise read from DNS (`op`). */
32
33
  hostOperator?: string;
34
+ /**
35
+ * Since 1.2: take no answer but one signed by this identity under this selector, as a provider's
36
+ * own app expects of its server: its domain's operator (for example `admin$saas.example`). Unsigned
37
+ * answers, and those of any other signer, are refused. Off when not set.
38
+ */
39
+ requireSignedBy?: {
40
+ identity: string;
41
+ selector: string;
42
+ };
43
+ /**
44
+ * Since 1.2: finds the keys this client checks and encrypts with: an answer's signer (`verify`)
45
+ * and, in `resolveIdentity`, the receiver's key (`encrypt`, before asking the receiver's host).
46
+ * Without it, each is looked up in DNS, as before.
47
+ */
48
+ keyResolver?: BtpsKeyResolver;
33
49
  version?: string;
34
50
  port?: number;
35
51
  maxQueue?: number;
@@ -54,8 +70,41 @@ export interface BTPTransporterOptions extends Omit<BTPClientOptions, 'to'> {
54
70
  }
55
71
  export type BtpsAgentDoc = BTPDocType | BTPAuthReqDoc | BTPAgentMutation | BTPIdsPayload | BTPAgentQuery;
56
72
  export type BtpsAgentCommandOptions = BTPCryptoOptions & {
57
- /** Required on `event.send`, refused elsewhere: the id of the `BTPS_DOC` artifact that delivered the invoice. */
73
+ /**
74
+ * Required on `event.send`: the id of the `BTPS_DOC` artifact that delivered the invoice. Since 1.2, required on
75
+ * `details.respond` (the `DETAILS_REQ` it answers) and allowed on `details.request` (the `DETAILS_CHANGED` it
76
+ * follows). Refused elsewhere.
77
+ */
58
78
  relatesTo?: string;
79
+ /**
80
+ * Since 1.2, required on `details.changed`, `details.request` and `details.respond`, and refused elsewhere: the
81
+ * `detail:` names the artifact is about, set on its envelope. A `details.respond` is always encrypted.
82
+ */
83
+ details?: BTPDetailPermission[];
84
+ /**
85
+ * Since 1.2, on `artifact.send` to the device's own address only: this send is a sync, the user's own copy of
86
+ * the send it names, by the sent artifact's id and the SHA-256 of its RFC 8785 form (`syncOfArtifact`).
87
+ */
88
+ syncOf?: BTPSyncOf;
89
+ /**
90
+ * Since 1.2, on `artifact.send` only: the document's type, named on the envelope, signed and readable, for a
91
+ * send under a trust with permissions, whose receiver checks `send:<documentType>` is granted. It is the
92
+ * document's own `type`, and stamps the artifact `1.2.0`, so leave it out for any other send.
93
+ */
94
+ documentType?: BTPDocumentType;
95
+ /**
96
+ * Since 1.2, on `trust.request` only: the permissions asked for, one flat list (see Trust permissions). With it,
97
+ * `entityType` is required, and every detail asked for is given in `given`.
98
+ */
99
+ permissions?: BTPTrustPermissions;
100
+ /** Since 1.2, on `trust.request` and `trust.respond`: what owns the user's address. Required with `permissions` and `granted`. */
101
+ entityType?: BTPEntityType;
102
+ /** Since 1.2, on `trust.request` only: the `detail:` names of the details the user gives; their values go in the document. */
103
+ given?: BTPDetailPermission[];
104
+ /** Since 1.2, on `trust.request` only: `true` for a change to an active trust, asking for the whole set now wanted. */
105
+ change?: true;
106
+ /** Since 1.2, on `trust.respond` only, and only when accepting: the permission names granted. */
107
+ granted?: BTPPermissionName[];
59
108
  /**
60
109
  * The id of the artifact the command sends, a UUID. Sending the same document again after a lost answer under
61
110
  * the same id lets the receiver keep it once. Without it, a new id. An event always travels under its own id, so
@@ -72,6 +121,7 @@ export type BtpsAgentCommandParams = {
72
121
  export interface ConnectionStates {
73
122
  isConnecting: boolean;
74
123
  isConnected: boolean;
124
+ /** Always false since 1.2: the socket buffers what it cannot send at once, and the client keeps no queue of its own. */
75
125
  isDraining: boolean;
76
126
  isDestroyed: boolean;
77
127
  shouldRetry: boolean;
@@ -150,6 +200,8 @@ export type TypedEventEmitter<T = BtpsClientEvents> = {
150
200
  export interface BTPClientResponse {
151
201
  response?: BTPServerResponse;
152
202
  error?: BTPErrorException;
203
+ /** Since 1.2: a trust request sent as its 1.1 receiver allows, and what it left out */
204
+ shaped?: BTPShaped;
153
205
  }
154
206
  export type BtpsHostDnsTxt = {
155
207
  version: string;
@@ -4,18 +4,48 @@
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
+ import type { TypedEventEmitter } from '../../client/types/index.js';
7
8
  import type { BTPAuthResDoc } from '../server/types.js';
8
9
  import { generateUserToken, type BTPSigningKey } from '../crypto/index.js';
9
- import type { ServerAuthConfig, AuthRequestResponse, AuthValidationResult, CreateAgentOptions, AuthAgentOptions } from './types.js';
10
+ import type { ServerAuthConfig, AuthRequestResponse, AuthValidationResult, CreateAgentOptions, AuthAgentOptions, BtpsAuthenticationEvents } from './types.js';
10
11
  import { BTPErrorException } from '../error/index.js';
11
12
  export declare class BtpsAuthentication {
12
13
  private readonly tokenConfig;
13
14
  private readonly trustStore;
14
15
  private readonly tokenStore;
16
+ private readonly maxKeyAgeMs?;
17
+ private readonly refreshGraceMs;
18
+ private readonly emitter;
15
19
  /**
16
20
  * Private constructor - use factory methods instead
17
21
  */
18
22
  constructor(config: ServerAuthConfig);
23
+ /**
24
+ * Since 1.2: listen for `keyRotated` and `refreshTokenReused`.
25
+ * @param event - The event to listen to
26
+ * @param listener - The listener function
27
+ */
28
+ on: TypedEventEmitter<BtpsAuthenticationEvents>['on'];
29
+ /**
30
+ * @param event - The event to stop listening to
31
+ * @param listener - The listener function
32
+ */
33
+ off: TypedEventEmitter<BtpsAuthenticationEvents>['off'];
34
+ /**
35
+ * Tell every listener, each on its own: one that throws is warned about and
36
+ * never stops the others or the refresh, whose state is already stored.
37
+ */
38
+ private tell;
39
+ /**
40
+ * Put a taken refresh token back for what is left of its life, so the device
41
+ * can try again rather than register anew.
42
+ */
43
+ private restoreRefreshToken;
44
+ /**
45
+ * A refresh token used a second time: only a copy of it can do that, so the
46
+ * device is revoked, and whoever holds its newer token is refused too.
47
+ */
48
+ private refuseReusedRefreshToken;
19
49
  /**
20
50
  * Create an agent trust record
21
51
  * @param options - Agent creation options
@@ -75,6 +105,18 @@ export declare class BtpsAuthentication {
75
105
  data?: BTPAuthResDoc;
76
106
  error?: BTPErrorException;
77
107
  }>;
108
+ /**
109
+ * A consumed token whose refresh has no answer yet, taken inside the grace
110
+ * window: the refresh that took it is still being made. After the window
111
+ * with no answer, a second use is theft, as before.
112
+ */
113
+ private refreshInProgress;
114
+ /**
115
+ * A refresh token used again inside the grace window, by the device that
116
+ * lost the answer: the same answer again, while its new token is unused and
117
+ * the device still let in. Undefined when it is not a retry, so it is theft.
118
+ */
119
+ private retriedRefresh;
78
120
  /**
79
121
  * Create an agent and trust record (server-side)
80
122
  * @param options - Agent creation options
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { randomUUID, randomBytes } from "crypto";
9
+ import { EventEmitter } from "events";
9
10
  import { BtpsAgent } from "../../client/btpsAgent.js";
10
11
  import { computeAgentTrustId } from "../trust/trustUtils.js";
11
12
  import {
@@ -16,8 +17,14 @@ import {
16
17
  signBtpPayloadWithSigner
17
18
  } from "../crypto/index.js";
18
19
  import { keyProofPayload } from "./keyProof.js";
20
+ import { openSuccessor, sealSuccessor } from "./refreshSuccessor.js";
19
21
  import { isValidIdentity, pemToBase64 } from "../utils/index.js";
20
- import { BTP_ERROR_AUTHENTICATION_INVALID, BTP_ERROR_IDENTITY } from "../error/constant.js";
22
+ import {
23
+ BTP_ERROR_AUTHENTICATION_INVALID,
24
+ BTP_ERROR_IDENTITY,
25
+ BTP_ERROR_KEY_TOO_OLD,
26
+ BTP_ERROR_TEMPORARILY_UNAVAILABLE
27
+ } from "../error/constant.js";
21
28
  import { BTPErrorException, transformToBTPErrorException } from "../error/index.js";
22
29
  const DEFAULT_TOKEN_CONFIG = {
23
30
  authTokenLength: 12,
@@ -26,16 +33,68 @@ const DEFAULT_TOKEN_CONFIG = {
26
33
 
27
34
  refreshTokenExpiryMs: 7 * 24 * 60 * 60 * 1e3
28
35
 
29
- };
36
+ }, DEFAULT_REFRESH_GRACE_MS = 30 * 1e3, currentKeySince = (record) => record.keyHistory?.at(-1)?.lastSeen ?? record.createdAt;
30
37
  class BtpsAuthentication {
31
38
  tokenConfig;
32
39
  trustStore;
33
40
  tokenStore;
41
+ maxKeyAgeMs;
42
+ refreshGraceMs;
43
+ emitter = new EventEmitter();
34
44
  constructor(config) {
35
45
  this.tokenConfig = {
36
46
  ...DEFAULT_TOKEN_CONFIG,
37
47
  ...config.tokenConfig ?? {}
38
- }, this.trustStore = config.trustStore, this.tokenStore = config.tokenStore;
48
+ }, this.trustStore = config.trustStore, this.tokenStore = config.tokenStore, this.maxKeyAgeMs = config.maxKeyAgeMs, this.tokenStore.isConsumed || console.warn(
49
+ "[BtpsAuthentication] Warning: the token store has no isConsumed, so a refresh token used a second time is refused but not detected as theft: the device is not revoked and refreshTokenReused does not fire."
50
+ );
51
+ const grace = config.refreshGraceMs ?? DEFAULT_REFRESH_GRACE_MS;
52
+ this.refreshGraceMs = this.tokenStore.isConsumed && this.tokenStore.markSuccessor ? grace : 0, grace > 0 && this.tokenStore.isConsumed && !this.tokenStore.markSuccessor && console.warn(
53
+ "[BtpsAuthentication] Warning: the token store has no markSuccessor, so refreshGraceMs is 0: a refresh retried with its old token is theft, even straight after."
54
+ );
55
+ }
56
+ on = (event, listener) => {
57
+ this.emitter.on(event, listener);
58
+ };
59
+ off = (event, listener) => {
60
+ this.emitter.off(event, listener);
61
+ };
62
+ tell(event, info) {
63
+ for (const listener of this.emitter.listeners(event))
64
+ try {
65
+ listener(info);
66
+ } catch (error) {
67
+ console.warn(`[BtpsAuthentication] Warning: a ${event} listener threw:`, error);
68
+ }
69
+ }
70
+ async restoreRefreshToken(storedToken, refreshToken) {
71
+ const remainingMs = new Date(storedToken.expiresAt).getTime() - Date.now();
72
+ remainingMs <= 0 || await this.tokenStore.store(
73
+ refreshToken,
74
+ storedToken.agentId,
75
+ storedToken.userIdentity,
76
+ remainingMs,
77
+ storedToken.decryptBy,
78
+ storedToken.metadata
79
+ );
80
+ }
81
+ async refuseReusedRefreshToken(agentId, refreshToken, consumedToken) {
82
+ const identity = consumedToken.userIdentity, computedId = computeAgentTrustId(agentId, identity), at = ( new Date()).toISOString();
83
+ try {
84
+ const trustRecord = await this.trustStore.getById(computedId);
85
+ trustRecord && await this.trustStore.update(computedId, { status: "revoked", decidedAt: at }), this.tell("refreshTokenReused", {
86
+ agentId,
87
+ identity,
88
+ fingerprint: trustRecord?.publicKeyFingerprint,
89
+ at
90
+ });
91
+ } catch (error) {
92
+ return transformToBTPErrorException(error);
93
+ }
94
+ return new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
95
+ cause: "Refresh token used a second time: the device is revoked",
96
+ meta: { agentId }
97
+ });
39
98
  }
40
99
  async createAgentTrustRecord(options) {
41
100
  const { userIdentity, publicKey, agentInfo, decidedBy, privacyType, trustExpiryMs } = options, now = new Date(), agentId = BtpsAuthentication.generateAgentId(), trustRecord = {
@@ -87,7 +146,7 @@ class BtpsAuthentication {
87
146
  success: !1,
88
147
  error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
89
148
  cause: "Invalid authentication response",
90
- meta: { agentId, identity, authToken, agentInfo, response }
149
+ meta: { agentId, identity, agentInfo, status: response?.status }
91
150
  })
92
151
  };
93
152
  const authResponse = response.document;
@@ -96,7 +155,7 @@ class BtpsAuthentication {
96
155
  success: !1,
97
156
  error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
98
157
  cause: "Invalid authentication response format",
99
- meta: { agentId, identity, authToken, agentInfo, response }
158
+ meta: { agentId, identity, agentInfo, status: response?.status }
100
159
  })
101
160
  };
102
161
  const { type: type2, ...restResponse } = response;
@@ -150,21 +209,52 @@ class BtpsAuthentication {
150
209
  }
151
210
  async validateAndReissueRefreshToken(agentId, refreshToken, options) {
152
211
  const storedToken = await this.tokenStore.consume(agentId, refreshToken);
153
- if (!storedToken)
212
+ if (!storedToken) {
213
+ const consumedToken = await this.tokenStore.isConsumed?.(agentId, refreshToken);
214
+ if (consumedToken) {
215
+ const retried = await this.retriedRefresh(agentId, refreshToken, consumedToken);
216
+ return retried || (this.refreshInProgress(consumedToken) ? {
217
+ data: void 0,
218
+ error: new BTPErrorException(BTP_ERROR_TEMPORARILY_UNAVAILABLE, {
219
+ cause: "A refresh with this token is still being made: try again shortly",
220
+ meta: { agentId }
221
+ })
222
+ } : {
223
+ data: void 0,
224
+ error: await this.refuseReusedRefreshToken(agentId, refreshToken, consumedToken)
225
+ });
226
+ }
154
227
  return {
155
228
  data: void 0,
156
229
  error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
157
230
  cause: "Invalid or expired refresh token",
158
- meta: { agentId, refreshToken }
231
+ meta: { agentId }
159
232
  })
160
233
  };
234
+ }
161
235
  const { userIdentity } = storedToken, computedId = computeAgentTrustId(agentId, userIdentity), trustRecord = await this.trustStore.getById(computedId);
162
236
  if (!trustRecord)
163
237
  return {
164
238
  data: void 0,
165
239
  error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
166
240
  cause: `Trust record not found for ${agentId} \u2192 ${userIdentity}`,
167
- meta: { agentId, userIdentity, refreshToken }
241
+ meta: { agentId, userIdentity }
242
+ })
243
+ };
244
+ if (trustRecord.status === "revoked" || trustRecord.status === "blocked")
245
+ return {
246
+ data: void 0,
247
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
248
+ cause: `Device ${agentId} is ${trustRecord.status}`,
249
+ meta: { agentId, userIdentity }
250
+ })
251
+ };
252
+ const { agentInfo, decidedBy, privacyType, publicKey } = options, previousFingerprint = trustRecord.publicKeyFingerprint, currentFingerprint = publicKey ? getFingerprintFromPem(publicKey, "sha256") : void 0, rotates = currentFingerprint !== void 0 && currentFingerprint !== previousFingerprint, keySince = currentKeySince(trustRecord);
253
+ if (!rotates && this.maxKeyAgeMs !== void 0 && Date.now() - new Date(keySince).getTime() > this.maxKeyAgeMs)
254
+ return await this.restoreRefreshToken(storedToken, refreshToken), {
255
+ data: void 0,
256
+ error: new BTPErrorException(BTP_ERROR_KEY_TOO_OLD, {
257
+ meta: { agentId, keySince, maxKeyAgeMs: this.maxKeyAgeMs }
168
258
  })
169
259
  };
170
260
  const patch = {
@@ -172,50 +262,76 @@ class BtpsAuthentication {
172
262
  expiresAt: new Date(
173
263
  Date.now() + (options.trustExpiryMs ?? this.tokenConfig.refreshTokenExpiryMs)
174
264
  ).toISOString()
175
- }, { agentInfo, decidedBy, privacyType, publicKey } = options;
176
- if (patch.metadata = {
265
+ };
266
+ patch.metadata = {
177
267
  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();
268
+ };
269
+ const now = ( new Date()).toISOString();
270
+ publicKey && currentFingerprint && rotates && (patch.keyHistory = trustRecord.keyHistory || [], patch.keyHistory.push({
271
+ fingerprint: previousFingerprint,
272
+ firstSeen: keySince,
273
+ lastSeen: now
274
+ }), patch.publicKeyBase64 = pemToBase64(publicKey), patch.publicKeyFingerprint = currentFingerprint), patch.decidedBy = decidedBy, patch.privacyType = privacyType ?? patch.privacyType, patch.status = "accepted", patch.decidedAt = now;
187
275
  try {
188
276
  await this.trustStore.update(computedId, patch);
189
277
  } 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
- ), {
278
+ return await this.restoreRefreshToken(storedToken, refreshToken), {
199
279
  data: void 0,
200
280
  error: transformToBTPErrorException(error)
201
281
  };
202
282
  }
203
283
  const newRefreshToken = BtpsAuthentication.generateRefreshToken();
204
- return await this.tokenStore.store(
284
+ await this.tokenStore.store(
205
285
  newRefreshToken,
206
286
  agentId,
207
287
  userIdentity,
208
288
  this.tokenConfig.refreshTokenExpiryMs,
209
289
  options.decryptBy,
210
290
  { agentInfo }
211
- ), {
212
- data: {
213
- agentId,
214
- refreshToken: newRefreshToken,
215
- expiresAt: patch.expiresAt,
216
- decryptBy: options.decryptBy
217
- }
291
+ ), rotates && currentFingerprint && this.tell("keyRotated", {
292
+ agentId,
293
+ identity: userIdentity,
294
+ previousFingerprint,
295
+ fingerprint: currentFingerprint,
296
+ at: now
297
+ });
298
+ const answer = {
299
+ agentId,
300
+ refreshToken: newRefreshToken,
301
+ expiresAt: patch.expiresAt,
302
+ decryptBy: options.decryptBy
218
303
  };
304
+ if (this.refreshGraceMs > 0)
305
+ try {
306
+ await this.tokenStore.markSuccessor?.(
307
+ agentId,
308
+ refreshToken,
309
+ sealSuccessor(refreshToken, userIdentity, answer, now)
310
+ );
311
+ } catch (error) {
312
+ console.warn(
313
+ "[BtpsAuthentication] Warning: could not keep the refresh for a retry:",
314
+ error
315
+ );
316
+ }
317
+ return { data: answer };
318
+ }
319
+ refreshInProgress(consumedToken) {
320
+ const { successor, consumedAt } = consumedToken;
321
+ return this.refreshGraceMs <= 0 || successor || !consumedAt ? !1 : Date.now() - new Date(consumedAt).getTime() <= this.refreshGraceMs;
322
+ }
323
+ async retriedRefresh(agentId, refreshToken, consumedToken) {
324
+ const { successor, userIdentity } = consumedToken;
325
+ if (this.refreshGraceMs <= 0 || !successor || Date.now() - new Date(successor.at).getTime() > this.refreshGraceMs) return;
326
+ const answer = openSuccessor(refreshToken, agentId, userIdentity, successor);
327
+ if (!answer || !await this.tokenStore.get(agentId, answer.refreshToken)) return;
328
+ const trustRecord = await this.trustStore.getById(computeAgentTrustId(agentId, userIdentity));
329
+ return !trustRecord || trustRecord.status === "revoked" || trustRecord.status === "blocked" ? {
330
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
331
+ cause: `Device ${agentId} is ${trustRecord?.status ?? "unknown"}`,
332
+ meta: { agentId, userIdentity }
333
+ })
334
+ } : { data: answer };
219
335
  }
220
336
  async createAgent(options, decryptBy) {
221
337
  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();
@@ -0,0 +1,47 @@
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 { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "crypto";
9
+ import { computeAgentTrustId } from "../trust/trustUtils.js";
10
+ const INFO = "btps refresh successor v1", TAG_LENGTH = 16, keyFrom = (oldToken) => Buffer.from(hkdfSync("sha256", oldToken, "", INFO, 32)), boundTo = (agentId, userIdentity, at) => Buffer.from(JSON.stringify([INFO, computeAgentTrustId(agentId, userIdentity), at]), "utf8");
11
+ function sealSuccessor(oldToken, userIdentity, answer, at) {
12
+ const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", keyFrom(oldToken), iv, {
13
+ authTagLength: TAG_LENGTH
14
+ });
15
+ cipher.setAAD(boundTo(answer.agentId, userIdentity, at));
16
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(answer), "utf8"), cipher.final()]);
17
+ return {
18
+ at,
19
+ iv: iv.toString("base64"),
20
+ ciphertext: ciphertext.toString("base64"),
21
+ tag: cipher.getAuthTag().toString("base64")
22
+ };
23
+ }
24
+ function openSuccessor(oldToken, agentId, userIdentity, sealed) {
25
+ const tag = Buffer.from(sealed.tag, "base64");
26
+ if (tag.length === TAG_LENGTH)
27
+ try {
28
+ const decipher = createDecipheriv(
29
+ "aes-256-gcm",
30
+ keyFrom(oldToken),
31
+ Buffer.from(sealed.iv, "base64"),
32
+ { authTagLength: TAG_LENGTH }
33
+ );
34
+ decipher.setAAD(boundTo(agentId, userIdentity, sealed.at)), decipher.setAuthTag(tag);
35
+ const plain = Buffer.concat([
36
+ decipher.update(Buffer.from(sealed.ciphertext, "base64")),
37
+ decipher.final()
38
+ ]);
39
+ return JSON.parse(plain.toString("utf8"));
40
+ } catch {
41
+ return;
42
+ }
43
+ }
44
+ export {
45
+ openSuccessor,
46
+ sealSuccessor
47
+ };