@auth-craft/backend-sdk 0.6.9 → 0.7.1

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/index.d.ts CHANGED
@@ -5,48 +5,53 @@ import { Result } from 'ts-micro-result';
5
5
  * Backend SDK Types
6
6
  * Configuration, request, and response types for internal service-to-service calls
7
7
  */
8
- /** HMAC-SHA256 symmetric signing */
9
- interface JwtHmacConfig {
10
- strategy: 'hmac';
11
- /** Shared HMAC secret. MUST be different from user-facing JWT secret. */
12
- secret: string;
13
- }
14
- /** EdDSA (Ed25519) asymmetric signing */
15
- interface JwtEddsaConfig {
16
- strategy: 'eddsa';
17
- /** Ed25519 private key as hex string or raw bytes */
18
- privateKey: string | Uint8Array;
19
- }
20
- /** RS256 (RSA-SHA256) asymmetric signing */
21
- interface JwtRs256Config {
22
- strategy: 'rs256';
23
- /** RSA private key in PEM or JWK format */
24
- privateKey: string | JsonWebKey;
25
- }
26
- /** ES256 (ECDSA P-256) asymmetric signing */
27
- interface JwtEs256Config {
28
- strategy: 'es256';
29
- /** ECDSA P-256 private key in PEM or JWK format */
30
- privateKey: string | JsonWebKey;
31
- }
32
- type JwtConfig = (JwtHmacConfig | JwtEddsaConfig | JwtRs256Config | JwtEs256Config) & {
33
- /** JWT issuer claim (e.g., 'tenant-provisioning-service') */
34
- issuer?: string;
35
- /** JWT audience claim (e.g., 'auth-service') */
8
+ interface ServiceJwtConfig {
9
+ /**
10
+ * Private key as base64-encoded JWK for signing service tokens.
11
+ * Must match the algorithm specified in `alg`.
12
+ *
13
+ * Generate (Node.js):
14
+ * EdDSA: subtle.generateKey({name:'Ed25519'}, true, ['sign','verify']) → exportKey('jwk', privateKey) → JSON.stringify → btoa
15
+ * ES256: subtle.generateKey({name:'ECDSA', namedCurve:'P-256'}, true, ['sign','verify']) → same
16
+ * RS256: subtle.generateKey({name:'RSASSA-PKCS1-v1_5', hash:'SHA-256', modulusLength:2048, publicExponent:Uint8Array.of(1,0,1)}, true, ['sign','verify']) → same
17
+ * PS256: subtle.generateKey({name:'RSA-PSS', hash:'SHA-256', modulusLength:2048, publicExponent:Uint8Array.of(1,0,1)}, true, ['sign','verify']) → same
18
+ */
19
+ privateKeyJwk: string;
20
+ /**
21
+ * Signing algorithm. Must be in the Worker's SERVICE_JWT_ALLOWED_ALGORITHMS whitelist.
22
+ * @default 'EdDSA'
23
+ */
24
+ alg?: 'EdDSA' | 'ES256' | 'RS256' | 'PS256';
25
+ /** Service identity — becomes the `sub` claim (e.g. 'svc_billing') */
26
+ serviceId: string;
27
+ /** Service roles embedded in token (e.g. ['internal-service']) */
28
+ roles?: string[];
29
+ /** Audience claim — must match Worker's SERVICE_JWT_AUDIENCE @default 'auth-craft:internal' */
36
30
  audience?: string;
37
- /** Token TTL in seconds @default 300 (5 minutes) */
38
- expiresInSeconds?: number;
39
- };
31
+ /** Token expiry in minutes @default 10 */
32
+ expiresInMinutes?: number;
33
+ /** Issuer claim — must match Worker's SERVICE_JWT_ISSUER if set @default 'auth-craft' */
34
+ issuer?: string;
35
+ }
40
36
  interface InternalClientConfig {
41
37
  /** Base URL of the auth service (e.g., 'https://auth.example.com') */
42
38
  baseUrl: string;
43
39
  /**
44
- * Base path prefix before /internal (e.g., '/system' → /system/internal/*)
40
+ * Base path prefix (e.g., '/system' → /system/{serviceRoutePath}/*)
45
41
  * @default ''
46
42
  */
47
43
  basePath?: string;
44
+ /**
45
+ * Path segment for service-to-service routes.
46
+ * Must match SERVICE_ROUTE_PREFIX configured on the Worker/Lambda.
47
+ * Can be changed to obscure the internal API surface.
48
+ *
49
+ * @default '/internal'
50
+ * @example '/svc' → requests go to {baseUrl}{basePath}/svc/*
51
+ */
52
+ serviceRoutePath?: string;
48
53
  /** Service JWT signing configuration */
49
- jwt: JwtConfig;
54
+ jwt: ServiceJwtConfig;
50
55
  /** Custom fetch implementation (for testing or middleware) */
51
56
  fetchImpl?: typeof fetch;
52
57
  /** Request timeout in milliseconds @default 30000 */
@@ -78,8 +83,8 @@ interface UpdateTenantMemberPermissionRequest {
78
83
  tenantId: string;
79
84
  userId: string;
80
85
  actorUserId: string;
81
- role?: string;
82
- permMask?: number;
86
+ roles?: string[];
87
+ perms?: Record<string, number>;
83
88
  authPerms?: string[];
84
89
  }
85
90
  interface ListTenantInvitesRequest {
@@ -95,8 +100,8 @@ interface InviteToTenantRequest {
95
100
  inviteeUserId?: string;
96
101
  inviteeEmail?: string;
97
102
  inviteePhone?: string;
98
- role?: string;
99
- permMask?: number;
103
+ roles?: string[];
104
+ perms?: Record<string, number>;
100
105
  authPerms?: string[];
101
106
  displayName?: string;
102
107
  givenName?: string;
@@ -186,7 +191,6 @@ interface BootstrapTenantOwnerResponse {
186
191
  message: string;
187
192
  tenantId: string;
188
193
  userId: string;
189
- role: string;
190
194
  }
191
195
  interface TenantProfileFields {
192
196
  tenantId: string;
@@ -205,8 +209,8 @@ interface TenantProfileFields {
205
209
  }
206
210
  interface TenantProfileResponse extends TenantProfileFields {
207
211
  status: string;
208
- role?: string;
209
- permMask: number;
212
+ roles?: string[];
213
+ perms?: Record<string, number>;
210
214
  authPerms: string[];
211
215
  isOwner: boolean;
212
216
  createdAt: string;
@@ -221,8 +225,8 @@ interface TenantMemberResponse {
221
225
  tenantId: string;
222
226
  userId: string;
223
227
  status: string;
224
- role?: string;
225
- permMask?: number;
228
+ roles?: string[];
229
+ perms?: Record<string, number>;
226
230
  authPerms: string[];
227
231
  isOwner: boolean;
228
232
  createdAt: string;
@@ -230,13 +234,11 @@ interface TenantMemberResponse {
230
234
  tenantProfile?: TenantMemberProfileResponse;
231
235
  }
232
236
  type ListTenantMembersResponse = TenantMemberResponse[];
233
- interface UserTenantResponse {
234
- tenantId: string;
235
- userId: string;
237
+ interface UserTenantResponse extends TenantProfileFields {
236
238
  status: string;
237
- role?: string;
238
- permMask?: number;
239
- authPerms: string[];
239
+ roles?: string[];
240
+ perms?: Record<string, number>;
241
+ authPerm?: number;
240
242
  isOwner: boolean;
241
243
  createdAt: string;
242
244
  updatedAt: string;
@@ -255,8 +257,8 @@ interface TenantInviteResponse {
255
257
  inviteeUserId?: string;
256
258
  inviteeEmail?: string;
257
259
  inviteePhone?: string;
258
- role?: string;
259
- permMask?: number;
260
+ roles?: string[];
261
+ perms?: Record<string, number>;
260
262
  authPerms: string[];
261
263
  displayName?: string;
262
264
  givenName?: string;
@@ -482,9 +484,10 @@ declare const sdkErrors: {
482
484
  * baseUrl: 'https://auth.example.com',
483
485
  * basePath: '/system',
484
486
  * jwt: {
485
- * strategy: 'hmac',
486
- * secret: process.env.INTERNAL_JWT_SECRET!,
487
- * issuer: 'tenant-provisioning-service',
487
+ * privateKeyJwk: process.env.SERVICE_PRIVATE_KEY_JWK!,
488
+ * alg: 'EdDSA', // or 'ES256', 'RS256', 'PS256'
489
+ * serviceId: 'tenant-provisioning-service',
490
+ * roles: ['internal-service'],
488
491
  * },
489
492
  * });
490
493
  *
@@ -494,9 +497,8 @@ declare const sdkErrors: {
494
497
 
495
498
  /**
496
499
  * Create an internal service client for Auth-Craft.
497
- *
498
- * The client auto-signs service JWTs and refreshes them before expiry.
500
+ * Requests are authenticated using short-lived Service JWT (EdDSA/ES256/RS256/PS256).
499
501
  */
500
502
  declare function createInternalClient(config: InternalClientConfig): InternalClient;
501
503
 
502
- export { AUTH_PERM_STRINGS, type AcceptInviteRequest, type AcceptInviteResponse, type AccountDetailResponse, type AccountPermContextRequest, type AccountSummaryResponse, type AuthPermString, type BootstrapTenantOwnerRequest, type BootstrapTenantOwnerResponse, type CheckPendingInvitesRequest, type CheckPendingInvitesResponse, type DeclineInviteRequest, type GetAccountRequest, type GetTenantProfileRequest, InternalClient, type InternalClientConfig, type InviteToTenantRequest, type InviteToTenantResponse, type InvitedByInfo, type JwtConfig, type JwtEddsaConfig, type JwtEs256Config, type JwtHmacConfig, type JwtRs256Config, type ListAccountsRequest, type ListAccountsResponse, type ListTenantInvitesRequest, type ListTenantInvitesResponse, type ListTenantMembersRequest, type ListTenantMembersResponse, type ListUserTenantsRequest, type ListUserTenantsResponse, type RemoveAccountRequest, type RemoveTenantMemberRequest, type ResetAccountCredentialsRequest, type RevokeInviteRequest, type TenantInviteResponse, type TenantMemberProfileResponse, type TenantMemberResponse, type TenantProfileFields, type TenantProfileResponse, type UpdateAccountProfileRequest, type UpdateAccountStatusRequest, type UpdateTenantMemberPermissionRequest, type UpdateTenantMemberStatusRequest, type UpdateTenantProfileRequest, type UserTenantResponse, createInternalClient, getHttpStatus, sdkErrors };
504
+ export { AUTH_PERM_STRINGS, type AcceptInviteRequest, type AcceptInviteResponse, type AccountDetailResponse, type AccountPermContextRequest, type AccountSummaryResponse, type AuthPermString, type BootstrapTenantOwnerRequest, type BootstrapTenantOwnerResponse, type CheckPendingInvitesRequest, type CheckPendingInvitesResponse, type DeclineInviteRequest, type GetAccountRequest, type GetTenantProfileRequest, InternalClient, type InternalClientConfig, type InviteToTenantRequest, type InviteToTenantResponse, type InvitedByInfo, type ListAccountsRequest, type ListAccountsResponse, type ListTenantInvitesRequest, type ListTenantInvitesResponse, type ListTenantMembersRequest, type ListTenantMembersResponse, type ListUserTenantsRequest, type ListUserTenantsResponse, type RemoveAccountRequest, type RemoveTenantMemberRequest, type ResetAccountCredentialsRequest, type RevokeInviteRequest, type ServiceJwtConfig, type TenantInviteResponse, type TenantMemberProfileResponse, type TenantMemberResponse, type TenantProfileFields, type TenantProfileResponse, type UpdateAccountProfileRequest, type UpdateAccountStatusRequest, type UpdateTenantMemberPermissionRequest, type UpdateTenantMemberStatusRequest, type UpdateTenantProfileRequest, type UserTenantResponse, createInternalClient, getHttpStatus, sdkErrors };
package/dist/index.js CHANGED
@@ -2,205 +2,109 @@
2
2
  import { ok, err } from "ts-micro-result";
3
3
 
4
4
  // src/jwt-signer.ts
5
- function base64urlEncode(data) {
6
- let binary = "";
7
- for (let i = 0; i < data.length; i++) {
8
- binary += String.fromCharCode(data[i]);
5
+ var TOKEN_CACHE_BUFFER_SECONDS = 60;
6
+ var tokenCache = /* @__PURE__ */ new Map();
7
+ function algToImportParams(alg) {
8
+ switch (alg) {
9
+ case "EdDSA":
10
+ return { name: "Ed25519" };
11
+ case "ES256":
12
+ return { name: "ECDSA", namedCurve: "P-256" };
13
+ case "RS256":
14
+ return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
15
+ case "PS256":
16
+ return { name: "RSA-PSS", hash: "SHA-256" };
9
17
  }
10
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
11
18
  }
12
- function hexToUint8Array(hex) {
13
- const bytes = new Uint8Array(hex.length / 2);
14
- for (let i = 0; i < hex.length; i += 2) {
15
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
19
+ function algToSignParams(alg) {
20
+ switch (alg) {
21
+ case "EdDSA":
22
+ return "Ed25519";
23
+ case "ES256":
24
+ return { name: "ECDSA", hash: "SHA-256" };
25
+ case "RS256":
26
+ return { name: "RSASSA-PKCS1-v1_5" };
27
+ case "PS256":
28
+ return { name: "RSA-PSS", saltLength: 32 };
16
29
  }
17
- return bytes;
18
30
  }
19
- function parsePemToSpki(pem) {
20
- const pemBody = pem.replace(/-----BEGIN PRIVATE KEY-----/g, "").replace(/-----END PRIVATE KEY-----/g, "").replace(/\s/g, "");
21
- const binary = atob(pemBody);
22
- const bytes = new Uint8Array(binary.length);
23
- for (let i = 0; i < binary.length; i++) {
24
- bytes[i] = binary.charCodeAt(i);
25
- }
26
- return bytes;
27
- }
28
- async function importHmacSigningKey(secret) {
29
- const encoder = new TextEncoder();
30
- const keyData = encoder.encode(secret);
31
+ var HEX_ED25519_RE = /^[0-9a-fA-F]{64}$/;
32
+ async function importEd25519HexKey(hex) {
33
+ const bytes = new Uint8Array(32);
34
+ for (let i = 0; i < 32; i++) {
35
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
36
+ }
31
37
  return crypto.subtle.importKey(
32
38
  "raw",
33
- keyData.buffer,
34
- { name: "HMAC", hash: "SHA-256" },
35
- false,
36
- ["sign"]
37
- );
38
- }
39
- var ED25519_PKCS8_PREFIX = new Uint8Array([
40
- 48,
41
- 46,
42
- 2,
43
- 1,
44
- 0,
45
- 48,
46
- 5,
47
- 6,
48
- 3,
49
- 43,
50
- 101,
51
- 112,
52
- 4,
53
- 34,
54
- 4,
55
- 32
56
- ]);
57
- async function importEdDSAPrivateKey(privateKey) {
58
- const keyBytes = typeof privateKey === "string" ? hexToUint8Array(privateKey) : privateKey;
59
- const pkcs8 = new Uint8Array(ED25519_PKCS8_PREFIX.length + keyBytes.length);
60
- pkcs8.set(ED25519_PKCS8_PREFIX);
61
- pkcs8.set(keyBytes, ED25519_PKCS8_PREFIX.length);
62
- return crypto.subtle.importKey(
63
- "pkcs8",
64
- pkcs8.buffer,
39
+ bytes,
65
40
  { name: "Ed25519" },
66
41
  false,
67
42
  ["sign"]
68
43
  );
69
44
  }
70
- async function importRsaPrivateKey(privateKey) {
71
- if (typeof privateKey === "object") {
72
- return crypto.subtle.importKey(
73
- "jwk",
74
- privateKey,
75
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
76
- false,
77
- ["sign"]
78
- );
45
+ async function importPrivateKey(raw, alg) {
46
+ if (HEX_ED25519_RE.test(raw)) {
47
+ if (alg !== "EdDSA") {
48
+ throw new Error(`Hex key format is only supported for EdDSA, got ${alg}`);
49
+ }
50
+ return importEd25519HexKey(raw);
79
51
  }
80
- const pkcs8Bytes = parsePemToSpki(privateKey);
81
- return crypto.subtle.importKey(
82
- "pkcs8",
83
- pkcs8Bytes.buffer,
84
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
85
- false,
86
- ["sign"]
87
- );
88
- }
89
- async function importEcdsaPrivateKey(privateKey) {
90
- if (typeof privateKey === "object") {
91
- return crypto.subtle.importKey(
92
- "jwk",
93
- privateKey,
94
- { name: "ECDSA", namedCurve: "P-256" },
95
- false,
96
- ["sign"]
97
- );
52
+ let jwk;
53
+ try {
54
+ jwk = JSON.parse(atob(raw));
55
+ } catch {
56
+ throw new Error(`Invalid privateKeyJwk: failed to parse JWK for algorithm ${alg}`);
98
57
  }
99
- const pkcs8Bytes = parsePemToSpki(privateKey);
100
- return crypto.subtle.importKey(
101
- "pkcs8",
102
- pkcs8Bytes.buffer,
103
- { name: "ECDSA", namedCurve: "P-256" },
104
- false,
105
- ["sign"]
106
- );
58
+ return crypto.subtle.importKey("jwk", jwk, algToImportParams(alg), false, ["sign"]);
107
59
  }
108
- async function resolveSignKey(config) {
109
- const strategy = config.strategy;
110
- switch (strategy) {
111
- case "hmac": {
112
- const c = config;
113
- return {
114
- key: await importHmacSigningKey(c.secret),
115
- jwtAlgorithm: "HS256",
116
- cryptoAlgorithm: "HMAC"
117
- };
118
- }
119
- case "eddsa": {
120
- const c = config;
121
- return {
122
- key: await importEdDSAPrivateKey(c.privateKey),
123
- jwtAlgorithm: "EdDSA",
124
- cryptoAlgorithm: { name: "Ed25519" }
125
- };
126
- }
127
- case "rs256": {
128
- const c = config;
129
- return {
130
- key: await importRsaPrivateKey(c.privateKey),
131
- jwtAlgorithm: "RS256",
132
- cryptoAlgorithm: "RSASSA-PKCS1-v1_5"
133
- };
134
- }
135
- case "es256": {
136
- const c = config;
137
- return {
138
- key: await importEcdsaPrivateKey(c.privateKey),
139
- jwtAlgorithm: "ES256",
140
- cryptoAlgorithm: { name: "ECDSA", hash: "SHA-256" }
141
- };
142
- }
143
- }
60
+ function base64UrlEncode(bytes) {
61
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
144
62
  }
145
- var REFRESH_BUFFER_SECONDS = 60;
146
- var JwtSigner = class {
147
- constructor(config) {
148
- this.config = config;
63
+ async function buildServiceJwtHeader(config) {
64
+ const alg = config.alg ?? "EdDSA";
65
+ const now = Math.floor(Date.now() / 1e3);
66
+ const audience = config.audience ?? "auth-craft:internal";
67
+ const issuer = config.issuer ?? "auth-craft";
68
+ const expiresInMinutes = config.expiresInMinutes ?? 10;
69
+ const cacheKey = `${config.serviceId}:${audience}:${issuer}`;
70
+ const cached = tokenCache.get(cacheKey);
71
+ if (cached && cached.expiresAt > Date.now()) {
72
+ return { Authorization: `Bearer ${cached.token}` };
73
+ }
74
+ const header = { alg, typ: "JWT" };
75
+ const payload = {
76
+ sub: config.serviceId,
77
+ aud: audience,
78
+ iss: issuer,
79
+ jti: crypto.randomUUID(),
80
+ typ: 3,
81
+ // TokenType.Service
82
+ iat: now,
83
+ exp: now + expiresInMinutes * 60
84
+ };
85
+ if (config.roles !== void 0) {
86
+ payload["roles"] = config.roles;
149
87
  }
150
- cachedKeyInfo = null;
151
- cachedToken = null;
152
- cachedExp = 0;
153
- /**
154
- * Get a valid service JWT token.
155
- * Automatically signs a new token when the current one is about to expire.
156
- */
157
- async getToken() {
158
- const nowSeconds = Math.floor(Date.now() / 1e3);
159
- if (this.cachedToken && nowSeconds < this.cachedExp - REFRESH_BUFFER_SECONDS) {
160
- return this.cachedToken;
161
- }
162
- return this.signNewToken();
163
- }
164
- async signNewToken() {
165
- const keyInfo = await this.getKeyInfo();
166
- const encoder = new TextEncoder();
167
- const expiresInSeconds = this.config.expiresInSeconds ?? 300;
168
- const nowSeconds = Math.floor(Date.now() / 1e3);
169
- const header = base64urlEncode(
170
- encoder.encode(JSON.stringify({ alg: keyInfo.jwtAlgorithm, typ: "JWT" }))
171
- );
172
- const payload = {
173
- iat: nowSeconds,
174
- exp: nowSeconds + expiresInSeconds
175
- };
176
- if (this.config.issuer !== void 0) {
177
- payload.iss = this.config.issuer;
178
- }
179
- if (this.config.audience !== void 0) {
180
- payload.aud = this.config.audience;
181
- }
182
- const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));
183
- const signData = encoder.encode(`${header}.${payloadB64}`);
184
- const signatureBytes = new Uint8Array(
185
- await crypto.subtle.sign(
186
- keyInfo.cryptoAlgorithm,
187
- keyInfo.key,
188
- signData.buffer
189
- )
190
- );
191
- const signature = base64urlEncode(signatureBytes);
192
- const token = `${header}.${payloadB64}.${signature}`;
193
- this.cachedToken = token;
194
- this.cachedExp = nowSeconds + expiresInSeconds;
195
- return token;
196
- }
197
- async getKeyInfo() {
198
- if (!this.cachedKeyInfo) {
199
- this.cachedKeyInfo = await resolveSignKey(this.config);
200
- }
201
- return this.cachedKeyInfo;
202
- }
203
- };
88
+ const encoder = new TextEncoder();
89
+ const headerB64 = base64UrlEncode(encoder.encode(JSON.stringify(header)));
90
+ const payloadB64 = base64UrlEncode(encoder.encode(JSON.stringify(payload)));
91
+ const unsignedToken = `${headerB64}.${payloadB64}`;
92
+ let cryptoKey;
93
+ try {
94
+ cryptoKey = await importPrivateKey(config.privateKeyJwk, alg);
95
+ } catch (e) {
96
+ throw new Error(`Invalid privateKeyJwk: failed to import key for algorithm ${alg}. ${e instanceof Error ? e.message : ""}`);
97
+ }
98
+ const signatureBuffer = await crypto.subtle.sign(
99
+ algToSignParams(alg),
100
+ cryptoKey,
101
+ encoder.encode(unsignedToken)
102
+ );
103
+ const token = `${unsignedToken}.${base64UrlEncode(new Uint8Array(signatureBuffer))}`;
104
+ const expiresAt = (now + expiresInMinutes * 60 - TOKEN_CACHE_BUFFER_SECONDS) * 1e3;
105
+ tokenCache.set(cacheKey, { token, expiresAt });
106
+ return { Authorization: `Bearer ${token}` };
107
+ }
204
108
 
205
109
  // src/errors.ts
206
110
  import { defineError } from "ts-micro-result";
@@ -213,33 +117,37 @@ var sdkErrors = {
213
117
 
214
118
  // src/http-client.ts
215
119
  var HttpClient = class {
216
- signer;
120
+ config;
217
121
  baseUrl;
218
122
  basePath;
123
+ serviceRoutePath;
219
124
  fetchFn;
220
125
  timeout;
221
126
  customHeaders;
222
127
  constructor(config) {
223
- this.signer = new JwtSigner(config.jwt);
128
+ this.config = config;
224
129
  this.baseUrl = config.baseUrl.replace(/\/$/, "");
225
130
  this.basePath = config.basePath ?? "";
131
+ const rawSrp = config.serviceRoutePath ?? "/internal";
132
+ const srp = rawSrp.startsWith("/") ? rawSrp : `/${rawSrp}`;
133
+ this.serviceRoutePath = srp.endsWith("/") ? srp.slice(0, -1) : srp;
226
134
  this.fetchFn = config.fetchImpl ?? globalThis.fetch;
227
135
  this.timeout = config.timeout ?? 3e4;
228
136
  this.customHeaders = config.headers ?? {};
229
137
  }
230
138
  async request(method, path, options) {
231
139
  try {
232
- let token;
140
+ const url = this.buildUrl(path, options?.query);
141
+ let jwtHeader;
233
142
  try {
234
- token = await this.signer.getToken();
143
+ jwtHeader = await buildServiceJwtHeader(this.config.jwt);
235
144
  } catch (signError) {
236
145
  const message = signError instanceof Error ? signError.message : String(signError);
237
146
  return err(sdkErrors.JWT_SIGN_FAILED({ message }));
238
147
  }
239
- const url = this.buildUrl(path, options?.query);
240
148
  const headers = {
241
149
  "Content-Type": "application/json",
242
- "Authorization": `Bearer ${token}`,
150
+ ...jwtHeader,
243
151
  ...this.customHeaders
244
152
  };
245
153
  const controller = new AbortController();
@@ -285,7 +193,7 @@ var HttpClient = class {
285
193
  }
286
194
  }
287
195
  buildUrl(path, query) {
288
- let url = `${this.baseUrl}${this.basePath}/internal${path}`;
196
+ let url = `${this.baseUrl}${this.basePath}${this.serviceRoutePath}${path}`;
289
197
  if (query) {
290
198
  const entries = Object.entries(query).filter(([, v]) => v !== void 0);
291
199
  if (entries.length > 0) {