Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,400 changes: 814 additions & 586 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 9 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@leanix/reporting-cli",
"type": "commonjs",
"version": "1.0.0-beta.27",
"version": "1.0.0-beta.28",
"description": "Command line interface to develop custom reports for LeanIX EAM",
"preferGlobal": true,
"author": "LeanIX GmbH <support@leanix.net>",
Expand All @@ -28,28 +28,30 @@
"test": "jest",
"test-install": "npm run build && npm -g install .",
"prepare": "npm run build",
"prepublishOnly": "npm run lint && npm test"
"prepublishOnly": "npm run lint && npm test",
"type-check": "npx tsc --noEmit"
},
"dependencies": {
"axios": "1.10.0",
"axios": "1.12.2",
"chalk": "4.1.2",
"commander": "12.1.0",
"cross-spawn": "7.0.6",
"ejs": "3.1.10",
"form-data": "4.0.4",
"https-proxy-agent": "7.0.6",
"inquirer": "7.3.3",
"jwt-decode": "2.2.0",
"inquirer": "8.2.7",
"jwt-decode": "4.0.0",
"lodash": "4.17.21",
"mkdirp": "3.0.1",
"opn": "5.5.0",
"rimraf": "6.0.1",
"tar": "6.2.1"
"tar": "6.2.1",
"zod": "^4.1.9"
},
"devDependencies": {
"@antfu/eslint-config": "4.19.0",
"@types/ejs": "3.1.5",
"@types/inquirer": "7.3.3",
"@types/inquirer": "8.2.7",
"@types/jest": "29.5.13",
"@types/lodash": "4.17.9",
"@types/mkdirp": "2.0.0",
Expand Down
12 changes: 5 additions & 7 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ the "host" given in lxr.json.`)
.action(async () => {
const cliConfig = loadCliConfig()
const lxrConfig = loadLxrConfig()
const url = `https://${lxrConfig.host}/services/pathfinder/v1/reports/upload`
const { host: tokenhost, apitoken, proxyURL } = lxrConfig

const builder = new Builder(console)
const bundler = new Bundler()
Expand All @@ -87,7 +87,7 @@ the "host" given in lxr.json.`)
try {
await builder.build(cliConfig.distPath, cliConfig.buildCommand)
await bundler.bundle(cliConfig.distPath)
await uploader.upload(url, lxrConfig.apitoken, lxrConfig.host, lxrConfig.proxyURL)
await uploader.upload({ tokenhost, apitoken, proxyURL })
}
catch (error) {
handleError(error)
Expand All @@ -97,14 +97,12 @@ the "host" given in lxr.json.`)
program
.command('store-upload <id> <apitoken>')
.description('Uploads the report to the LeanIX Store')
.requiredOption('--tokenhost <tokenhost>', 'Where to resolve the apitoken (default: app.leanix.net)')
.option('--host <host>', 'Which store to use (default: store.leanix.net)')
.option('--tokenhost <tokenhost>', 'Where to resolve the apitoken (default: app.leanix.net)')
.action(async (id: string, apitoken: string, options: { host: string, tokenhost: string }) => {
.action(async (assetVersionId: string, apitoken: string, options: { host: string, tokenhost: string }) => {
const cliConfig = loadCliConfig()

const host = options.host || 'store.leanix.net'
const tokenhost = options.tokenhost || 'app.leanix.net'
const url = `https://${host}/services/torg/v1/assetversions/${id}/payload`

const builder = new Builder(console)
const bundler = new Bundler()
Expand All @@ -115,7 +113,7 @@ program
try {
await builder.build(cliConfig.distPath, cliConfig.buildCommand)
await bundler.bundle(cliConfig.distPath)
await uploader.upload(url, apitoken, tokenhost)
await uploader.upload({ apitoken, tokenhost: options.tokenhost, store: { assetVersionId, host } })
}
catch (error) {
handleError(error)
Expand Down
39 changes: 14 additions & 25 deletions src/dev-starter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import type { LxrConfig } from './interfaces'
import { join } from 'node:path'
import chalk from 'chalk'
import { spawn } from 'cross-spawn'
import jwtDecode from 'jwt-decode'
import * as _ from 'lodash'
import opn from 'opn'
import { ApiTokenResolver } from './api-token-resolver'
import { loadLxrConfig } from './file.helpers'
import { getJwtClaims } from './helpers'

interface DevServerStartResult {
launchUrl: string
Expand All @@ -27,24 +26,21 @@ export class DevStarter {
)
}

private async startLocalServer(config: LxrConfig, accessToken?: string): Promise<DevServerStartResult> {
private async startLocalServer(config: LxrConfig, accessToken: string): Promise<DevServerStartResult> {
const port = config.localPort || 8080
const localhostUrl = `https://localhost:${port}`
const urlEncoded = encodeURIComponent(localhostUrl)
const host = `https://${config.host}`
const claims = getJwtClaims(accessToken)

const accessTokenHash = accessToken ? `#access_token=${accessToken}` : ''
const workspace = accessToken ? this.getWorkspaceFromAccesToken(accessToken) : config.workspace
const instanceUrl = claims.instanceUrl
const workspace = claims.principal.permission.workspaceName

if (_.isEmpty(workspace)) {
console.error(chalk.red('Workspace not specified. The local server can\'t be started.'))
return new Promise(null)
}
console.log(chalk.green(`Your workspace is ${workspace}`))

const baseLaunchUrl = `${host}/${workspace}/reports/dev?url=${urlEncoded}`
const launchUrl = baseLaunchUrl + accessTokenHash
console.log(chalk.green(`Starting development server and launching with url: ${baseLaunchUrl}`))
const launchUrl = new URL(`${instanceUrl}/${workspace}/reports/dev?url=${urlEncoded}`)
launchUrl.hash = `access_token=${accessToken}`

console.log(chalk.green(`Starting development server and launching with url: ${launchUrl}`))

const wpMajorVersion = await this.getCurrentWebpackMajorVersion()
const args = ['--port', `${port}`]
Expand Down Expand Up @@ -91,7 +87,7 @@ export class DevStarter {
}

if (projectRunning && output.toLowerCase().includes('compiled successfully')) {
resolve({ launchUrl, localhostUrl })
resolve({ launchUrl: launchUrl.toString(), localhostUrl })
}
})
})
Expand All @@ -109,19 +105,12 @@ export class DevStarter {
})
}

private getWorkspaceFromAccesToken(accessToken: string) {
const claims = jwtDecode(accessToken)
return claims.principal.permission.workspaceName
}

private async getAccessToken(config: LxrConfig): Promise<string> {
if (!_.isEmpty(config.apitoken)) {
const token = await ApiTokenResolver.getAccessToken(`https://${config.host}`, config.apitoken, config.proxyURL)
return token
}
else {
return Promise.resolve(null)
if (!config.apitoken) {
throw new Error('no api token provided, please include it in the lxr.json file')
}
const token = await ApiTokenResolver.getAccessToken(`https://${config.host}`, config.apitoken, config.proxyURL)
return token
}

private openUrlInBrowser(url: string) {
Expand Down
48 changes: 48 additions & 0 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,52 @@
import { HttpsProxyAgent } from 'https-proxy-agent'
import { InvalidTokenError, jwtDecode } from 'jwt-decode'
import z, { ZodError } from 'zod'

export const jwtClaimsPrincipalSchema = z.object({
id: z.string(),
username: z.string(),
role: z.string(),
status: z.string(),
account: z.object({ id: z.string(), name: z.string() }),
permission: z.object({
id: z.string(),
workspaceId: z.string(),
workspaceName: z.string(),
role: z.string(),
status: z.string()
})
})

export const jwtClaimsSchema = z.object({
sub: z.string(),
principal: jwtClaimsPrincipalSchema,
iss: z.url(),
jti: z.string(),
exp: z.number(),
instanceUrl: z.url(),
region: z.string()
})

export type TJwtClaims = z.infer<typeof jwtClaimsSchema>

export const getJwtClaims = (bearerToken: string): TJwtClaims => {
let claims: TJwtClaims
let claimsUnchecked: unknown
try {
claimsUnchecked = jwtDecode(bearerToken)
claims = jwtClaimsSchema.parse(claimsUnchecked)
}
catch (err) {
if (err instanceof InvalidTokenError) {
console.error('could not decode jwt token', err)
}
if (err instanceof ZodError) {
console.error('unexpected jwt claims schema', err.message)
}
throw err
}
return claims
}

export const getAxiosProxyConfiguration = (proxyConfig: string): HttpsProxyAgent<string> => {
const httpsAgent = new HttpsProxyAgent(proxyConfig)
Expand Down
5 changes: 0 additions & 5 deletions src/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,6 @@ export class Initializer {
default: 'app.leanix.net',
message: 'Which host do you want to work with?'
},
{
type: 'input',
name: 'workspace',
message: 'Which is the workspace you want to test your report in?'
},
{
type: 'input',
name: 'apitoken',
Expand Down
1 change: 0 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export interface LxrConfig {
host: string
workspace: string
apitoken: string
localPort?: string
proxyURL?: string
Expand Down
28 changes: 18 additions & 10 deletions src/uploader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,25 @@ import axios from 'axios'
import chalk from 'chalk'
import FormData from 'form-data'
import { ApiTokenResolver } from './api-token-resolver'
import { getAxiosProxyConfiguration } from './helpers'
import { getAxiosProxyConfiguration, getJwtClaims } from './helpers'
import { getProjectDirectoryPath } from './path.helpers'

export class Uploader {
public async upload(url: string, apitoken: string, tokenhost: string, proxy?: string): Promise<boolean> {
const accessToken = await ApiTokenResolver.getAccessToken(`https://${tokenhost}`, apitoken, proxy)
return await this.executeUpload(url, accessToken, proxy)
}
public async upload(params: { tokenhost: string, apitoken: string, proxyURL?: string, store?: { assetVersionId: string, host?: string } }) {
const { tokenhost, apitoken, proxyURL, store } = params
const accessToken = await ApiTokenResolver.getAccessToken(`https://${tokenhost}`, apitoken, proxyURL)

const claims = getJwtClaims(accessToken)
let url: string
if (store) {
const { host = 'store.leanix.net', assetVersionId } = store
url = `https://${host}/services/torg/v1/assetversions/${assetVersionId}/payload`
}
else {
url = `${claims.instanceUrl}/services/pathfinder/v1/reports/upload`
}

private async executeUpload(url: string, accessToken: string, proxy?: string) {
console.log(chalk.yellow(chalk.italic(`Uploading to ${url} ${proxy ? `through a proxy` : ``}...`)))
console.log(chalk.yellow(chalk.italic(`Uploading to ${url} ${proxyURL ? `through a proxy` : ``}...`)))

const formData = new FormData()
formData.append('file', fs.createReadStream(getProjectDirectoryPath('bundle.tgz')))
Expand All @@ -26,12 +34,12 @@ export class Uploader {
}
}

if (proxy) {
options.httpsAgent = getAxiosProxyConfiguration(proxy)
if (proxyURL) {
options.httpsAgent = getAxiosProxyConfiguration(proxyURL)
}

try {
const response = await axios.post(url, formData, options)
const response = await axios.post(url.toString(), formData, options)
if (response.data.status === 'OK') {
console.log(chalk.green('\u2713 Project successfully uploaded!'))
return true
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { join } from 'node:path'
import { readJsonFile } from './file.helpers'

const packageJson = readJsonFile(join(__dirname, '..', 'package.json'))
const packageJson = readJsonFile(join(__dirname, '..', 'package.json')) as { version: string }
export const version = packageJson.version
2 changes: 1 addition & 1 deletion template/README.md.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ Builds the report and outputs the build result into `dist` folder.

`npm run upload`

Uploads the report to the workspace configured in `lxr.json`.
Uploads the report to the workspace where the API token was issued.
Please see [Uploading to LeanIX workspace](https://github.com/leanix/leanix-reporting-cli#uploading-to-leanix-workspace).
1 change: 0 additions & 1 deletion template/lxr.json.ejs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"host": "<%= host %>",
"workspace": "<%= workspace %>",
"apitoken": "<%= apitoken %>",
"proxyURL": "<%= behindProxy ? proxyURL : '' %>",
"localPort": "8080"
Expand Down