@crittora/sdk-js 2.0.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +348 -0
  3. package/dist/auth/bearer.d.ts +2 -0
  4. package/dist/auth/bearer.js +11 -0
  5. package/dist/auth/bearer.js.map +1 -0
  6. package/dist/auth/cognito.d.ts +14 -0
  7. package/dist/auth/cognito.js +53 -0
  8. package/dist/auth/cognito.js.map +1 -0
  9. package/dist/auth/types.d.ts +9 -0
  10. package/dist/auth/types.js +3 -0
  11. package/dist/auth/types.js.map +1 -0
  12. package/dist/client.d.ts +18 -0
  13. package/dist/client.js +57 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/crittora.d.ts +18 -0
  16. package/dist/crittora.js +79 -0
  17. package/dist/crittora.js.map +1 -0
  18. package/dist/errors/authenticationError.d.ts +1 -0
  19. package/dist/errors/authenticationError.js +6 -0
  20. package/dist/errors/authenticationError.js.map +1 -0
  21. package/dist/errors/crittoraErrors.d.ts +1 -0
  22. package/dist/errors/crittoraErrors.js +12 -0
  23. package/dist/errors/crittoraErrors.js.map +1 -0
  24. package/dist/errors.d.ts +33 -0
  25. package/dist/errors.js +59 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/index.d.ts +7 -0
  28. package/dist/index.js +24 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/resources/crypto.d.ts +14 -0
  31. package/dist/resources/crypto.js +102 -0
  32. package/dist/resources/crypto.js.map +1 -0
  33. package/dist/transport/httpTransport.d.ts +16 -0
  34. package/dist/transport/httpTransport.js +158 -0
  35. package/dist/transport/httpTransport.js.map +1 -0
  36. package/dist/types.d.ts +101 -0
  37. package/dist/types.js +3 -0
  38. package/dist/types.js.map +1 -0
  39. package/docs/API.md +225 -0
  40. package/docs/ARCHITECTURE.md +83 -0
  41. package/docs/MIGRATION.md +187 -0
  42. package/package.json +82 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package will be documented in this file.
