|
| 1 | +#!/usr/bin/env node |
| 2 | +// @ts-check |
| 3 | + |
| 4 | +import { existsSync, readFileSync } from 'node:fs' |
| 5 | +import https from 'node:https' |
| 6 | +import os from 'node:os' |
| 7 | +import path from 'node:path' |
| 8 | +import { pathToFileURL } from 'node:url' |
| 9 | + |
| 10 | +/** |
| 11 | + * @typedef {{ url: string, username: string, token: string }} Credentials |
| 12 | + */ |
| 13 | + |
| 14 | +const DEFAULT_CRED_FILE = path.join(os.homedir(), '.unic-confluence.json') |
| 15 | + |
| 16 | +/** |
| 17 | + * Loads Confluence credentials from env vars or a JSON credentials file. |
| 18 | + * CONFLUENCE_URL, CONFLUENCE_USER, CONFLUENCE_TOKEN env vars take precedence. |
| 19 | + * Falls back to the JSON file at credPath (~/.unic-confluence.json by default). |
| 20 | + * Throws a descriptive Error if neither source yields valid credentials. |
| 21 | + * |
| 22 | + * @param {string} [credPath] |
| 23 | + * @returns {Credentials} |
| 24 | + */ |
| 25 | +export function loadCredentials(credPath = DEFAULT_CRED_FILE) { |
| 26 | + const { CONFLUENCE_URL, CONFLUENCE_USER, CONFLUENCE_TOKEN } = process.env |
| 27 | + if (CONFLUENCE_URL && CONFLUENCE_USER && CONFLUENCE_TOKEN) { |
| 28 | + return { url: CONFLUENCE_URL, username: CONFLUENCE_USER, token: CONFLUENCE_TOKEN } |
| 29 | + } |
| 30 | + if (existsSync(credPath)) { |
| 31 | + let raw |
| 32 | + try { |
| 33 | + raw = JSON.parse(readFileSync(credPath, 'utf8')) |
| 34 | + } catch (err) { |
| 35 | + throw new Error( |
| 36 | + `Failed to read Confluence credentials from ${credPath}: ${/** @type {Error} */ (err).message}\n` + |
| 37 | + 'Verify the file is readable and contains valid JSON.', |
| 38 | + { cause: err } |
| 39 | + ) |
| 40 | + } |
| 41 | + const typed = /** @type {Credentials} */ (raw) |
| 42 | + if (typed.url && typed.username && typed.token) return typed |
| 43 | + throw new Error( |
| 44 | + `Confluence credentials file ${credPath} is missing required fields — expected { url, username, token }` |
| 45 | + ) |
| 46 | + } |
| 47 | + throw new Error( |
| 48 | + 'Confluence credentials not configured — set CONFLUENCE_URL, CONFLUENCE_USER, CONFLUENCE_TOKEN' + |
| 49 | + ' or create ~/.unic-confluence.json with { url, username, token }' |
| 50 | + ) |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Extracts the numeric page ID from a Confluence page URL. |
| 55 | + * Handles patterns: |
| 56 | + * - /pages/{id}/slug |
| 57 | + * - /pages/{id} (end of string) |
| 58 | + * - /pages/{id}?query |
| 59 | + * - /pages/{id}#anchor |
| 60 | + * |
| 61 | + * @param {string} pageUrl |
| 62 | + * @returns {string} |
| 63 | + */ |
| 64 | +export function extractPageId(pageUrl) { |
| 65 | + const match = pageUrl.match(/\/pages\/(\d+)(?:\/|[?#]|$)/) |
| 66 | + if (!match) throw new Error(`Could not extract numeric page ID from URL: ${pageUrl}`) |
| 67 | + const id = match[1] |
| 68 | + if (!id) throw new Error(`Could not extract numeric page ID from URL: ${pageUrl}`) |
| 69 | + return id |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Makes an HTTPS GET request and returns status + body. |
| 74 | + * |
| 75 | + * @param {string} urlStr |
| 76 | + * @param {string} authHeader |
| 77 | + * @returns {Promise<{ status: number, body: string }>} |
| 78 | + * @throws {Error} On network error, request timeout, or response stream error (promise rejects). |
| 79 | + */ |
| 80 | +function httpsGet(urlStr, authHeader) { |
| 81 | + return new Promise((resolve, reject) => { |
| 82 | + const parsed = new URL(urlStr) |
| 83 | + const options = { |
| 84 | + method: 'GET', |
| 85 | + hostname: parsed.hostname, |
| 86 | + path: parsed.pathname + parsed.search, |
| 87 | + headers: { |
| 88 | + Authorization: authHeader, |
| 89 | + Accept: 'application/json', |
| 90 | + }, |
| 91 | + } |
| 92 | + const req = https.request(options, (res) => { |
| 93 | + let data = '' |
| 94 | + res.on('data', (chunk) => { |
| 95 | + data += chunk |
| 96 | + }) |
| 97 | + res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data })) |
| 98 | + res.on('error', reject) |
| 99 | + }) |
| 100 | + req.setTimeout(30_000, () => { |
| 101 | + req.destroy(new Error('Request timed out after 30s — check VPN/network connectivity')) |
| 102 | + }) |
| 103 | + req.on('error', reject) |
| 104 | + req.end() |
| 105 | + }) |
| 106 | +} |
| 107 | + |
| 108 | +/** |
| 109 | + * @typedef {(url: string, authHeader: string) => Promise<{ status: number, body: string }>} HttpGet |
| 110 | + */ |
| 111 | + |
| 112 | +/** |
| 113 | + * Fetches the Confluence storage-format body of a page by its URL. |
| 114 | + * Uses the Confluence v2 API with Basic auth. |
| 115 | + * Throws on non-2xx response or network error. |
| 116 | + * |
| 117 | + * The optional `httpGet` parameter allows injecting an alternative transport |
| 118 | + * (used by tests). It defaults to the internal `httpsGet` so callers do not |
| 119 | + * need to pass anything. |
| 120 | + * |
| 121 | + * @param {string} pageUrl |
| 122 | + * @param {Credentials} credentials |
| 123 | + * @param {HttpGet} [httpGet] |
| 124 | + * @returns {Promise<string>} The raw Confluence storage-format markup for the page body |
| 125 | + */ |
| 126 | +export async function fetchPageText(pageUrl, credentials, httpGet = httpsGet) { |
| 127 | + const pageId = extractPageId(pageUrl) |
| 128 | + const apiUrl = `${credentials.url.replace(/\/$/, '')}/wiki/api/v2/pages/${pageId}?body-format=storage` |
| 129 | + const authHeader = `Basic ${Buffer.from(`${credentials.username}:${credentials.token}`).toString('base64')}` |
| 130 | + |
| 131 | + let res |
| 132 | + try { |
| 133 | + res = await httpGet(apiUrl, authHeader) |
| 134 | + } catch (err) { |
| 135 | + throw new Error(`Network error fetching ${pageUrl}: ${/** @type {Error} */ (err).message}`, { cause: err }) |
| 136 | + } |
| 137 | + |
| 138 | + if (res.status < 200 || res.status >= 300) { |
| 139 | + throw new Error(`Confluence returned HTTP ${res.status} for ${pageUrl}`) |
| 140 | + } |
| 141 | + |
| 142 | + let parsed |
| 143 | + try { |
| 144 | + parsed = JSON.parse(res.body) |
| 145 | + } catch { |
| 146 | + throw new Error(`Unexpected non-JSON response from Confluence for ${pageUrl}`) |
| 147 | + } |
| 148 | + |
| 149 | + const content = parsed?.body?.storage?.value |
| 150 | + if (typeof content !== 'string') { |
| 151 | + throw new Error(`No storage body found in Confluence response for ${pageUrl}`) |
| 152 | + } |
| 153 | + return content |
| 154 | +} |
| 155 | + |
| 156 | +// ── CLI entry point ──────────────────────────────────────────────────────────── |
| 157 | + |
| 158 | +let isMain = false |
| 159 | +try { |
| 160 | + isMain = Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href |
| 161 | +} catch { |
| 162 | + // not running as a CLI entry point (e.g. node -e / REPL / relative argv[1]) |
| 163 | +} |
| 164 | + |
| 165 | +if (isMain) { |
| 166 | + const args = process.argv.slice(2) |
| 167 | + |
| 168 | + if (args.length === 0 || (args[0] !== '--check-creds' && !args[0]?.startsWith('http'))) { |
| 169 | + console.error('Usage:') |
| 170 | + console.error(' node scripts/confluence-client.mjs --check-creds') |
| 171 | + console.error(' node scripts/confluence-client.mjs <confluence-page-url>') |
| 172 | + process.exit(1) |
| 173 | + } |
| 174 | + |
| 175 | + if (args[0] === '--check-creds') { |
| 176 | + try { |
| 177 | + loadCredentials() |
| 178 | + process.exit(0) |
| 179 | + } catch (err) { |
| 180 | + console.error(/** @type {Error} */ (err).message) |
| 181 | + process.exit(1) |
| 182 | + } |
| 183 | + } else { |
| 184 | + const url = args[0] ?? '' |
| 185 | + try { |
| 186 | + const creds = loadCredentials() |
| 187 | + const text = await fetchPageText(url, creds) |
| 188 | + process.stdout.write(text) |
| 189 | + } catch (err) { |
| 190 | + const message = err instanceof Error ? err.message : String(err) |
| 191 | + console.error(message) |
| 192 | + const cause = err instanceof Error ? /** @type {any} */ (err).cause : undefined |
| 193 | + if (cause instanceof Error) { |
| 194 | + console.error(`Caused by: ${cause.message}`) |
| 195 | + } |
| 196 | + process.exit(1) |
| 197 | + } |
| 198 | + } |
| 199 | +} |
0 commit comments