1 | |
2 |
|
3 | function wapiUrl(auth: RT.InfobloxNios, path: string) { |
4 | const host = auth.host |
5 | .trim() |
6 | .replace(/^https?:\/\//, "") |
7 | .replace(/\/+$/, "") |
8 | const version = auth.wapi_version.trim().replace(/^v/, "") |
9 | return new URL(`https://${host}/wapi/v${version}/${path}`) |
10 | } |
11 |
|
12 | function refUrl(auth: RT.InfobloxNios, ref: string, type: string) { |
13 | |
14 | const segments = ref.split("/") |
15 | if ( |
16 | segments[0] !== type || |
17 | segments.length < 2 || |
18 | segments.some((s) => s === "." || s === "..") |
19 | ) { |
20 | throw new Error(`Expected a ${type} reference, got: ${ref}`) |
21 | } |
22 | return wapiUrl( |
23 | auth, |
24 | segments.map((s) => encodeURIComponent(s).replace(/%3A/gi, ":")).join("/") |
25 | ) |
26 | } |
27 |
|
28 | function basicAuth(auth: RT.InfobloxNios) { |
29 | const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`) |
30 | return `Basic ${btoa(String.fromCharCode(...bytes))}` |
31 | } |
32 |
|
33 | |
34 | * Update CNAME record |
35 | * Change the alias name, canonical name, TTL or comment of a CNAME record, identified by its _ref (from Search records). Empty inputs are left unchanged. |
36 | */ |
37 | export async function main( |
38 | auth: RT.InfobloxNios, |
39 | ref: string, |
40 | name: string | undefined, |
41 | canonical: string | undefined, |
42 | ttl: number | undefined, |
43 | comment: string | undefined |
44 | ) { |
45 | const body: { [key: string]: any } = {} |
46 | if (name) body.name = name |
47 | if (canonical) body.canonical = canonical |
48 | if (ttl != null) { |
49 | body.ttl = ttl |
50 | body.use_ttl = true |
51 | } |
52 | if (comment) body.comment = comment |
53 | if (Object.keys(body).length === 0) { |
54 | throw new Error("Nothing to update: set at least one field") |
55 | } |
56 |
|
57 | const url = refUrl(auth, ref, "record:cname") |
58 | url.searchParams.append("_return_fields+", "name,canonical,view,ttl,comment") |
59 | url.searchParams.append("_return_as_object", "1") |
60 |
|
61 | const response = await fetch(url, { |
62 | method: "PUT", |
63 | headers: { |
64 | Authorization: basicAuth(auth), |
65 | "Content-Type": "application/json", |
66 | Accept: "application/json", |
67 | }, |
68 | body: JSON.stringify(body), |
69 | }) |
70 |
|
71 | if (!response.ok) { |
72 | throw new Error(`${response.status} ${await response.text()}`) |
73 | } |
74 |
|
75 | return await response.json() |
76 | } |
77 |
|