All files common.ts

90.55% Statements 115/127
83.67% Branches 82/98
96.55% Functions 28/29
98.09% Lines 103/105

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289                            6x                                     128x   128x             128x         128x                   127x 127x   127x 127x 6x   121x   127x       1x   1x 1x 1x   1x       52x       52x       1x       44x       1x       1x       13x 12x 12x   4x 4x     1x       272x 35x         19x       4x       19x 19x       55x 55x 55x 55x 55x       55x 55x 8x   55x       7x 5x   2x           29x     29x 12x 11x 11x       29x       268x           147x 147x   6x     141x 58x 58x     58x 58x     55x   55x                       92x 92x   6x     86x 62x 61x     61x     58x   58x         120x 13x 11x         64x 64x         13x 13x 3x 9x 9x 9x   8x   2x               11x 11x   31x 11x 11x 11x 32x     11x 11x   10x         96x 384x   96x 96x 96x 96x   96x    
// SPDX-FileCopyrightText: 2025-2026 Anaconda, Inc
// SPDX-License-Identifier: Apache-2.0
 
import * as fs from 'fs';
import { Configuration, InternalConfiguration, toImpl as toImplCfg } from './config.js';
import { ResourceAttributes, InternalResourceAttributes, toImpl as toImplAttrs } from './attributes.js';
import type { AttrMap } from './types.js';
 
// value import (namespace gives us both ESM & CJS shapes)
import * as resourcesNS from '@opentelemetry/resources';
import { setGlobalDispatcher, ProxyAgent } from 'undici'
 
// ---- v2 export OR v1 fallback to `new Resource(attrs)` ----
const resourceFromAttributes =
  (resourcesNS as any).resourceFromAttributes ??
  ((attrs: Record<string, unknown>) => new (resourcesNS as any).Resource(attrs));
 
// type import + alias (so you can keep using `Resource` in type positions)
import type { Resource as _Resource } from '@opentelemetry/resources';
type Resource = _Resource;
 
// type import for typing only
import type { Resource as ResourceType } from '@opentelemetry/resources';
 
/**
 * Build a Resource with SDK defaults + user attributes.
 * Synchronous, ctor-safe, no detectors.
 */
export function buildResourceWithDefaults(
  attrs: Record<string, unknown> = {}
): ResourceType {
  // Get SDK default resource
  let base: any;
  if (typeof (resourcesNS as any).defaultResource === 'function') {
    // v2.x function API
    base = (resourcesNS as any).defaultResource();
  } else E{
    throw new Error('Unsupported @opentelemetry/resources runtime');
  }
 
  // Build resource from attributes
  const custom =
    typeof (resourcesNS as any).resourceFromAttributes === 'function'
      ? (resourcesNS as any).resourceFromAttributes(attrs)
      : new (resourcesNS as any).Resource(attrs);
 
  // Merge: defaults <- custom (custom wins)
    return base.merge(custom) as ResourceType;
}
 
 
export class AnacondaCommon {
    config: InternalConfiguration
    attributes: InternalResourceAttributes
    resources: Resource
 
    protected constructor(config: Configuration, attributes: ResourceAttributes) {
        this.config = toImplCfg(config)
        this.attributes = toImplAttrs(attributes)
 
        let resourceObject = this.attributes.getResourceAttributes()
        if (this.config.getEntropy() !== '') {
            resourceObject['session.id'] = this.config.getEntropy()
        } else {
            resourceObject['session.id'] = crypto.randomUUID();
        }
        this.resources = buildResourceWithDefaults(resourceObject)
    }
 
    protected makeNewResource(newAttributes: ResourceAttributes): void {
        this.attributes = toImplAttrs(newAttributes)
 
        let resourceObject = this.attributes.getResourceAttributes()
        Eif (this.config.getEntropy() !== '') {
            resourceObject['session.id'] = this.config.getEntropy()
        }
        this.resources = buildResourceWithDefaults(resourceObject)
    }
 
    protected get serviceName(): string {
        return this.attributes.getServiceName()
    }
 
    protected get serviceVersion(): string {
        return this.attributes.getServiceVersion()
    }
 
    protected get useConsole(): boolean {
        return this.config.getUseConsole()
    }
 
    protected get metricsExportIntervalMs(): number {
        return this.config.getMetricsExportIntervalMs()
    }
 
    protected get loggingExportIntervalMs(): number {
        return this.config.getLoggingExportIntervalMs()
    }
 
    protected get skipInternetCheck(): boolean {
        return this.config.getSkipInternetCheck()
    }
 
    protected readCertFile(certFile: string): string | undefined {
        if (certFile && certFile.length > 0) {
            try {
                return fs.readFileSync(certFile, 'utf8')
            } catch (error) {
                this._error(`Failed to read certificate file: ${certFile}: ${error}`)
                return undefined
            }
        }
        return undefined
    }
 
    protected _debug(line: string) {
        if (this.config.getUseDebug()) {
            console.debug(`${localTimeString()} > *** ATEL DEBUG: ${line}`)
        }
    }
 
    protected _warn(line: string) {
        console.warn(`${localTimeString()} > *** ATEL WARNING: ${line}`)
    }
 
    protected _error(line: string) {
        console.error(`${localTimeString()} > *** ATEL ERROR: ${line}`)
    }
 
