@auth-craft/backend-sdk 0.6.9 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +82 -196
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -52
- package/dist/index.d.ts +56 -52
- package/dist/index.js +81 -195
- package/dist/index.js.map +1 -1
- package/package.json +35 -32
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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
/**
|
|
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
|
|
38
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
82
|
-
|
|
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
|
-
|
|
99
|
-
|
|
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
|
-
|
|
209
|
-
|
|
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
|
-
|
|
225
|
-
|
|
228
|
+
roles?: string[];
|
|
229
|
+
perms?: Record<string, number>;
|
|
226
230
|
authPerms: string[];
|
|
227
231
|
isOwner: boolean;
|
|
228
232
|
createdAt: string;
|
|
@@ -234,8 +238,8 @@ interface UserTenantResponse {
|
|
|
234
238
|
tenantId: string;
|
|
235
239
|
userId: string;
|
|
236
240
|
status: string;
|
|
237
|
-
|
|
238
|
-
|
|
241
|
+
roles?: string[];
|
|
242
|
+
perms?: Record<string, number>;
|
|
239
243
|
authPerms: string[];
|
|
240
244
|
isOwner: boolean;
|
|
241
245
|
createdAt: string;
|
|
@@ -255,8 +259,8 @@ interface TenantInviteResponse {
|
|
|
255
259
|
inviteeUserId?: string;
|
|
256
260
|
inviteeEmail?: string;
|
|
257
261
|
inviteePhone?: string;
|
|
258
|
-
|
|
259
|
-
|
|
262
|
+
roles?: string[];
|
|
263
|
+
perms?: Record<string, number>;
|
|
260
264
|
authPerms: string[];
|
|
261
265
|
displayName?: string;
|
|
262
266
|
givenName?: string;
|
|
@@ -482,9 +486,10 @@ declare const sdkErrors: {
|
|
|
482
486
|
* baseUrl: 'https://auth.example.com',
|
|
483
487
|
* basePath: '/system',
|
|
484
488
|
* jwt: {
|
|
485
|
-
*
|
|
486
|
-
*
|
|
487
|
-
*
|
|
489
|
+
* privateKeyJwk: process.env.SERVICE_PRIVATE_KEY_JWK!,
|
|
490
|
+
* alg: 'EdDSA', // or 'ES256', 'RS256', 'PS256'
|
|
491
|
+
* serviceId: 'tenant-provisioning-service',
|
|
492
|
+
* roles: ['internal-service'],
|
|
488
493
|
* },
|
|
489
494
|
* });
|
|
490
495
|
*
|
|
@@ -494,9 +499,8 @@ declare const sdkErrors: {
|
|
|
494
499
|
|
|
495
500
|
/**
|
|
496
501
|
* Create an internal service client for Auth-Craft.
|
|
497
|
-
*
|
|
498
|
-
* The client auto-signs service JWTs and refreshes them before expiry.
|
|
502
|
+
* Requests are authenticated using short-lived Service JWT (EdDSA/ES256/RS256/PS256).
|
|
499
503
|
*/
|
|
500
504
|
declare function createInternalClient(config: InternalClientConfig): InternalClient;
|
|
501
505
|
|
|
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
|
|
506
|
+
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,87 @@
|
|
|
2
2
|
import { ok, err } from "ts-micro-result";
|
|
3
3
|
|
|
4
4
|
// src/jwt-signer.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
|
20
|
-
|
|
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;
|
|
31
|
+
function base64UrlEncode(bytes) {
|
|
32
|
+
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
27
33
|
}
|
|
28
|
-
async function
|
|
34
|
+
async function buildServiceJwtHeader(config) {
|
|
35
|
+
const alg = config.alg ?? "EdDSA";
|
|
36
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
37
|
+
const audience = config.audience ?? "auth-craft:internal";
|
|
38
|
+
const issuer = config.issuer ?? "auth-craft";
|
|
39
|
+
const expiresInMinutes = config.expiresInMinutes ?? 10;
|
|
40
|
+
const cacheKey = `${config.serviceId}:${audience}:${issuer}`;
|
|
41
|
+
const cached = tokenCache.get(cacheKey);
|
|
42
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
43
|
+
return { Authorization: `Bearer ${cached.token}` };
|
|
44
|
+
}
|
|
45
|
+
const header = { alg, typ: "JWT" };
|
|
46
|
+
const payload = {
|
|
47
|
+
sub: config.serviceId,
|
|
48
|
+
aud: audience,
|
|
49
|
+
iss: issuer,
|
|
50
|
+
jti: crypto.randomUUID(),
|
|
51
|
+
typ: 3,
|
|
52
|
+
// TokenType.Service
|
|
53
|
+
iat: now,
|
|
54
|
+
exp: now + expiresInMinutes * 60
|
|
55
|
+
};
|
|
56
|
+
if (config.roles !== void 0) {
|
|
57
|
+
payload["roles"] = config.roles;
|
|
58
|
+
}
|
|
29
59
|
const encoder = new TextEncoder();
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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,
|
|
65
|
-
{ name: "Ed25519" },
|
|
60
|
+
const headerB64 = base64UrlEncode(encoder.encode(JSON.stringify(header)));
|
|
61
|
+
const payloadB64 = base64UrlEncode(encoder.encode(JSON.stringify(payload)));
|
|
62
|
+
const unsignedToken = `${headerB64}.${payloadB64}`;
|
|
63
|
+
let jwk;
|
|
64
|
+
try {
|
|
65
|
+
jwk = JSON.parse(atob(config.privateKeyJwk));
|
|
66
|
+
} catch {
|
|
67
|
+
throw new Error(`Invalid privateKeyJwk: failed to parse JWK for algorithm ${alg}`);
|
|
68
|
+
}
|
|
69
|
+
const cryptoKey = await crypto.subtle.importKey(
|
|
70
|
+
"jwk",
|
|
71
|
+
jwk,
|
|
72
|
+
algToImportParams(alg),
|
|
66
73
|
false,
|
|
67
74
|
["sign"]
|
|
68
75
|
);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
"jwk",
|
|
74
|
-
privateKey,
|
|
75
|
-
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
|
|
76
|
-
false,
|
|
77
|
-
["sign"]
|
|
78
|
-
);
|
|
79
|
-
}
|
|
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"]
|
|
76
|
+
const signatureBuffer = await crypto.subtle.sign(
|
|
77
|
+
algToSignParams(alg),
|
|
78
|
+
cryptoKey,
|
|
79
|
+
encoder.encode(unsignedToken)
|
|
87
80
|
);
|
|
81
|
+
const token = `${unsignedToken}.${base64UrlEncode(new Uint8Array(signatureBuffer))}`;
|
|
82
|
+
const expiresAt = (now + expiresInMinutes * 60 - TOKEN_CACHE_BUFFER_SECONDS) * 1e3;
|
|
83
|
+
tokenCache.set(cacheKey, { token, expiresAt });
|
|
84
|
+
return { Authorization: `Bearer ${token}` };
|
|
88
85
|
}
|
|
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
|
-
);
|
|
98
|
-
}
|
|
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
|
-
);
|
|
107
|
-
}
|
|
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
|
-
}
|
|
144
|
-
}
|
|
145
|
-
var REFRESH_BUFFER_SECONDS = 60;
|
|
146
|
-
var JwtSigner = class {
|
|
147
|
-
constructor(config) {
|
|
148
|
-
this.config = config;
|
|
149
|
-
}
|
|
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
|
-
};
|
|
204
86
|
|
|
205
87
|
// src/errors.ts
|
|
206
88
|
import { defineError } from "ts-micro-result";
|
|
@@ -213,33 +95,37 @@ var sdkErrors = {
|
|
|
213
95
|
|
|
214
96
|
// src/http-client.ts
|
|
215
97
|
var HttpClient = class {
|
|
216
|
-
|
|
98
|
+
config;
|
|
217
99
|
baseUrl;
|
|
218
100
|
basePath;
|
|
101
|
+
serviceRoutePath;
|
|
219
102
|
fetchFn;
|
|
220
103
|
timeout;
|
|
221
104
|
customHeaders;
|
|
222
105
|
constructor(config) {
|
|
223
|
-
this.
|
|
106
|
+
this.config = config;
|
|
224
107
|
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
225
108
|
this.basePath = config.basePath ?? "";
|
|
109
|
+
const rawSrp = config.serviceRoutePath ?? "/internal";
|
|
110
|
+
const srp = rawSrp.startsWith("/") ? rawSrp : `/${rawSrp}`;
|
|
111
|
+
this.serviceRoutePath = srp.endsWith("/") ? srp.slice(0, -1) : srp;
|
|
226
112
|
this.fetchFn = config.fetchImpl ?? globalThis.fetch;
|
|
227
113
|
this.timeout = config.timeout ?? 3e4;
|
|
228
114
|
this.customHeaders = config.headers ?? {};
|
|
229
115
|
}
|
|
230
116
|
async request(method, path, options) {
|
|
231
117
|
try {
|
|
232
|
-
|
|
118
|
+
const url = this.buildUrl(path, options?.query);
|
|
119
|
+
let jwtHeader;
|
|
233
120
|
try {
|
|
234
|
-
|
|
121
|
+
jwtHeader = await buildServiceJwtHeader(this.config.jwt);
|
|
235
122
|
} catch (signError) {
|
|
236
123
|
const message = signError instanceof Error ? signError.message : String(signError);
|
|
237
124
|
return err(sdkErrors.JWT_SIGN_FAILED({ message }));
|
|
238
125
|
}
|
|
239
|
-
const url = this.buildUrl(path, options?.query);
|
|
240
126
|
const headers = {
|
|
241
127
|
"Content-Type": "application/json",
|
|
242
|
-
|
|
128
|
+
...jwtHeader,
|
|
243
129
|
...this.customHeaders
|
|
244
130
|
};
|
|
245
131
|
const controller = new AbortController();
|
|
@@ -285,7 +171,7 @@ var HttpClient = class {
|
|
|
285
171
|
}
|
|
286
172
|
}
|
|
287
173
|
buildUrl(path, query) {
|
|
288
|
-
let url = `${this.baseUrl}${this.basePath}
|
|
174
|
+
let url = `${this.baseUrl}${this.basePath}${this.serviceRoutePath}${path}`;
|
|
289
175
|
if (query) {
|
|
290
176
|
const entries = Object.entries(query).filter(([, v]) => v !== void 0);
|
|
291
177
|
if (entries.length > 0) {
|