0

Add SSL Certificate

by
Published Apr 8, 2025

Uploads an SSL certificate and its matching secret so that you can use Telnyx’s storage as your CDN.

Script telnyx Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Telnyx = {
3
	apiKey: string
4
}
5
type Base64 = string
6
/**
7
 * Add SSL Certificate
8
 * Uploads an SSL certificate and its matching secret so that you can use Telnyx’s storage as your CDN.
9
 */
10
export async function main(
11
	auth: Telnyx,
12
	bucketName: string,
13
	body: {
14
		certificate?: {
15
			base64: Base64
16
			type:
17
				| 'image/png'
18
				| 'image/jpeg'
19
				| 'image/gif'
20
				| 'application/pdf'
21
				| 'appication/json'
22
				| 'text/csv'
23
				| 'text/plain'
24
				| 'audio/mpeg'
25
				| 'audio/wav'
26
				| 'video/mp4'
27
			name: string
28
		}
29
		private_key?: {
30
			base64: Base64
31
			type:
32
				| 'image/png'
33
				| 'image/jpeg'
34
				| 'image/gif'
35
				| 'application/pdf'
36
				| 'appication/json'
37
				| 'text/csv'
38
				| 'text/plain'
39
				| 'audio/mpeg'
40
				| 'audio/wav'
41
				| 'video/mp4'
42
			name: string
43
		}
44
	}
45
) {
46
	const url = new URL(`https://api.telnyx.com/v2/storage/buckets/${bucketName}/ssl_certificate`)
47

48
	const formData = new FormData()
49
	for (const [k, v] of Object.entries(body)) {
50
		if (v !== undefined) {
51
			if (['certificate', 'private_key'].includes(k)) {
52
				const { base64, type, name } = v as {
53
					base64: Base64
54
					type: string
55
					name: string
56
				}
57
				formData.append(
58
					k,
59
					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
60
						type
61
					}),
62
					name
63
				)
64
			} else {
65
				formData.append(k, String(v))
66
			}
67
		}
68
	}
69
	const response = await fetch(url, {
70
		method: 'PUT',
71
		headers: {
72
			Authorization: 'Bearer ' + auth.apiKey
73
		},
74
		body: formData
75
	})
76
	if (!response.ok) {
77
		const text = await response.text()
78
		throw new Error(`${response.status} ${text}`)
79
	}
80
	return await response.json()
81
}
82