@auth-craft/backend-sdk 0.6.8 → 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 +96 -196
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +76 -50
- package/dist/index.d.ts +76 -50
- package/dist/index.js +95 -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;
|
|
@@ -126,6 +131,11 @@ interface RemoveTenantMemberRequest {
|
|
|
126
131
|
userId: string;
|
|
127
132
|
actorUserId: string;
|
|
128
133
|
}
|
|
134
|
+
interface ListUserTenantsRequest {
|
|
135
|
+
userId: string;
|
|
136
|
+
limit?: number;
|
|
137
|
+
cursor?: string;
|
|
138
|
+
}
|
|
129
139
|
interface UpdateTenantProfileRequest {
|
|
130
140
|
tenantId: string;
|
|
131
141
|
userId: string;
|
|
@@ -181,7 +191,6 @@ interface BootstrapTenantOwnerResponse {
|
|
|
181
191
|
message: string;
|
|
182
192
|
tenantId: string;
|
|
183
193
|
userId: string;
|
|
184
|
-
role: string;
|
|
185
194
|
}
|
|
186
195
|
interface TenantProfileFields {
|
|
187
196
|
tenantId: string;
|
|
@@ -200,8 +209,8 @@ interface TenantProfileFields {
|
|
|
200
209
|
}
|
|
201
210
|
interface TenantProfileResponse extends TenantProfileFields {
|
|
202
211
|
status: string;
|
|
203
|
-
|
|
204
|
-
|
|
212
|
+
roles?: string[];
|
|
213
|
+
perms?: Record<string, number>;
|
|
205
214
|
authPerms: string[];
|
|
206
215
|
isOwner: boolean;
|
|
207
216
|
createdAt: string;
|
|
@@ -216,8 +225,8 @@ interface TenantMemberResponse {
|
|
|
216
225
|
tenantId: string;
|
|
217
226
|
userId: string;
|
|
218
227
|
status: string;
|
|
219
|
-
|
|
220
|
-
|
|
228
|
+
roles?: string[];
|
|
229
|
+
perms?: Record<string, number>;
|
|
221
230
|
authPerms: string[];
|
|
222
231
|
isOwner: boolean;
|
|
223
232
|
createdAt: string;
|
|
@@ -225,6 +234,18 @@ interface TenantMemberResponse {
|
|
|
225
234
|
tenantProfile?: TenantMemberProfileResponse;
|
|
226
235
|
}
|
|
227
236
|
type ListTenantMembersResponse = TenantMemberResponse[];
|
|
237
|
+
interface UserTenantResponse {
|
|
238
|
+
tenantId: string;
|
|
239
|
+
userId: string;
|
|
240
|
+
status: string;
|
|
241
|
+
roles?: string[];
|
|
242
|
+
perms?: Record<string, number>;
|
|
243
|
+
authPerms: string[];
|
|
244
|
+
isOwner: boolean;
|
|
245
|
+
createdAt: string;
|
|
246
|
+
updatedAt: string;
|
|
247
|
+
}
|
|
248
|
+
type ListUserTenantsResponse = UserTenantResponse[];
|
|
228
249
|
interface InvitedByInfo {
|
|
229
250
|
id: string;
|
|
230
251
|
name?: string;
|
|
@@ -238,8 +259,8 @@ interface TenantInviteResponse {
|
|
|
238
259
|
inviteeUserId?: string;
|
|
239
260
|
inviteeEmail?: string;
|
|
240
261
|
inviteePhone?: string;
|
|
241
|
-
|
|
242
|
-
|
|
262
|
+
roles?: string[];
|
|
263
|
+
perms?: Record<string, number>;
|
|
243
264
|
authPerms: string[];
|
|
244
265
|
displayName?: string;
|
|
245
266
|
givenName?: string;
|
|
@@ -404,6 +425,11 @@ declare class InternalClient {
|
|
|
404
425
|
* Protects last owner invariant.
|
|
405
426
|
*/
|
|
406
427
|
removeTenantMember(request: RemoveTenantMemberRequest): Promise<Result<void>>;
|
|
428
|
+
/**
|
|
429
|
+
* List all tenants a user belongs to (internal).
|
|
430
|
+
* No permission check — service is trusted.
|
|
431
|
+
*/
|
|
432
|
+
listUserTenants(request: ListUserTenantsRequest): Promise<Result<ListUserTenantsResponse>>;
|
|
407
433
|
/**
|
|
408
434
|
* List accounts with cursor-based pagination (internal).
|
|
409
435
|
* Requires VIEW_ACCOUNTS permission in the specified system tenant.
|
|
@@ -460,9 +486,10 @@ declare const sdkErrors: {
|
|
|
460
486
|
* baseUrl: 'https://auth.example.com',
|
|
461
487
|
* basePath: '/system',
|
|
462
488
|
* jwt: {
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
489
|
+
* privateKeyJwk: process.env.SERVICE_PRIVATE_KEY_JWK!,
|
|
490
|
+
* alg: 'EdDSA', // or 'ES256', 'RS256', 'PS256'
|
|
491
|
+
* serviceId: 'tenant-provisioning-service',
|
|
492
|
+
* roles: ['internal-service'],
|
|
466
493
|
* },
|
|
467
494
|
* });
|
|
468
495
|
*
|
|
@@ -472,9 +499,8 @@ declare const sdkErrors: {
|
|
|
472
499
|
|
|
473
500
|
/**
|
|
474
501
|
* Create an internal service client for Auth-Craft.
|
|
475
|
-
*
|
|
476
|
-
* The client auto-signs service JWTs and refreshes them before expiry.
|
|
502
|
+
* Requests are authenticated using short-lived Service JWT (EdDSA/ES256/RS256/PS256).
|
|
477
503
|
*/
|
|
478
504
|
declare function createInternalClient(config: InternalClientConfig): InternalClient;
|
|
479
505
|
|
|
480
|
-
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
|
-
|
|
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),
|
|
35
73
|
false,
|
|
36
74
|
["sign"]
|
|
37
75
|
);
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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,
|
|
65
|
-
{ name: "Ed25519" },
|
|
66
|
-
false,
|
|
67
|
-
["sign"]
|
|
68
|
-
);
|
|
69
|
-
}
|
|
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
|
-
);
|
|
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) {
|
|
@@ -457,6 +343,20 @@ var InternalClient = class {
|
|
|
457
343
|
);
|
|
458
344
|
}
|
|
459
345
|
// ============================================================
|
|
346
|
+
// User Tenants
|
|
347
|
+
// ============================================================
|
|
348
|
+
/**
|
|
349
|
+
* List all tenants a user belongs to (internal).
|
|
350
|
+
* No permission check — service is trusted.
|
|
351
|
+
*/
|
|
352
|
+
async listUserTenants(request) {
|
|
353
|
+
return this.http.request(
|
|
354
|
+
"POST",
|
|
355
|
+
"/user/tenants/list",
|
|
356
|
+
{ body: request }
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
// ============================================================
|
|
460
360
|
// Account Management (System-Tenant Only)
|
|
461
361
|
// ============================================================
|
|
462
362
|
/**
|