@mastra/deployer-cloudflare 0.0.1-alpha.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.
@@ -0,0 +1,230 @@
1
+ // secrets-manager.test.ts
2
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
3
+
4
+ import { CloudflareSecretsManager } from './index.js';
5
+
6
+ const mockFetch = vi.fn();
7
+ global.fetch = mockFetch;
8
+
9
+ describe('CloudflareSecretsManager', () => {
10
+ let secretsManager: CloudflareSecretsManager;
11
+ const mockAccountId = 'test-account-id';
12
+ const mockApiToken = 'test-api-token';
13
+ const mockWorkerId = 'test-worker';
14
+
15
+ beforeEach(() => {
16
+ secretsManager = new CloudflareSecretsManager({
17
+ accountId: mockAccountId,
18
+ apiToken: mockApiToken,
19
+ });
20
+ vi.resetAllMocks();
21
+ });
22
+
23
+ describe('createSecret', () => {
24
+ it('should successfully create a secret', async () => {
25
+ const mockResponse = {
26
+ success: true,
27
+ result: { name: 'TEST_SECRET_123', type: 'secret_text' },
28
+ };
29
+
30
+ mockFetch.mockReturnValueOnce(
31
+ Promise.resolve({
32
+ json: () => Promise.resolve(mockResponse),
33
+ } as Response),
34
+ );
35
+
36
+ const result = await secretsManager.createSecret({
37
+ workerId: mockWorkerId,
38
+ secretName: 'TEST_SECRET_123',
39
+ secretValue: 'test-value',
40
+ });
41
+
42
+ expect(mockFetch).toHaveBeenCalledWith(
43
+ `https://api.cloudflare.com/client/v4/accounts/${mockAccountId}/workers/scripts/${mockWorkerId}/secrets`,
44
+ {
45
+ method: 'PUT',
46
+ headers: {
47
+ Authorization: `Bearer ${mockApiToken}`,
48
+ 'Content-Type': 'application/json',
49
+ },
50
+ body: JSON.stringify({
51
+ name: 'TEST_SECRET_123',
52
+ text: 'test-value',
53
+ }),
54
+ },
55
+ );
56
+
57
+ expect(result).toEqual(mockResponse.result);
58
+ });
59
+
60
+ it('should handle API errors for invalid secret names', async () => {
61
+ const mockError = {
62
+ success: false,
63
+ errors: [{ message: 'Invalid secret name' }],
64
+ };
65
+
66
+ mockFetch.mockReturnValueOnce(
67
+ Promise.resolve({
68
+ json: () => Promise.resolve(mockError),
69
+ } as Response),
70
+ );
71
+
72
+ await expect(
73
+ secretsManager.createSecret({
74
+ workerId: mockWorkerId,
75
+ secretName: 'invalid-name!', // Invalid secret name with special character
76
+ secretValue: 'test-value',
77
+ }),
78
+ ).rejects.toThrowError('Invalid secret name');
79
+ });
80
+
81
+ it('should handle network errors', async () => {
82
+ mockFetch.mockRejectedValueOnce(new Error('Network error'));
83
+
84
+ await expect(
85
+ secretsManager.createSecret({
86
+ workerId: mockWorkerId,
87
+ secretName: 'VALID_SECRET_NAME',
88
+ secretValue: 'test-value',
89
+ }),
90
+ ).rejects.toThrowError('Network error');
91
+ });
92
+ });
93
+
94
+ describe('createProjectSecrets', () => {
95
+ it('should create project-specific secrets', async () => {
96
+ const mockResponse = {
97
+ success: true,
98
+ result: { name: 'PROJECT_ABC123', type: 'secret_text' },
99
+ };
100
+
101
+ mockFetch.mockReturnValueOnce(
102
+ Promise.resolve({
103
+ json: () => Promise.resolve(mockResponse),
104
+ } as Response),
105
+ );
106
+
107
+ const envVars = {
108
+ API_KEY: 'test_key',
109
+ DATABASE_URL: 'test_url',
110
+ };
111
+
112
+ const result = await secretsManager.createProjectSecrets({
113
+ workerId: mockWorkerId,
114
+ customerId: 'ABC123',
115
+ envVars,
116
+ });
117
+
118
+ expect(mockFetch).toHaveBeenCalledWith(
119
+ expect.any(String),
120
+ expect.objectContaining({
121
+ method: 'PUT',
122
+ body: JSON.stringify({
123
+ name: 'PROJECT_ABC123',
124
+ text: JSON.stringify(envVars),
125
+ }),
126
+ }),
127
+ );
128
+
129
+ expect(result).toEqual(mockResponse.result);
130
+ });
131
+ });
132
+
133
+ describe('deleteSecret', () => {
134
+ it('should successfully delete a secret', async () => {
135
+ const mockResponse = {
136
+ success: true,
137
+ result: { id: 'deleted-secret-id' },
138
+ };
139
+
140
+ mockFetch.mockReturnValueOnce(
141
+ Promise.resolve({
142
+ json: () => Promise.resolve(mockResponse),
143
+ } as Response),
144
+ );
145
+
146
+ const result = await secretsManager.deleteSecret({
147
+ workerId: mockWorkerId,
148
+ secretName: 'TEST_SECRET_123',
149
+ });
150
+
151
+ expect(mockFetch).toHaveBeenCalledWith(
152
+ `https://api.cloudflare.com/client/v4/accounts/${mockAccountId}/workers/scripts/${mockWorkerId}/secrets/TEST_SECRET_123`,
153
+ {
154
+ method: 'DELETE',
155
+ headers: {
156
+ Authorization: `Bearer ${mockApiToken}`,
157
+ },
158
+ },
159
+ );
160
+
161
+ expect(result).toEqual(mockResponse.result);
162
+ });
163
+
164
+ it('should handle deletion errors', async () => {
165
+ const mockError = {
166
+ success: false,
167
+ errors: [{ message: 'Secret not found' }],
168
+ };
169
+
170
+ mockFetch.mockReturnValueOnce(
171
+ Promise.resolve({
172
+ json: () => Promise.resolve(mockError),
173
+ } as Response),
174
+ );
175
+
176
+ await expect(
177
+ secretsManager.deleteSecret({
178
+ workerId: mockWorkerId,
179
+ secretName: 'NONEXISTENT_SECRET',
180
+ }),
181
+ ).rejects.toThrowError('Secret not found');
182
+ });
183
+ });
184
+
185
+ describe('listSecrets', () => {
186
+ it('should successfully list all secrets', async () => {
187
+ const mockResponse = {
188
+ success: true,
189
+ result: [
190
+ { name: 'PROJECT_ABC123', type: 'secret_text' },
191
+ { name: 'PROJECT_DEF456', type: 'secret_text' },
192
+ ],
193
+ };
194
+
195
+ mockFetch.mockReturnValueOnce(
196
+ Promise.resolve({
197
+ json: () => Promise.resolve(mockResponse),
198
+ } as Response),
199
+ );
200
+
201
+ const result = await secretsManager.listSecrets(mockWorkerId);
202
+
203
+ expect(mockFetch).toHaveBeenCalledWith(
204
+ `https://api.cloudflare.com/client/v4/accounts/${mockAccountId}/workers/scripts/${mockWorkerId}/secrets`,
205
+ {
206
+ headers: {
207
+ Authorization: `Bearer ${mockApiToken}`,
208
+ },
209
+ },
210
+ );
211
+
212
+ expect(result).toEqual(mockResponse.result);
213
+ });
214
+
215
+ it('should handle listing errors', async () => {
216
+ const mockError = {
217
+ success: false,
218
+ errors: [{ message: 'Invalid worker ID' }],
219
+ };
220
+
221
+ mockFetch.mockReturnValueOnce(
222
+ Promise.resolve({
223
+ json: () => Promise.resolve(mockError),
224
+ } as Response),
225
+ );
226
+
227
+ await expect(secretsManager.listSecrets('invalid-worker')).rejects.toThrowError('Invalid worker ID');
228
+ });
229
+ });
230
+ });
@@ -0,0 +1,110 @@
1
+ export class CloudflareSecretsManager {
2
+ accountId: string;
3
+ apiToken: string;
4
+ baseUrl: string;
5
+
6
+ constructor({ accountId, apiToken }: { accountId: string; apiToken: string }) {
7
+ this.accountId = accountId;
8
+ this.apiToken = apiToken;
9
+ this.baseUrl = 'https://api.cloudflare.com/client/v4';
10
+ }
11
+
12
+ async createSecret({
13
+ workerId,
14
+ secretName,
15
+ secretValue,
16
+ }: {
17
+ workerId: string;
18
+ secretName: string;
19
+ secretValue: string;
20
+ }) {
21
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets`;
22
+
23
+ try {
24
+ const response = await fetch(url, {
25
+ method: 'PUT',
26
+ headers: {
27
+ Authorization: `Bearer ${this.apiToken}`,
28
+ 'Content-Type': 'application/json',
29
+ },
30
+ body: JSON.stringify({
31
+ name: secretName,
32
+ text: secretValue,
33
+ }),
34
+ });
35
+
36
+ const data = await response.json();
37
+
38
+ if (!data.success) {
39
+ throw new Error(data.errors[0].message);
40
+ }
41
+
42
+ return data.result;
43
+ } catch (error) {
44
+ console.error('Failed to create secret:', error);
45
+ throw error;
46
+ }
47
+ }
48
+
49
+ async createProjectSecrets({
50
+ workerId,
51
+ customerId,
52
+ envVars,
53
+ }: {
54
+ workerId: string;
55
+ customerId: string;
56
+ envVars: Record<string, string>;
57
+ }) {
58
+ const secretName = `PROJECT_${customerId.toUpperCase()}`;
59
+ const secretValue = JSON.stringify(envVars);
60
+
61
+ return this.createSecret({ workerId, secretName, secretValue });
62
+ }
63
+
64
+ async deleteSecret({ workerId, secretName }: { workerId: string; secretName: string }) {
65
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets/${secretName}`;
66
+
67
+ try {
68
+ const response = await fetch(url, {
69
+ method: 'DELETE',
70
+ headers: {
71
+ Authorization: `Bearer ${this.apiToken}`,
72
+ },
73
+ });
74
+
75
+ const data = await response.json();
76
+
77
+ if (!data.success) {
78
+ throw new Error(data.errors[0].message);
79
+ }
80
+
81
+ return data.result;
82
+ } catch (error) {
83
+ console.error('Failed to delete secret:', error);
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ async listSecrets(workerId: string) {
89
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets`;
90
+
91
+ try {
92
+ const response = await fetch(url, {
93
+ headers: {
94
+ Authorization: `Bearer ${this.apiToken}`,
95
+ },
96
+ });
97
+
98
+ const data = await response.json();
99
+
100
+ if (!data.success) {
101
+ throw new Error(data.errors[0].message);
102
+ }
103
+
104
+ return data.result;
105
+ } catch (error) {
106
+ console.error('Failed to list secrets:', error);
107
+ throw error;
108
+ }
109
+ }
110
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "moduleResolution": "bundler",
5
+ "outDir": "./dist",
6
+ "rootDir": "./src"
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["node_modules", "**/*.test.ts"]
10
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ include: ['src/**/*.test.ts'],
7
+ },
8
+ });