@auth-craft/backend-sdk 0.8.1 → 0.8.3

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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Service JWT Signer
3
+ * Signs outgoing requests with a short-lived service JWT for service-to-service authentication.
4
+ * Uses Web Crypto API — edge compatible, zero dependencies.
5
+ *
6
+ * Supported algorithms: EdDSA, ES256, RS256, PS256
7
+ * Key formats:
8
+ * - JWK encoded as base64 (all algorithms)
9
+ * - Hex string, 64 chars (EdDSA only — 32-byte Ed25519 private key seed)
10
+ */
11
+ // ── Token cache ───────────────────────────────────────────────────────────────
12
+ // Key: `${serviceId}:${audience}:${issuer}` → { token, expiresAt (epoch ms) }
13
+ // Tokens are evicted 60s before expiry to avoid using a near-expired token.
14
+ const TOKEN_CACHE_BUFFER_SECONDS = 60;
15
+ const tokenCache = new Map();
16
+ function algToImportParams(alg) {
17
+ switch (alg) {
18
+ case 'EdDSA':
19
+ return { name: 'Ed25519' };
20
+ case 'ES256':
21
+ return { name: 'ECDSA', namedCurve: 'P-256' };
22
+ case 'RS256':
23
+ return { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
24
+ case 'PS256':
25
+ return { name: 'RSA-PSS', hash: 'SHA-256' };
26
+ }
27
+ }
28
+ function algToSignParams(alg) {
29
+ switch (alg) {
30
+ case 'EdDSA':
31
+ return 'Ed25519';
32
+ case 'ES256':
33
+ return { name: 'ECDSA', hash: 'SHA-256' };
34
+ case 'RS256':
35
+ return { name: 'RSASSA-PKCS1-v1_5' };
36
+ case 'PS256':
37
+ return { name: 'RSA-PSS', saltLength: 32 };
38
+ }
39
+ }
40
+ const HEX_ED25519_RE = /^[0-9a-fA-F]{64}$/;
41
+ /**
42
+ * Import an Ed25519 private key from a 32-byte hex seed.
43
+ * Wraps the raw seed in a minimal PKCS#8 DER envelope (RFC 8410).
44
+ * The 'raw' format is not supported for Ed25519 signing in all runtimes.
45
+ */
46
+ async function importEd25519HexKey(hex) {
47
+ const seed = new Uint8Array(32);
48
+ for (let i = 0; i < 32; i++) {
49
+ seed[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
50
+ }
51
+ // PKCS#8 DER prefix for Ed25519 (RFC 8410): SEQUENCE { version, AlgorithmIdentifier { OID 1.3.101.112 }, OCTET STRING { OCTET STRING { seed } } }
52
+ const prefix = new Uint8Array([
53
+ 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
54
+ ]);
55
+ const pkcs8 = new Uint8Array(prefix.length + 32);
56
+ pkcs8.set(prefix);
57
+ pkcs8.set(seed, prefix.length);
58
+ return crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, false, ['sign']);
59
+ }
60
+ /**
61
+ * Detect key format and import CryptoKey:
62
+ * 1. 64-char hex → Ed25519 raw seed import (EdDSA only)
63
+ * 2. base64-encoded JWK → standard JWK import (all algorithms)
64
+ */
65
+ async function importPrivateKey(raw, alg) {
66
+ if (HEX_ED25519_RE.test(raw)) {
67
+ if (alg !== 'EdDSA') {
68
+ throw new Error(`Hex key format is only supported for EdDSA, got ${alg}`);
69
+ }
70
+ return importEd25519HexKey(raw);
71
+ }
72
+ let jwk;
73
+ try {
74
+ jwk = JSON.parse(atob(raw));
75
+ }
76
+ catch {
77
+ throw new Error(`Invalid privateKeyJwk: failed to parse JWK for algorithm ${alg}`);
78
+ }
79
+ return crypto.subtle.importKey('jwk', jwk, algToImportParams(alg), false, ['sign']);
80
+ }
81
+ function base64UrlEncode(bytes) {
82
+ return btoa(String.fromCharCode(...bytes))
83
+ .replace(/\+/g, '-')
84
+ .replace(/\//g, '_')
85
+ .replace(/=/g, '');
86
+ }
87
+ /**
88
+ * Sign a short-lived service JWT.
89
+ * Tokens are cached in memory and reused until 60s before expiry.
90
+ * A new token is signed when the cache is empty or the cached token is near-expired.
91
+ */
92
+ export async function buildServiceJwtHeader(config) {
93
+ const alg = config.alg ?? 'EdDSA';
94
+ const now = Math.floor(Date.now() / 1000);
95
+ const audience = config.audience ?? 'auth-craft:internal';
96
+ const issuer = config.issuer ?? 'auth-craft';
97
+ const expiresInMinutes = config.expiresInMinutes ?? 10;
98
+ const cacheKey = `${config.serviceId}:${audience}:${issuer}`;
99
+ const cached = tokenCache.get(cacheKey);
100
+ if (cached && cached.expiresAt > Date.now()) {
101
+ return { Authorization: `Bearer ${cached.token}` };
102
+ }
103
+ const header = { alg, typ: 'JWT' };
104
+ const payload = {
105
+ sub: config.serviceId,
106
+ aud: audience,
107
+ iss: issuer,
108
+ jti: crypto.randomUUID(),
109
+ typ: 3, // TokenType.Service
110
+ iat: now,
111
+ exp: now + expiresInMinutes * 60,
112
+ };
113
+ if (config.roles !== undefined) {
114
+ payload.roles = config.roles;
115
+ }
116
+ const encoder = new TextEncoder();
117
+ const headerB64 = base64UrlEncode(encoder.encode(JSON.stringify(header)));
118
+ const payloadB64 = base64UrlEncode(encoder.encode(JSON.stringify(payload)));
119
+ const unsignedToken = `${headerB64}.${payloadB64}`;
120
+ // Import private key — auto-detects hex (EdDSA raw) or JWK base64 format
121
+ const rawKey = config.privateKey;
122
+ let cryptoKey;
123
+ try {
124
+ cryptoKey = await importPrivateKey(rawKey, alg);
125
+ }
126
+ catch (e) {
127
+ throw new Error(`Invalid privateKeyJwk: failed to import key for algorithm ${alg}. ${e instanceof Error ? e.message : ''}`);
128
+ }
129
+ const signatureBuffer = await crypto.subtle.sign(algToSignParams(alg), cryptoKey, encoder.encode(unsignedToken));
130
+ const token = `${unsignedToken}.${base64UrlEncode(new Uint8Array(signatureBuffer))}`;
131
+ const expiresAt = (now + expiresInMinutes * 60 - TOKEN_CACHE_BUFFER_SECONDS) * 1000;
132
+ tokenCache.set(cacheKey, { token, expiresAt });
133
+ return { Authorization: `Bearer ${token}` };
134
+ }
135
+ /** Clear the token cache (useful for testing or after key rotation). */
136
+ export function clearServiceJwtCache() {
137
+ tokenCache.clear();
138
+ }
139
+ //# sourceMappingURL=jwt-signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt-signer.js","sourceRoot":"","sources":["../src/jwt-signer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,iFAAiF;AACjF,8EAA8E;AAC9E,4EAA4E;AAE5E,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAOtC,MAAM,UAAU,GAAG,IAAI,GAAG,EAAuB,CAAC;AAIlD,SAAS,iBAAiB,CAAC,GAAiB;IAC1C,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,SAAS,EAAqB,CAAC;QAChD,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAqB,CAAC;QACnE,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,IAAI,EAAE,SAAS,EAAqB,CAAC;QAC3E,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAqB,CAAC;IACnE,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,GAAiB;IACxC,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,OAAO;YACV,OAAO,SAA4B,CAAC;QACtC,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAqB,CAAC;QAC/D,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAqB,CAAC;QAC1D,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAqB,CAAC;IAClE,CAAC;AACH,CAAC;AAED,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAE3C;;;;GAIG;AACH,KAAK,UAAU,mBAAmB,CAAC,GAAW;IAC5C,MAAM,IAAI,GAAG,IA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AC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3G,CAAC;IACJ,CAAC;IAED,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IAEjH,MAAM,KAAK,GAAG,GAAG,aAAa,IAAI,eAAe,CAAC,IAAI,UAAU,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC;IAErF,MAAM,SAAS,GAAG,CAAC,GAAG,GAAG,gBAAgB,GAAG,EAAE,GAAG,0BAA0B,CAAC,GAAG,IAAI,CAAC;IACpF,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAE/C,OAAO,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE,CAAC;AAC9C,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,oBAAoB;IAClC,UAAU,CAAC,KAAK,EAAE,CAAC;AACrB,CAAC"}
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Backend SDK Types
3
+ * Configuration, request, and response types for internal service-to-service calls
4
+ */
5
+ export interface ServiceJwtConfig {
6
+ /**
7
+ * Private key for signing service tokens. Accepts two formats:
8
+ *
9
+ * - **Hex string (64 chars)** — Ed25519 only. 32-byte seed in hex encoding.
10
+ * Example: `INTERNAL_JWT_PRIVATE_KEY=06A70CB7...`
11
+ *
12
+ * - **Base64-encoded JWK** — All algorithms (EdDSA, ES256, RS256, PS256).
13
+ * Generate (Node.js): `subtle.generateKey(...)` → `exportKey('jwk', key)` → `JSON.stringify` → `btoa`
14
+ */
15
+ privateKey: string;
16
+ /**
17
+ * Signing algorithm. Must be in the Worker's SERVICE_JWT_ALLOWED_ALGORITHMS whitelist.
18
+ * @default 'EdDSA'
19
+ */
20
+ alg?: 'EdDSA' | 'ES256' | 'RS256' | 'PS256';
21
+ /** Service identity — becomes the `sub` claim (e.g. 'svc_billing') */
22
+ serviceId: string;
23
+ /** Service roles embedded in token (e.g. ['internal-service']) */
24
+ roles?: string[];
25
+ /** Audience claim — must match Worker's SERVICE_JWT_AUDIENCE @default 'auth-craft:internal' */
26
+ audience?: string;
27
+ /** Token expiry in minutes @default 10 */
28
+ expiresInMinutes?: number;
29
+ /** Issuer claim — must match Worker's SERVICE_JWT_ISSUER if set @default 'auth-craft' */
30
+ issuer?: string;
31
+ }
32
+ export interface InternalClientConfig {
33
+ /** Base URL of the auth service (e.g., 'https://auth.example.com') */
34
+ baseUrl: string;
35
+ /**
36
+ * Base path prefix (e.g., '/system' → /system/{serviceRoutePath}/*)
37
+ * @default ''
38
+ */
39
+ basePath?: string;
40
+ /**
41
+ * Path segment for service-to-service routes.
42
+ * Must match SERVICE_ROUTE_PREFIX configured on the Worker/Lambda.
43
+ * Can be changed to obscure the internal API surface.
44
+ *
45
+ * @default '/internal'
46
+ * @example '/svc' → requests go to {baseUrl}{basePath}/svc/*
47
+ */
48
+ serviceRoutePath?: string;
49
+ /** Service JWT signing configuration */
50
+ jwt: ServiceJwtConfig;
51
+ /** Custom fetch implementation (for testing or middleware) */
52
+ fetchImpl?: typeof fetch;
53
+ /** Request timeout in milliseconds @default 30000 */
54
+ timeout?: number;
55
+ /** Custom headers to include in all requests */
56
+ headers?: Record<string, string>;
57
+ /**
58
+ * Optional secret header for direct backend access.
59
+ * Useful when calling Lambda/Docker directly and the backend expects
60
+ * a shared secret header such as X-Gateway-Secret.
61
+ */
62
+ secretHeader?: {
63
+ /** Header value to send */
64
+ value: string;
65
+ /** Header name override @default 'X-Gateway-Secret' */
66
+ name?: string;
67
+ };
68
+ /**
69
+ * Optional logger hook for transport-level diagnostics.
70
+ * The SDK never logs by default; provide a logger if you want runtime visibility.
71
+ */
72
+ logger?: {
73
+ warn(message: string, context?: Record<string, unknown>): void;
74
+ };
75
+ }
76
+ export type { BootstrapTenantOwnerRequest, GetTenantProfileRequest, UpdateTenantProfileRequest, ListTenantMembersRequest, UpdateTenantMemberStatusRequest, UpdateTenantMemberPermissionRequest, RemoveTenantMemberRequest, AddMemberToTenantRequest, ListTenantInvitesRequest, InviteToTenantRequest, AcceptInviteRequest, DeclineInviteRequest, RevokeInviteRequest, CheckPendingInvitesRequest, ListUserTenantsRequest, ListAccountsRequest, GetAccountRequest, UpdateAccountProfileRequest, UpdateAccountStatusRequest, ResetAccountCredentialsRequest, RemoveAccountRequest, BootstrapTenantOwnerResponse, TenantProfileResponse, AddMemberToTenantResponse, InviteToTenantResponse, AcceptInviteResponse, CheckPendingInvitesResponse, TenantMemberResponse, ListTenantMembersResponse, UserTenantResponse, ListUserTenantsResponse, TenantInviteResponse, ListTenantInvitesResponse, AccountSummaryResponse, ListAccountsResponse, AccountDetailResponse, AccountPermContextRequest, InvitedByInfo, TenantProfileFields, TenantMemberProfileResponse, } from './contract-types';
77
+ /**
78
+ * Valid auth permission strings for operations.
79
+ * Use these when setting authPerms via the SDK.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * await client.updateTenantMemberPermission({
84
+ * tenantId: 'org-123',
85
+ * userId: 'user-abc',
86
+ * authPerms: [AUTH_PERM_STRINGS.INVITE_MEMBERS, AUTH_PERM_STRINGS.VIEW_MEMBERS],
87
+ * });
88
+ * ```
89
+ */
90
+ export declare const AUTH_PERM_STRINGS: {
91
+ readonly INVITE_MEMBERS: "tenant.member.invite";
92
+ readonly REMOVE_MEMBERS: "tenant.member.remove";
93
+ readonly VIEW_MEMBERS: "tenant.member.view";
94
+ readonly CHANGE_MEMBER_PERMISSION: "tenant.member.permission";
95
+ readonly UPDATE_MEMBER_PROFILE: "tenant.member.profile.update";
96
+ readonly UPDATE_MEMBER_STATUS: "tenant.member.status.update";
97
+ readonly VIEW_ACCOUNTS: "account.view";
98
+ readonly UPDATE_ACCOUNT_PROFILE: "account.profile.update";
99
+ readonly UPDATE_ACCOUNT_STATUS: "account.status.update";
100
+ readonly RESET_ACCOUNT_CREDENTIALS: "account.credentials.reset";
101
+ readonly REMOVE_ACCOUNTS: "account.remove";
102
+ };
103
+ /** Union type of all valid auth permission strings */
104
+ export type AuthPermString = (typeof AUTH_PERM_STRINGS)[keyof typeof AUTH_PERM_STRINGS];
105
+ /** Standard API response envelope from auth service */
106
+ export interface ApiResponseEnvelope<T = unknown> {
107
+ ok: boolean;
108
+ data?: T;
109
+ errors?: Array<{
110
+ code: string;
111
+ message: string;
112
+ field?: string;
113
+ }>;
114
+ meta?: Record<string, unknown>;
115
+ }
116
+ /**
117
+ * Extract the HTTP status code from a Result returned by the SDK.
118
+ *
119
+ * Every Result from InternalClient includes `meta.params.httpStatus`
120
+ * carrying the original HTTP status code from the auth service.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * const result = await client.getTenantProfile({ tenantId, userId });
125
+ * const status = getHttpStatus(result); // 200 | 404 | 403 | ...
126
+ *
127
+ * if (!result.ok && status === 404) {
128
+ * // handle not found
129
+ * }
130
+ * ```
131
+ */
132
+ export declare function getHttpStatus(result: {
133
+ meta?: {
134
+ params?: Record<string, unknown>;
135
+ };
136
+ }): number | undefined;
137
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;;;OAQG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,GAAG,CAAC,EAAE,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;IAC5C,sEAAsE;IACtE,SAAS,EAAE,MAAM,CAAC;IAClB,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,+FAA+F;IAC/F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yFAAyF;IACzF,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AuB,EACvB,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,mBAAmB,EACnB,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAM1B;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;CAcpB,CAAC;AAEX,sDAAsD;AACtD,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC;AAMxF,uDAAuD;AACvD,MAAM,WAAW,mBAAmB,CAAC,CAAC,GAAG,OAAO;IAC9C,EAAE,EAAE,OAAO,CAAC;IACZ,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,MAAM,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAClE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAMD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAA;CAAE,GAAG,MAAM,GAAG,SAAS,CAEzG"}
package/dist/types.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Backend SDK Types
3
+ * Configuration, request, and response types for internal service-to-service calls
4
+ */
5
+ // ============================================================
6
+ // Auth Permission String Constants
7
+ // ============================================================
8
+ /**
9
+ * Valid auth permission strings for operations.
10
+ * Use these when setting authPerms via the SDK.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * await client.updateTenantMemberPermission({
15
+ * tenantId: 'org-123',
16
+ * userId: 'user-abc',
17
+ * authPerms: [AUTH_PERM_STRINGS.INVITE_MEMBERS, AUTH_PERM_STRINGS.VIEW_MEMBERS],
18
+ * });
19
+ * ```
20
+ */
21
+ export const AUTH_PERM_STRINGS = {
22
+ // ─── Tenant Member Management ──────────────────────────────────
23
+ INVITE_MEMBERS: 'tenant.member.invite',
24
+ REMOVE_MEMBERS: 'tenant.member.remove',
25
+ VIEW_MEMBERS: 'tenant.member.view',
26
+ CHANGE_MEMBER_PERMISSION: 'tenant.member.permission',
27
+ UPDATE_MEMBER_PROFILE: 'tenant.member.profile.update',
28
+ UPDATE_MEMBER_STATUS: 'tenant.member.status.update',
29
+ // ─── Account Management ────────────────────────────────────────
30
+ VIEW_ACCOUNTS: 'account.view',
31
+ UPDATE_ACCOUNT_PROFILE: 'account.profile.update',
32
+ UPDATE_ACCOUNT_STATUS: 'account.status.update',
33
+ RESET_ACCOUNT_CREDENTIALS: 'account.credentials.reset',
34
+ REMOVE_ACCOUNTS: 'account.remove',
35
+ };
36
+ // ============================================================
37
+ // SDK Result Helpers
38
+ // ============================================================
39
+ /**
40
+ * Extract the HTTP status code from a Result returned by the SDK.
41
+ *
42
+ * Every Result from InternalClient includes `meta.params.httpStatus`
43
+ * carrying the original HTTP status code from the auth service.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const result = await client.getTenantProfile({ tenantId, userId });
48
+ * const status = getHttpStatus(result); // 200 | 404 | 403 | ...
49
+ *
50
+ * if (!result.ok && status === 404) {
51
+ * // handle not found
52
+ * }
53
+ * ```
54
+ */
55
+ export function getHttpStatus(result) {
56
+ return result.meta?.params?.httpStatus;
57
+ }
58
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA4IH,+DAA+D;AAC/D,mCAAmC;AACnC,+DAA+D;AAE/D;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,kEAAkE;IAClE,cAAc,EAAE,sBAAsB;IACtC,cAAc,EAAE,sBAAsB;IACtC,YAAY,EAAE,oBAAoB;IAClC,wBAAwB,EAAE,0BAA0B;IACpD,qBAAqB,EAAE,8BAA8B;IACrD,oBAAoB,EAAE,6BAA6B;IACnD,kEAAkE;IAClE,aAAa,EAAE,cAAc;IAC7B,sBAAsB,EAAE,wBAAwB;IAChD,qBAAqB,EAAE,uBAAuB;IAC9C,yBAAyB,EAAE,2BAA2B;IACtD,eAAe,EAAE,gBAAgB;CACzB,CAAC;AAiBX,+DAA+D;AAC/D,qBAAqB;AACrB,+DAA+D;AAE/D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,aAAa,CAAC,MAAuD;IACnF,OAAO,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,UAAgC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.test-d.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.test-d.d.ts","sourceRoot":"","sources":["../src/types.test-d.ts"],"names":[],"mappings":""}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Type-level guard — backend-sdk is pinned to @auth-craft/api-contract/internal.
3
+ *
4
+ * Closes the drift gap that name-only coverage misses: InternalClient methods
5
+ * forward `request` straight to HTTP, so they never read a body field by name —
6
+ * a renamed contract field would not break the SDK on its own. These checks make
7
+ * the break happen, in three independent ways:
8
+ *
9
+ * 1. COVERAGE — every internal endpoint must have an InternalClient method
10
+ * (add an endpoint, forget the method → compile error here).
11
+ * 2. NO EXTRAS — every request-taking method must map to an endpoint
12
+ * (stray method / typo'd name → compile error here).
13
+ * 3. SHAPE — each method's argument must be assignable from the body
14
+ * inferred from the contract. This is what catches a renamed
15
+ * field AND a hand-written `*Request` that drifted from the
16
+ * schema (the "do NOT re-add hand-written shapes" rule, now
17
+ * mechanically enforced).
18
+ *
19
+ * Plus a few @ts-expect-error samples proving a wrong field name is rejected.
20
+ *
21
+ * Type-checked by `tsc --noEmit` (tsconfig does not exclude *.test-d.ts), never
22
+ * executed. No runtime cost, no bundle impact.
23
+ */
24
+ import { internalContract } from '@auth-craft/api-contract/internal';
25
+ void _coverage;
26
+ void _noExtras;
27
+ void _shape;
28
+ const accountCtx = { actorUserId: 'u', systemTenantId: 's' };
29
+ // ✓ correct fields per the contract
30
+ void sdk.getAccount({ ...accountCtx, userId: 'x' });
31
+ void sdk.updateAccountStatus({ ...accountCtx, userId: 'x', status: 'active' });
32
+ // ✗ renamed/unknown field → MUST error
33
+ // @ts-expect-error 'userId' is the contract field; 'userIdX' is not
34
+ void sdk.getAccount({ ...accountCtx, userIdX: 'x' });
35
+ // ✗ invalid enum value (status is a picklist, not a free string) → MUST error
36
+ // @ts-expect-error 'frozen' is not a valid UserStatus
37
+ void sdk.updateAccountStatus({ ...accountCtx, userId: 'x', status: 'frozen' });
38
+ //# sourceMappingURL=types.test-d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.test-d.js","sourceRoot":"","sources":["../src/types.test-d.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAuBrE,KAAM,SAAiD,CAAC;AASxD,KAAM,SAA0B,CAAC;AAgBjC,KAAM,MAAsC,CAAC;AAK7C,MAAM,UAAU,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC;AAE7D,oCAAoC;AACpC,KAAK,GAAG,CAAC,UAAU,CAAC,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;AACpD,KAAK,GAAG,CAAC,mBAAmB,CAAC,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;AAE/E,uCAAuC;AACvC,oEAAoE;AACpE,KAAK,GAAG,CAAC,UAAU,CAAC,EAAE,GAAG,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;AAErD,8EAA8E;AAC9E,sDAAsD;AACtD,KAAK,GAAG,CAAC,mBAAmB,CAAC,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,35 +1,37 @@
1
1
  {
2
2
  "name": "@auth-craft/backend-sdk",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "description": "Type-safe internal service SDK for Auth-Craft service-to-service calls",
5
5
  "type": "module",
6
- "main": "./dist/index.cjs",
6
+ "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "types": "./dist/index.d.ts",
9
+ "sideEffects": false,
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "dependencies": {
14
+ "ts-micro-result": "^3.3.0",
15
+ "valibot": "^1.4.1",
16
+ "@auth-craft/api-contract": "^0.1.2"
17
+ },
18
+ "devDependencies": {
19
+ "typescript": "^6.0.3",
20
+ "vitest": "^4.1.8",
21
+ "@auth-craft/tsconfig": "0.1.0"
22
+ },
9
23
  "exports": {
10
24
  ".": {
11
25
  "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
26
+ "import": "./dist/index.js"
14
27
  }
15
28
  },
16
- "sideEffects": false,
17
29
  "scripts": {
18
- "build": "tsup",
30
+ "build": "tsc",
19
31
  "type-check": "tsc --noEmit",
20
- "dev": "tsup --watch",
32
+ "dev": "tsc --watch",
21
33
  "test": "vitest run",
22
- "test:watch": "vitest"
23
- },
24
- "files": [
25
- "dist"
26
- ],
27
- "dependencies": {
28
- "ts-micro-result": "^3.3.0"
29
- },
30
- "devDependencies": {
31
- "@auth-craft/tsup-config": "workspace:*",
32
- "typescript": "^5.9.3",
33
- "vitest": "^4.0.18"
34
+ "test:watch": "vitest",
35
+ "clean": "rm -rf dist"
34
36
  }
35
- }
37
+ }