    protected isValidName(name: string): boolean {
        const regex = /^[A-Za-z][A-Za-z_0-9]+$/;
        return regex.test(name);
    }
 
    protected transformURL(url: URL): [string, URL] {
        const scheme = url.protocol
        const ep = new URL(url.href)
        ep.protocol = ep.protocol.replace("grpcs:", "https:")
        ep.protocol = ep.protocol.replace("grpc:", "http:")
        return [scheme, ep]
    }
 
    protected makeHeaders(scheme: string, authToken: string | undefined): Record<string,string> {
        var headers: Record<string,string> = authToken ? { 'Authorization': `Bearer ${authToken}` } : {}
        if (scheme.startsWith('http')) {
            headers['Content-Type'] = 'application/x-protobuf'
        }
        return headers
    }
 
    errorMessage(err: any): string {
        if (err instanceof Error) {
            return err.message
        } else {
            return String(err)
        }
    }
 
    makeEventAttributes(userAttributes: AttrMap | undefined | null): AttrMap {
        // Get changing attributes from ResourceAttributes...
        const result: AttrMap = this.attributes.getEventAttributes()
 
        // Add user supplied attributes if any...
        if (userAttributes) {
            for (const key in userAttributes) {
                Eif (userAttributes[key]) {
                    result[key] = userAttributes[key]
                }
            }
        }
        return result
    }
 
    protected isValidOtelUrl(urlStr: string): boolean {
        return urlStr === "console:" || urlStr === "devnull:" ||
               this.isValidOtelHttpUrl(urlStr) || this.isValidOtelGrpcUrl(urlStr)
    }
 
    private isValidOtelHttpUrl(urlStr: string): boolean {
        let u: URL;
        try {
            u = new URL(urlStr);
        } catch {
            return false;
        }
 
        if (u.protocol !== "http:" && u.protocol !== "https:") return false;
        Iif (!this.isValidHost(u.hostname)) return false;
        Iif (u.port && !this.isValidPort(u.port)) return false;
 
        // Required exact path: /v1/{type} (no trailing "/")
        const m = /^\/v1\/(metrics|logs|traces)$/.exec(u.pathname);
        if (!m) return false;
 
        // No query/fragment
        Iif (u.search !== "" || u.hash !== "") return false;
 
        return true;
    }
 
    /**
     * 2) Validate an OTLP/gRPC URL:
     * - scheme: grpc | grpcs
     * - host: ipv4 | domain | localhost
     * - optional port
     * - MUST NOT have a path (i.e. "/" only), NO query/fragment
     */
    private isValidOtelGrpcUrl(urlStr: string): boolean {
        let u: URL;
        try {
            u = new URL(urlStr);
        } catch {
            return false;
        }
 
        if (u.protocol !== "grpc:" && u.protocol !== "grpcs:") return false;
        if (!this.isValidHost(u.hostname)) return false;
        Iif (u.port && !this.isValidPort(u.port)) return false;
 
        // No path (URL parser represents "no path" as "/")
        if (u.pathname !== "/") return false;
 
        // No query/fragment
        Iif (u.search !== "" || u.hash !== "") return false;
 
        return true;
    }
 
    /** Host can be "localhost", a valid IPv4, or a valid domain name. */
    private isValidHost(hostname: string): boolean {
        if (hostname === "localhost") return true;
        if (this.isValidIpv4(hostname)) return true;
        return this.isValidDomain(hostname);
    }
 
    private isValidPort(portStr: string): boolean {
        // URL.port is always digits or empty
        const port = Number(portStr);
        return Number.isInteger(port) && port >= 1 && port <= 65535;
    }
 
    private isValidIpv4(s: string): boolean {
        // Strict IPv4: 0-255.0-255.0-255.0-255
        const parts = s.split(".");
        if (parts.length !== 4) return false;
        for (const p of parts) {
            Iif (!/^\d{1,3}$/.test(p)) return false;
            const n = Number(p);
            if (!Number.isInteger(n) || n < 0 || n > 255) return false;
            // Optional: disallow leading zeros like "01" (commonly preferred)
            Iif (p.length > 1 && p.startsWith("0")) return false;
        }
        return true;
    }
 
    private isValidDomain(host: string): boolean {
        // Conservative domain validation:
        // - labels: [a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?
        // - TLD 2-63 letters
        // - total length <= 253
        const h = host.toLowerCase();
        Iif (h.length === 0 || h.length > 253) return false;
 
        const labels = h.includes(".") ? h.split(".").filter(l => l.length > 0) : [h];
        Iif (labels.length === 0) return false;
        const labelRe = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
        for (const label of labels) {
            Iif (!labelRe.test(label)) return false;
        }
 
        const tld = labels[labels.length - 1];
        if (labels.length > 1 &&!/^[a-z]{2,63}$/.test(tld)) return false;
 
        return true;
    }
}
 
export function localTimeString(): string {
    const d = new Date();
    const pad = (n: number, width = 2) => String(n).padStart(width, "0");
 
    const hh = pad(d.getHours());
    const mm = pad(d.getMinutes());
    const ss = pad(d.getSeconds());
    const ms = pad(d.getMilliseconds(), 3);
 
    return `${hh}:${mm}:${ss}.${ms}`;
}