4
+
5
+ ## 2.0.0 - 2026-03-08
6
+
7
+ This release introduces the new primary SDK architecture for `@crittora/sdk-js`.
8
+
9
+ ### Added
10
+
11
+ - Added `CrittoraClient` as the new primary instance-based SDK client.
12
+ - Added pluggable auth providers, including `bearerToken(...)` and `cognitoAuthProvider(...)`.
13
+ - Added a transport layer with timeout handling, retry support, and response normalization.
14
+ - Added a structured SDK error hierarchy for validation, auth, request, rate limit, encrypt, and decrypt failures.
15
+ - Added principal-level documentation in `README.md`, `docs/API.md`, `docs/MIGRATION.md`, and `docs/ARCHITECTURE.md`.
16
+
17
+ ### Changed
18
+
19
+ - Changed the primary public API from positional method arguments to typed object-based inputs.
20
+ - Changed public JavaScript and TypeScript models to camelCase while keeping wire-format translation internal.
21
+ - Changed runtime support to Node.js 18+.
22
+ - Changed package verification so publish flows run full build and test verification.
23
+
24
+ ### Deprecated
25
+
26
+ - Deprecated the legacy `Crittora` class as the preferred integration surface. It remains available as a compatibility shim for staged migrations.
27
+
28
+ ### Removed
29
+
30
+ - Removed singleton-based internal services and hidden package-managed configuration loading.
31
+ - Removed the package dependency on `dotenv`.
32
+
33
+ ### Migration notes
34
+
35
+ - Existing integrations can continue using `Crittora` temporarily.
36
+ - New integrations should use `CrittoraClient`.
37
+ - See `docs/MIGRATION.md` for the v1 to v2 migration path.
package/README.md ADDED
@@ -0,0 +1,348 @@
1
+ # Crittora JavaScript SDK
2
+
3
+ The Crittora JavaScript SDK provides a typed client for encryption, decryption, and decrypt-verify operations against the Crittora API.
4
+
5
+ This package now exposes a v2-style, instance-based client designed for predictable integration in production systems:
6
+
7
+ - explicit client construction
8
+ - explicit credentials and auth wiring
9
+ - transport-level timeout and retry controls
10
+ - typed request and response objects
11
+ - stable SDK error classes
12
+
13
+ The legacy `Crittora` class is still exported as a compatibility shim for existing consumers, but new integrations should use `CrittoraClient`.
14
+
15
+ ## Table of Contents
16
+
17
+ - [Runtime Support](#runtime-support)
18
+ - [Installation](#installation)
19
+ - [Design Principles](#design-principles)
20
+ - [Quick Start](#quick-start)
21
+ - [Authentication](#authentication)
22
+ - [Client Configuration](#client-configuration)
23
+ - [Operations](#operations)
24
+ - [Errors](#errors)
25
+ - [Migration from v1](#migration-from-v1)
26
+ - [Additional Documentation](#additional-documentation)
27
+
28
+ ## Runtime Support
29
+
30
+ - Node.js 18 or later
31
+ - Any runtime that provides a compatible `fetch` implementation, or where one is passed explicitly via the client options
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ npm install @crittora/sdk-js
37
+ ```
38
+
39
+ ## Design Principles
40
+
41
+ The v2 client is built around a few constraints that matter for SDK consumers:
42
+
43
+ - No hidden process-global configuration is required for the primary API.
44
+ - Client instances are isolated, so one process can talk to multiple environments safely.
45
+ - Public JavaScript and TypeScript types use camelCase, while wire-format translation stays internal.
46
+ - Auth is composable rather than hard-coded into every request path.
47
+ - Errors preserve transport and backend context so callers can make policy decisions.
48
+
49
+ ## Quick Start
50
+
51
+ ### Bearer token auth
52
+
53
+ ```ts
54
+ import { CrittoraClient } from "@crittora/sdk-js";
55
+
56
+ const client = new CrittoraClient({
57
+ baseUrl: "https://api.crittoraapis.com",
58
+ credentials: {
59
+ apiKey: process.env.CRITTORA_API_KEY!,
60
+ accessKey: process.env.CRITTORA_ACCESS_KEY!,
61
+ secretKey: process.env.CRITTORA_SECRET_KEY!,
62
+ },
63
+ auth: {
64
+ type: "bearer",
65
+ token: process.env.CRITTORA_ID_TOKEN!,
66
+ },
67
+ timeoutMs: 10_000,
68
+ retry: {
69
+ maxAttempts: 2,
70
+ },
71
+ });
72
+
73
+ const result = await client.encrypt({
74
+ data: "sensitive data",
75
+ permissions: [
76
+ {
77
+ partnerId: "partner-123",
78
+ actions: ["read"],
79
+ },
80
+ ],
81
+ });
82
+
83
+ console.log(result.encryptedData);
84
+ ```
85
+
86
+ ### Scoped auth
87
+
88
+ If the same client configuration is reused across identities, create a base client and scope auth per request flow:
89
+
90
+ ```ts
91
+ import { CrittoraClient } from "@crittora/sdk-js";
92
+
93
+ const baseClient = new CrittoraClient({
94
+ credentials: {
95
+ apiKey: process.env.CRITTORA_API_KEY!,
96
+ },
97
+ });
98
+
99
+ const userClient = baseClient.withAuth({
100
+ type: "bearer",
101
+ token: userIdToken,
102
+ });
103
+
104
+ const decrypted = await userClient.decrypt({
105
+ encryptedData,
106
+ });
107
+ ```
108
+
109
+ ## Authentication
110
+
111
+ The SDK supports two primary auth patterns:
112
+
113
+ ### 1. Static bearer token
114
+
115
+ Use this when your application already manages a token lifecycle:
116
+
117
+ ```ts
118
+ const client = new CrittoraClient({
119
+ credentials: { apiKey: "..." },
120
+ auth: {
121
+ type: "bearer",
122
+ token: idToken,
123
+ },
124
+ });
125
+ ```
126
+
127
+ ### 2. Cognito auth provider
128
+
129
+ Use the built-in Cognito provider when the SDK should perform login and hold the returned tokens:
130
+
131
+ ```ts
132
+ import { CrittoraClient, cognitoAuthProvider } from "@crittora/sdk-js";
133
+
134
+ const auth = cognitoAuthProvider({
135
+ userPoolId: "us-east-1_Tmljk4Uiw",
136
+ clientId: "5cvaao4qgphfp38g433vi5e82u",
137
+ });
138
+
139
+ await auth.login({
140
+ username: process.env.CRITTORA_USERNAME!,
141
+ password: process.env.CRITTORA_PASSWORD!,
142
+ });
143
+
144
+ const client = new CrittoraClient({
145
+ credentials: {
146
+ apiKey: process.env.CRITTORA_API_KEY!,
147
+ },
148
+ auth,
149
+ });
150
+ ```
151
+
152
+ ### Security note
153
+
154
+ If `accessKey` and `secretKey` represent privileged backend credentials, do not expose them in untrusted browser code. In that model, use this SDK server-side and front it with your own backend boundary.
155
+
156
+ ## Client Configuration
157
+
158
+ `CrittoraClient` accepts the following options:
159
+
160
+ ```ts
161
+ type CrittoraClientOptions = {
162
+ baseUrl?: string;
163
+ credentials?: {
164
+ apiKey: string;
165
+ accessKey?: string;
166
+ secretKey?: string;
167
+ };
168
+ auth?: BearerAuthConfig | AuthProvider;
169
+ fetch?: typeof globalThis.fetch;
170
+ timeoutMs?: number;
171
+ retry?: {
172
+ maxAttempts?: number;
173
+ backoffMs?: number;
174
+ retryOn?: number[];
175
+ };
176
+ headers?: Record<string, string>;
177
+ userAgent?: string;
178
+ };
179
+ ```
180
+
181
+ Operational guidance:
182
+
183
+ - Set `baseUrl` explicitly in non-production environments.
184
+ - Use `fetch` injection in runtimes where global `fetch` is absent or wrapped.
185
+ - Keep retry counts conservative unless the backend contract explicitly supports aggressive retries.
186
+ - Prefer a custom `userAgent` in services where request attribution matters.
187
+
188
+ ## Operations
189
+
190
+ ### Encrypt
191
+
192
+ ```ts
193
+ const result = await client.encrypt({
194
+ data: "hello",
195
+ permissions: [
196
+ {
197
+ partnerId: "partner-123",
198
+ actions: ["read", "write"],
199
+ },
200
+ ],
201
+ });
202
+
203
+ console.log(result.encryptedData);
204
+ console.log(result.transactionId);
205
+ ```
206
+
207
+ ### Decrypt
208
+
209
+ ```ts
210
+ const result = await client.decrypt({
211
+ encryptedData,
212
+ });
213
+
214
+ console.log(result.decryptedData);
215
+ ```
216
+
217
+ ### Decrypt and verify
218
+
219
+ ```ts
220
+ const result = await client.decryptVerify({
221
+ encryptedData,
222
+ });
223
+
224
+ console.log(result.decryptedData);
225
+ console.log(result.isValidSignature);
226
+ ```
227
+
228
+ Public request and response types:
229
+
230
+ ```ts
231
+ type Permission = {
232
+ partnerId: string;
233
+ actions: string[];
234
+ };
235
+
236
+ type EncryptInput = {
237
+ data: string;
238
+ permissions?: Permission[];
239
+ };
240
+
241
+ type EncryptResult = {
242
+ encryptedData: string;
243
+ transactionId?: string;
244
+ };
245
+
246
+ type DecryptInput = {
247
+ encryptedData: string;
248
+ permissions?: Permission[];
249
+ };
250
+
251
+ type DecryptResult = {
252
+ decryptedData: string;
253
+ transactionId?: string;
254
+ };
255
+
256
+ type DecryptVerifyResult = {
257
+ decryptedData: string;
258
+ isValidSignature: boolean;
259
+ transactionId?: string;
260
+ };
261
+ ```
262
+
263
+ ## Errors
264
+
265
+ The SDK exports a stable error hierarchy:
266
+
267
+ - `CrittoraError`
268
+ - `ValidationError`
269
+ - `AuthError`
270
+ - `RequestError`
271
+ - `RateLimitError`
272
+ - `EncryptError`
273
+ - `DecryptError`
274
+
275
+ All errors may carry the following diagnostic fields:
276
+
277
+ - `code`
278
+ - `status`
279
+ - `requestId`
280
+ - `details`
281
+ - `cause`
282
+
283
+ Example:
284
+
285
+ ```ts
286
+ import {
287
+ CrittoraClient,
288
+ DecryptError,
289
+ RateLimitError,
290
+ RequestError,
291
+ } from "@crittora/sdk-js";
292
+
293
+ try {
294
+ await client.decrypt({ encryptedData });
295
+ } catch (error) {
296
+ if (error instanceof RateLimitError) {
297
+ // retry later or trigger backpressure
298
+ } else if (error instanceof DecryptError) {
299
+ // operation-specific failure
300
+ } else if (error instanceof RequestError) {
301
+ // non-2xx or transport-level issue
302
+ } else {
303
+ throw error;
304
+ }
305
+ }
306
+ ```
307
+
308
+ ## Migration from v1
309
+
310
+ The package still exports the legacy `Crittora` class:
311
+
312
+ ```ts
313
+ import { Crittora } from "@crittora/sdk-js";
314
+ ```
315
+
316
+ That class exists to reduce migration friction, but it should be treated as transitional.
317
+
318
+ Key differences in v2:
319
+
320
+ - `new CrittoraClient({...})` replaces implicit singleton construction
321
+ - object-shaped inputs replace positional method arguments
322
+ - camelCase public types replace wire-format snake_case
323
+ - explicit auth providers replace hard-coded request token arguments
324
+ - stable typed errors replace broad wrapping
325
+
326
+ Simple mapping:
327
+
328
+ ```ts
329
+ // v1
330
+ await sdk.encrypt(idToken, data, ["read"]);
331
+
332
+ // v2
333
+ await client.withAuth({ type: "bearer", token: idToken }).encrypt({
334
+ data,
335
+ permissions: [
336
+ {
337
+ partnerId: "default",
338
+ actions: ["read"],
339
+ },
340
+ ],
341
+ });
342
+ ```
343
+
344
+ ## Additional Documentation
345
+
346
+ - [API Reference](./docs/API.md)
347
+ - [Migration Guide](./docs/MIGRATION.md)
348
+ - [Architecture Notes](./docs/ARCHITECTURE.md)
@@ -0,0 +1,2 @@
1
+ import { AuthProvider } from "./types";
2
+ export declare function bearerToken(token: string): AuthProvider;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bearerToken = bearerToken;
4
+ function bearerToken(token) {
5
+ return {
6
+ async getAuthorizationHeader() {
7
+ return `Bearer ${token}`;
8
+ },
9
+ };
10
+ }
11
+ //# sourceMappingURL=bearer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bearer.js","sourceRoot":"","sources":["../../src/auth/bearer.ts"],"names":[],"mappings":";;AAEA,kCAMC;AAND,SAAgB,WAAW,CAAC,KAAa;IACvC,OAAO;QACL,KAAK,CAAC,sBAAsB;YAC1B,OAAO,UAAU,KAAK,EAAE,CAAC;QAC3B,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { AuthProvider } from "./types";
2
+ import { AuthTokens, CognitoAuthConfig } from "../types";
3
+ export declare class CognitoAuthProvider implements AuthProvider {
4
+ private readonly config;
5
+ private readonly userPool;
6
+ private tokens?;
7
+ constructor(config: CognitoAuthConfig);
8
+ getAuthorizationHeader(): Promise<string | undefined>;
9
+ login(credentials?: {
10
+ username: string;
11
+ password: string;
12
+ }): Promise<AuthTokens>;
13
+ }
14
+ export declare function cognitoAuthProvider(config: CognitoAuthConfig): CognitoAuthProvider;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CognitoAuthProvider = void 0;
4
+ exports.cognitoAuthProvider = cognitoAuthProvider;
5
+ const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
6
+ const errors_1 = require("../errors");
7
+ class CognitoAuthProvider {
8
+ constructor(config) {
9
+ this.config = config;
10
+ this.userPool = new amazon_cognito_identity_js_1.CognitoUserPool({
11
+ UserPoolId: config.userPoolId,
12
+ ClientId: config.clientId,
13
+ });
14
+ }
15
+ async getAuthorizationHeader() {
16
+ return this.tokens?.idToken ? `Bearer ${this.tokens.idToken}` : undefined;
17
+ }
18
+ async login(credentials) {
19
+ const username = credentials?.username ?? this.config.username;
20
+ const password = credentials?.password ?? this.config.password;
21
+ if (!username || !password) {
22
+ throw new errors_1.ValidationError("Username and password are required for Cognito login.");
23
+ }
24
+ const authDetails = new amazon_cognito_identity_js_1.AuthenticationDetails({
25
+ Username: username,
26
+ Password: password,
27
+ });
28
+ const cognitoUser = new amazon_cognito_identity_js_1.CognitoUser({
29
+ Username: username,
30
+ Pool: this.userPool,
31
+ });
32
+ return new Promise((resolve, reject) => {
33
+ cognitoUser.authenticateUser(authDetails, {
34
+ onSuccess: (result) => {
35
+ this.tokens = {
36
+ idToken: result.getIdToken().getJwtToken(),
37
+ accessToken: result.getAccessToken().getJwtToken(),
38
+ refreshToken: result.getRefreshToken().getToken(),
39
+ };
40
+ resolve(this.tokens);
41
+ },
42
+ onFailure: (error) => {
43
+ reject(new errors_1.AuthError(error.message, undefined, error));
44
+ },
45
+ });
46
+ });
47
+ }
48
+ }
49
+ exports.CognitoAuthProvider = CognitoAuthProvider;
50
+ function cognitoAuthProvider(config) {
51
+ return new CognitoAuthProvider(config);
52
+ }
53
+ //# sourceMappingURL=cognito.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cognito.js","sourceRoot":"","sources":["../../src/auth/cognito.ts"],"names":[],"mappings":";;;AAiEA,kDAIC;AArED,2EAIoC;AACpC,sCAAuD;AAIvD,MAAa,mBAAmB;IAI9B,YAA6B,MAAyB;QAAzB,WAAM,GAAN,MAAM,CAAmB;QACpD,IAAI,CAAC,QAAQ,GAAG,IAAI,4CAAe,CAAC;YAClC,UAAU,EAAE,MAAM,CAAC,UAAU;YAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,sBAAsB;QAC1B,OAAO,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAA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AAC,CAAC,CAAC;gBACzD,CAAC;aACF,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtDD,kDAsDC;AAED,SAAgB,mBAAmB,CACjC,MAAyB;IAEzB,OAAO,IAAI,mBAAmB,CAAC,MAAM,CAAC,CAAC;AACzC,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { AuthTokens } from "../types";
2
+ export interface AuthProvider {
3
+ getAuthorizationHeader(): Promise<string | undefined>;
4
+ login?(credentials: {
5
+ username: string;
6
+ password: string;
7
+ }): Promise<AuthTokens>;
8
+ refresh?(): Promise<void>;
9
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
1
+ import { AuthProvider } from "./auth/types";
2
+ import { CrittoraClientOptions, DecryptInput, DecryptResult, DecryptVerifyInput, DecryptVerifyResult, EncryptInput, EncryptResult } from "./types";
3
+ export declare class CrittoraClient {
4
+ private readonly options;
5
+ private readonly transport;
6
+ private readonly authProvider?;
7
+ private readonly cryptoResource;
8
+ constructor(options?: CrittoraClientOptions);
9
+ get auth(): AuthProvider | undefined;
10
+ withAuth(auth: AuthProvider | {
11
+ type: "bearer";
12
+ token: string;
13
+ }): CrittoraClient;
14
+ encrypt(input: EncryptInput): Promise<EncryptResult>;
15
+ decrypt(input: DecryptInput): Promise<DecryptResult>;
16
+ decryptVerify(input: DecryptVerifyInput): Promise<DecryptVerifyResult>;
17
+ private resolveAuthProvider;
18
+ }
package/dist/client.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CrittoraClient = void 0;
4
+ const bearer_1 = require("./auth/bearer");
5
+ const crypto_1 = require("./resources/crypto");
6
+ const httpTransport_1 = require("./transport/httpTransport");
7
+ const DEFAULT_BASE_URL = "https://api.crittoraapis.com";
8
+ const DEFAULT_TIMEOUT_MS = 10000;
9
+ class CrittoraClient {
10
+ constructor(options = {}) {
11
+ this.options = options;
12
+ this.authProvider = this.resolveAuthProvider(options.auth);
13
+ this.transport = new httpTransport_1.HttpTransport({
14
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
15
+ credentials: options.credentials,
16
+ headers: options.headers,
17
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
18
+ userAgent: options.userAgent,
19
+ }, {
20
+ fetch: options.fetch,
21
+ retry: options.retry,
22
+ });
23
+ this.cryptoResource = new crypto_1.CryptoResource(this.transport, this.authProvider);
24
+ }
25
+ get auth() {
26
+ return this.authProvider;
27
+ }
28
+ withAuth(auth) {
29
+ return new CrittoraClient({
30
+ ...this.options,
31
+ auth,
32
+ });
33
+ }
34
+ async encrypt(input) {
35
+ return this.cryptoResource.encrypt(input);
36
+ }
37
+ async decrypt(input) {
38
+ return this.cryptoResource.decrypt(input);
39
+ }
40
+ async decryptVerify(input) {
41
+ return this.cryptoResource.decryptVerify(input);
42
+ }
43
+ resolveAuthProvider(auth) {
44
+ if (!auth) {
45
+ return undefined;
46
+ }
47
+ if ("type" in auth && auth.type === "bearer") {
48
+ return (0, bearer_1.bearerToken)(auth.token);
49
+ }
50
+ if ("getAuthorizationHeader" in auth) {
51
+ return auth;
52
+ }
53
+ return undefined;
54
+ }
55
+ }
56
+ exports.CrittoraClient = CrittoraClient;
57
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,0CAA4C;AAW5C,+CAAoD;AACpD,6DAA0D;AAE1D,MAAM,gBAAgB,GAAG,8BAA8B,CAAC;AACxD,MAAM,kBAAkB,GAAG,KAAM,CAAC;AAElC,MAAa,cAAc;IAKzB,YAA6B,UAAiC,EAAE;QAAnC,YAAO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MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7C,OAAO,IAAA,oBAAW,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC;QAED,IAAI,wBAAwB,IAAI,IAAI,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAnED,wCAmEC"}
@@ -0,0 +1,18 @@
1
+ import { CognitoAuthConfig, CrittoraClientOptions, LegacyAuthResponse } from "./types";
2
+ export interface LegacyCrittoraOptions extends CrittoraClientOptions {
3
+ cognito?: CognitoAuthConfig;
4
+ }
5
+ export declare class Crittora {
6
+ private readonly options;
7
+ private readonly client;
8
+ private readonly cognito;
9
+ constructor(options?: LegacyCrittoraOptions);
10
+ authenticate(username: string, password: string): Promise<LegacyAuthResponse>;
11
+ encrypt(idToken: string, data: string, permissions?: string[]): Promise<string>;
12
+ decrypt(idToken: string, encryptedData: string, permissions?: string[]): Promise<string>;
13
+ decryptVerify(idToken: string, encryptedData: string, permissions?: string[]): Promise<{
14
+ decrypted_data: string;
15
+ is_valid_signature: boolean;
16
+ }>;
17
+ private toLegacyPermissions;
18
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Crittora = void 0;
4
+ const cognito_1 = require("./auth/cognito");
5
+ const client_1 = require("./client");
6
+ class Crittora {
7
+ constructor(options = {}) {
8
+ this.options = options;
9
+ this.cognito = (0, cognito_1.cognitoAuthProvider)({
10
+ userPoolId: options.cognito?.userPoolId ?? "us-east-1_Tmljk4Uiw",
11
+ clientId: options.cognito?.clientId ?? "5cvaao4qgphfp38g433vi5e82u",
12
+ username: options.cognito?.username,
13
+ password: options.cognito?.password,
14
+ });
15
+ this.client = new client_1.CrittoraClient({
16
+ ...options,
17
+ baseUrl: options.baseUrl ?? "https://api.crittoraapis.com",
18
+ credentials: options.credentials ??
19
+ (process.env.API_KEY
20
+ ? {
21
+ apiKey: process.env.API_KEY,
22
+ accessKey: process.env.ACCESS_KEY,
23
+ secretKey: process.env.SECRET_KEY,
24
+ }
25
+ : undefined),
26
+ });
27
+ }
28
+ async authenticate(username, password) {
29
+ const tokens = await this.cognito.login({ username, password });
30
+ return {
31
+ IdToken: tokens.idToken,
32
+ AccessToken: tokens.accessToken,
33
+ RefreshToken: tokens.refreshToken,
34
+ };
35
+ }
36
+ async encrypt(idToken, data, permissions) {
37
+ const result = await this.client
38
+ .withAuth({ type: "bearer", token: idToken })
39
+ .encrypt({
40
+ data,
41
+ permissions: this.toLegacyPermissions(permissions),
42
+ });
43
+ return result.encryptedData;
44
+ }
45
+ async decrypt(idToken, encryptedData, permissions) {
46
+ const result = await this.client
47
+ .withAuth({ type: "bearer", token: idToken })
48
+ .decrypt({
49
+ encryptedData,
50
+ permissions: this.toLegacyPermissions(permissions),
51
+ });
52
+ return result.decryptedData;
53
+ }
54
+ async decryptVerify(idToken, encryptedData, permissions) {
55
+ const result = await this.client
56
+ .withAuth({ type: "bearer", token: idToken })
57
+ .decryptVerify({
58
+ encryptedData,
59
+ permissions: this.toLegacyPermissions(permissions),
60
+ });
61
+ return {
62
+ decrypted_data: result.decryptedData,
63
+ is_valid_signature: result.isValidSignature,
64
+ };
65
+ }
66
+ toLegacyPermissions(permissions) {
67
+ if (!permissions?.length) {
68
+ return undefined;
69
+ }
70
+ return [
71
+ {
72
+ partnerId: "default",
73
+ actions: permissions,
74
+ },
75
+ ];
76
+ }
77
+ }
78
+ exports.Crittora = Crittora;
79
+ //# sourceMappingURL=crittora.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crittora.js","sourceRoot":"","sources":["../src/crittora.ts"],"names":[],"mappings":";;;AAAA,4CAAqD;AACrD,qCAA0C;AAY1C,MAAa,QAAQ;IAInB,YAA6B,UAAiC,EAAE;QAAnC,YAAO,GAAP,OAAO,CAA4B;QAC9D,IAAI,CAAC,OAAO,GAAG,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