当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript chalk.red函数代码示例

本文整理汇总了TypeScript中chalk.red函数的典型用法代码示例。如果您正苦于以下问题:TypeScript red函数的具体用法?TypeScript red怎么用?TypeScript red使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了red函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: run

export async function run() {
  const yargs = require("yargs");

  const argv = yargs
    .usage("lerna-changelog [options]")
    .options({
      from: {
        type: "string",
        desc: "A git tag or commit hash that determines the lower bound of the range of commits",
        defaultDescription: "latest tagged commit",
      },
      to: {
        type: "string",
        desc: "A git tag or commit hash that determines the upper bound of the range of commits",
      },
      "tag-from": {
        hidden: true,
        type: "string",
        desc: "A git tag that determines the lower bound of the range of commits (defaults to last available)",
      },
      "tag-to": {
        hidden: true,
        type: "string",
        desc: "A git tag that determines the upper bound of the range of commits",
      },
      "next-version": {
        type: "string",
        desc: "The name of the next version",
        default: "Unreleased",
      },
      "next-version-from-metadata": {
        type: "boolean",
        desc: "Infer the name of the next version from package metadata",
        default: false,
      },
    })
    .example(
      "lerna-changelog",
      'create a changelog for the changes after the latest available tag, under "Unreleased" section'
    )
    .example(
      "lerna-changelog --from=0.1.0 --to=0.3.0",
      "create a changelog for the changes in all tags within the given range"
    )
    .epilog("For more information, see https://github.com/lerna/lerna-changelog")
    .wrap(Math.min(100, yargs.terminalWidth()))
    .parse();

  let options = {
    tagFrom: argv["from"] || argv["tag-from"],
    tagTo: argv["to"] || argv["tag-to"],
  };

  try {
    let config = loadConfig({
      nextVersionFromMetadata: argv["next-version-from-metadata"],
    });

    if (argv["next-version"]) {
      config.nextVersion = argv["next-version"];
    }

    let result = await new Changelog(config).createMarkdown(options);

    let highlighted = highlight(result, {
      language: "Markdown",
      theme: {
        section: chalk.bold,
        string: chalk.hex("#0366d6"),
        link: chalk.dim,
      },
    });

    console.log(highlighted);
  } catch (e) {
    if (e instanceof ConfigurationError) {
      console.log(chalk.red(e.message));
    } else {
      console.log(chalk.red(e.stack));
    }
  }
}
开发者ID:lerna,项目名称:lerna-changelog,代码行数:82,代码来源:cli.ts

示例2: registerPartials

    fs.writeFileSync(filePath, renderedTsCode);
    logUtils.log(`Created: ${chalk.bold(filePath)}`);
}

Handlebars.registerHelper('parameterType', utils.solTypeToTsType.bind(utils, ParamKind.Input, args.backend));
Handlebars.registerHelper('returnType', utils.solTypeToTsType.bind(utils, ParamKind.Output, args.backend));

if (args.partials) {
    registerPartials(args.partials);
}
const mainTemplate = utils.getNamedContent(args.template);
const template = Handlebars.compile<ContextData>(mainTemplate.content);
const abiFileNames = globSync(args.abis);

if (_.isEmpty(abiFileNames)) {
    logUtils.log(`${chalk.red(`No ABI files found.`)}`);
    logUtils.log(`Please make sure you've passed the correct folder name and that the files have
               ${chalk.bold('*.json')} extensions`);
    process.exit(1);
} else {
    logUtils.log(`Found ${chalk.green(`${abiFileNames.length}`)} ${chalk.bold('ABI')} files`);
    mkdirp.sync(args.output);
}
for (const abiFileName of abiFileNames) {
    const namedContent = utils.getNamedContent(abiFileName);
    logUtils.log(`Processing: ${chalk.bold(namedContent.name)}...`);
    const parsedContent = JSON.parse(namedContent.content);
    let ABI;
    if (_.isArray(parsedContent)) {
        ABI = parsedContent; // ABI file
    } else if (!_.isUndefined(parsedContent.abi)) {
开发者ID:ewingrj,项目名称:0x-monorepo,代码行数:31,代码来源:index.ts

示例3: gray

 const diff = diffJson2.map(part => {
   if (part.added) return green(part.value.replace(/.+/g, '    - $&'))
   if (part.removed) return red(part.value.replace(/.+/g, '    + $&'))
   return gray(part.value.replace(/.+/g, '    | $&'))
 }).join('')
开发者ID:ArchMa9e,项目名称:electron-builder,代码行数:5,代码来源:fileAssert.ts

示例4: tsCompile

 return tsCompile('ngc', ngcFlags).catch(() => {
   const error = red(`Failed to compile ${secondaryEntryPoint} using ${entryPointTsconfigPath}`);
   console.error(error);
   return Promise.reject(error);
 });
开发者ID:codef0rmer,项目名称:material2,代码行数:5,代码来源:compile-entry-point.ts

示例5: buildWxPlugin

async function buildWxPlugin (appPath, { watch }) {
  const {
    sourceDir,
    outputDir
  } = setBuildData(appPath, BUILD_TYPES.WEAPP)
  const pluginDir = path.join(sourceDir, PLUGIN_ROOT)
  const pluginPath = path.join(appPath, PLUGIN_ROOT)
  const docDir = path.join(pluginDir, DOC_ROOT)
  const docPath = path.join(appPath, DOC_ROOT)

  fs.existsSync(pluginPath) && Util.emptyDirectory(pluginPath)
  fs.existsSync(docPath) && Util.emptyDirectory(docPath)
  // 编译调试项目
  await buildWeapp(appPath, { adapter: BUILD_TYPES.WEAPP, envHasBeenSet: true })

  const pluginJsonPath = path.join(pluginDir, PLUGIN_JSON)
  if (!fs.existsSync(pluginDir) || !fs.existsSync(pluginJsonPath)) {
    return console.log(chalk.red('缺少 plugin.json!'))
  }
  const pluginJson = fs.readJSONSync(pluginJsonPath)
  const components = pluginJson.publicComponents
  const pages: { [key: string]: any } = pluginJson.pages
  const main = pluginJson.main

  // 编译插件页面
  if (pages && Object.keys(pages).length) {
    Util.printLog(processTypeEnum.COMPILE, '插件页面')
    const pagesPromises = Object.values(pages).map(page => buildSinglePage(path.join(PLUGIN_ROOT, page)))
    await Promise.all(pagesPromises)
  }

  // 编译插件组件
  if (components && Object.keys(components).length) {
    Util.printLog(processTypeEnum.COMPILE, '插件组件')
    const componentList: any[] = []
    for (const component in components) {
      const componentPath = components[component]
      componentList.push({
        path: /^(\.|\/)/.test(componentPath) ? componentPath : '.' + path.sep + componentPath,
        name: component,
        type: 'default'
      })
    }
    const realComponentsPathList = getRealComponentsPathList(pluginJsonPath, componentList)
    await buildDepComponents(realComponentsPathList)
  }

  // 编译插件 main.js
  if (main) {
    Util.printLog(processTypeEnum.COMPILE, '插件 JS')
    await Promise.all(compileDepScripts([path.join(pluginDir, main)], true, true))
  }

  // 把 plugin 目录挪到根目录
  fs.moveSync(path.join(outputDir, PLUGIN_ROOT), pluginPath)
  // 把 npm 拷贝一份到 plugin 目录
  fs.copySync(path.join(outputDir, NPM_DIR), path.join(pluginPath, NPM_DIR))
  // 把 doc 目录拷贝到根目录
  fs.existsSync(docDir) && fs.copySync(docDir, docPath)
  // 拷贝 plugin.json
  compilePluginJson(pluginJson, path.join(pluginPath, PLUGIN_JSON))

  // plugin 文件夹内对 npm 的引用路径修改
  const names = glob.sync('plugin/{,!(npm)/**/}*.js')
  const ioPromises = names.map(name => {
    const content = fs.readFileSync(name).toString()

    let isShouldBeWritten
    let replacement = content.replace(/['|"]((\.\.\/)+)npm\/.+?['|"]/g, (str, $1) => {
      isShouldBeWritten = true
      return $1 === '../' ? str.replace('../', './') : str.replace('../', '')
    })

    const REG_PLUGIN_DEPS = RegExp(`['|"](/${PLUGIN_ROOT}.+)['|"]`, 'g')
    replacement = replacement.replace(REG_PLUGIN_DEPS, (str, $1) => {
      if (REG_FONT.test($1) || REG_IMAGE.test($1) || REG_MEDIA.test($1)) {
        return str.replace(RegExp(`^['|"]/${PLUGIN_ROOT}`, 'g'), str => str.replace(`${PLUGIN_ROOT}`, ''))
      }
      return str
    })

    if (isShouldBeWritten) fs.writeFileSync(path.join(appPath, name), replacement)
  })
  await Promise.all(ioPromises)

  watch && wxPluginWatchFiles()
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:87,代码来源:plugin.ts

示例6: upload


//.........这里部分代码省略.........
      this.out.action.stop(chalk.cyan(`${Date.now() - before}ms`))
      before = Date.now()
      this.out.log('\nUploading nodes...')
      const state = this.getState()

      for (const fileName of files.nodes) {
        const n = this.getNumber(fileName)
        if (state.nodes >= n) {
          this.out.log(`Skipping file ${fileName} (already imported)`)
          continue
        }
        const file = fs.readFileSync(fileName, 'utf-8')
        const json = JSON.parse(file)
        const result = await this.client.upload(
          serviceName,
          stage,
          file,
          token,
          workspaceSlug,
        )
        this.checkForErrors(result)
        if (result.length > 0) {
          this.out.log(this.out.getStyledJSON(result))
          this.out.exit(1)
        }

        state.nodes = n
        this.saveState(state)
      }
      this.out.log(
        'Uploading nodes done ' + chalk.cyan(`${Date.now() - before}ms`),
      )
      before = Date.now()
      this.out.log('\nUploading lists')
      for (const fileName of files.lists) {
        const n = this.getNumber(fileName)
        if (state.lists >= n) {
          this.out.log(`Skipping file ${fileName} (already imported)`)
          continue
        }
        const file = fs.readFileSync(fileName, 'utf-8')
        const json = JSON.parse(file)
        const result = await this.client.upload(
          serviceName,
          stage,
          file,
          token,
          workspaceSlug,
        )
        this.checkForErrors(result)
        if (result.length > 0) {
          this.out.log(this.out.getStyledJSON(result))
          this.out.exit(1)
        }
        state.lists = n
        this.saveState(state)
      }
      this.out.log(
        'Uploading lists done ' + chalk.cyan(`${Date.now() - before}ms`),
      )
      before = Date.now()
      this.out.log('\nUploading relations')
      for (const fileName of files.relations) {
        const n = this.getNumber(fileName)
        if (state.relations >= n) {
          this.out.log(`Skipping file ${fileName} (already imported)`)
          continue
        }
        const file = fs.readFileSync(fileName, 'utf-8')
        const json = JSON.parse(file)
        const result = await this.client.upload(
          serviceName,
          stage,
          file,
          token,
          workspaceSlug,
        )
        this.checkForErrors(result)
        if (result.length > 0) {
          this.out.log(this.out.getStyledJSON(result))
          this.out.exit(1)
        }
        state.relations = n
        this.saveState(state)
      }
      this.saveState(defaultState)
      this.out.log(
        'Uploading relations done ' + chalk.cyan(`${Date.now() - before}ms`),
      )
      if (!this.isDir) {
        fs.removeSync(this.importDir)
      }
    } catch (e) {
      this.out.log(chalk.yellow(`Uncaught exception, cleaning up: ${e}`))
      this.out.action.stop(chalk.red(figures.cross))
      if (!this.isDir) {
        fs.removeSync(this.importDir)
      }
    }
  }
开发者ID:ahmb84,项目名称:prisma,代码行数:101,代码来源:Importer.ts

示例7: function

const run = async function (cliArgs: any): Promise<void> {
  clearConsole();
  console.log(chalk.underline('ActionableAgile Extraction Tool'));
  console.log('JIRA Extractor configuring...');
  // Parse CLI settings
  const jiraConfigPath: string = cliArgs.i ? cliArgs.i : defaultYamlPath;
  const isLegacyYaml: boolean = (cliArgs.l || cliArgs.legacy) ? true : false;
  const debugMode: boolean = cliArgs.d ? true : false;
  const outputPath: string = cliArgs.o ? cliArgs.o : defaultOutputPath;
  const outputType: string = outputPath.split('.')[1].toUpperCase();
  if (outputType !== 'CSV' && outputType !== 'JSON') {
    throw new Error('Only CSV and JSON is currently supported for file output.');
  }
  // Parse YAML settings
  let settings: any = {};
  try {
    let yamlConfig = safeLoad(fs.readFileSync(jiraConfigPath, 'utf8'));
    settings = yamlConfig;
    settings.legacy = isLegacyYaml;
  } catch (e) {
    console.log(`Error parsing settings ${e}`);
    throw e;
  }

  console.log('');
  if (debugMode) {
    console.log(`Debug mode: ${chalk.green('ON') }`);
  }

  if (settings['Feature Flags']) {
    console.log('Feature Flags detected:');
    for (let featureName in settings['Feature Flags']) {
      console.log(`  ${featureName}: ${settings['Feature Flags'][featureName] ? chalk.green('ON') : chalk.red('OFF')}`);
    }
    console.log('');
  }

  if (!settings.Connection.Password && !settings.Connection.Token) {
    const password = await getPassword();
    settings.Connection.Password = password;
    console.log('');
  }

  // Import data
  const jiraExtractorConfig = convertYamlToJiraSettings(settings);
  const jiraExtractor = new JiraExtractor(jiraExtractorConfig);

  console.log('Authenticating...');
  const isAuthenticated = await jiraExtractor.testConnection();
  if (!isAuthenticated) {
    throw new Error('Unable to authenticate. Please check your provided credentials.');
  }
  console.log(chalk.green('Authentication successful.\n'));

  console.log('Beginning extraction process');
  // Progress bar setup
  const updateProgressHook = (bar => {
    bar.tick();
    return (percentDone: number) => {
      if (percentDone <= 100) {
        bar.tick(percentDone);
      }
    };
  })(bar);

  try {
    const workItems = await jiraExtractor.extractAll(updateProgressHook, debugMode);
    // Export data
    let data: string = '';
    if (outputType === 'CSV') {
      data = await jiraExtractor.toCSV(workItems);
    } else if (outputType === 'JSON') {
      console.error('JSON not currently supported');
    }
    try {
      await writeFile(outputPath, data);
    } catch (e) {
      console.log(`Error writing jira data to ${outputPath}`);
    }
    console.log(chalk.green('Successful.'));
    console.log(`Results written to ${outputPath}`);
    return;
  } catch (e) {
    throw e;
  }
};
开发者ID:sarita1119,项目名称:jira-to-analytics,代码行数:86,代码来源:cli.ts

示例8: subscribe

    /**
     * Add a subscription to an API.
     */
    public subscribe(clientId: string, subscription: Subscription) {
        if (!this.clients[clientId]) {
            this.logger.error(`Unable to find a client with id '${clientId}'`)
            return
        }

        const subscriptionId = subscription.id
        const parts = subscriptionId.split('.')
        let errMsg
        if (parts.length < 2) {
            errMsg = `Invalid subscription id '${subscriptionId}', should be something like 'api_id.method'`
            this.logger.error(chalk.red(errMsg))

            throw new Error(errMsg)
        }

        const [apiId, apiMethod] = parts
        if (this.apis[apiId] === undefined) {
            errMsg = `Unable to find API matching id '${apiId}'`
            this.logger.error(chalk.red(errMsg))

            throw new Error(errMsg)
        }

        const api = this.apis[apiId]
        if (api.methods[apiMethod] === undefined) {
            errMsg = `Unable to find API method matching '${apiMethod}'`
            this.logger.error(chalk.red(errMsg))

            throw new Error(errMsg)
        }

        const callFn = api.methods[apiMethod]
        if (!isFunction(callFn)) {
            errMsg = `API method '${apiId}.${apiMethod}' MUST be a function`
            this.logger.error(chalk.red(errMsg))

            throw new Error(errMsg)
        }

        if (this.subscriptions[subscriptionId] === undefined) {
            this.subscriptions[subscriptionId] = {
                id: subscriptionId,
                clients: [],
                cached: null,
            }

            this.logger.info(`Added subscription '${subscriptionId}'`)

            if (api.mode === PollMode.Poll) {
                // make an immediate call to avoid waiting for the first interval.
                this.processApiCall(subscriptionId, callFn, subscription.params)
            } else if (api.mode === PollMode.Push) {
                this.logger.info(`Creating producer for '${subscriptionId}'`)
                callFn((data: any) => {
                    this.send(subscriptionId, {
                        id: subscriptionId,
                        data,
                    })
                }, subscription.params)
            }
        }

        // if there is no interval running, create one
        if (!this.subscriptions[subscriptionId].timer && api.mode === PollMode.Poll) {
            this.logger.info(`Creating scheduler for subscription '${subscriptionId}'`)

            this.subscriptions[subscriptionId].timer = setInterval(() => {
                this.processApiCall(subscriptionId, callFn, subscription.params)
            }, this.pollInterval)
        }

        // avoid adding a client for the same API call twice
        if (!this.subscriptions[subscriptionId].clients.includes(clientId)) {
            this.subscriptions[subscriptionId].clients.push(clientId)

            // if there's an available cached response, send it immediately
            if (
                this.subscriptions[subscriptionId].cached !== undefined &&
                this.subscriptions[subscriptionId].cached !== null
            ) {
                this.logger.info(
                    `Subscription ${subscriptionId} has cached response, sending to '${clientId}'`
                )

                this.clients[clientId].emit(
                    MessageType.Data,
                    this.subscriptions[subscriptionId].cached
                )
            }
        }
    }
开发者ID:plouc,项目名称:mozaik,代码行数:95,代码来源:bus.ts

示例9: it

 it('should report on the survived mutant', () => {
   expect(process.stdout.write).to.have.been.calledWith('Mutator: Math\n');
   expect(process.stdout.write).to.have.been.calledWith(chalk.red('-   original line') + '\n');
   expect(process.stdout.write).to.have.been.calledWith(chalk.green('+   mutated line') + '\n');
 });
开发者ID:devlucas,项目名称:stryker,代码行数:5,代码来源:ClearTextReporterSpec.ts

示例10: runCommand

export async function runCommand(config: Configuration): Promise<Error[]> {
  const stats = new StatsCounter()

  // step 0: create working dir
  if (!config.workspace) {
    config.workspace = await createWorkingDir(config.useSystemTempDirectory)
  }

  // step 1: find files
  const filenames = await getFileNames(config)
  if (filenames.length === 0) {
    console.log(chalk.magenta('no Markdown files found'))
    return []
  }

  // step 2: read and parse files
  const ASTs = await Promise.all(filenames.map(readAndParseFile))

  // step 3: find link targets
  const linkTargets = findLinkTargets(ASTs)

  // step 4: extract activities
  const activities = extractActivities(ASTs, config.classPrefix)
  const links = extractImagesAndLinks(ASTs)
  if (activities.length === 0 && links.length === 0) {
    console.log(chalk.magenta('no activities found'))
    return []
  }

  // step 5: execute the ActivityList
  process.chdir(config.workspace)
  const jobs = executeParallel(links, linkTargets, config, stats)
  jobs.push(executeSequential(activities, config, linkTargets, stats))
  const results = (await Promise.all(jobs)).filter(r => r) as Error[]

  // step 6: cleanup
  process.chdir(config.sourceDir)
  if (results.length === 0 && !config.keepTmp) {
    rimraf.sync(config.workspace)
  }

  // step 7: write stats
  let text = '\n'
  let color
  if (results.length === 0) {
    color = chalk.green
    text += chalk.green('Success! ')
  } else {
    color = chalk.red
    text += chalk.red(`${results.length} errors, `)
  }
  text += color(
    `${activities.length + links.length} activities in ${
      filenames.length
    } files`
  )
  if (stats.warnings() > 0) {
    text += color(', ')
    text += chalk.magenta(`${stats.warnings()} warnings`)
  }
  text += color(`, ${stats.duration()}`)
  console.log(chalk.bold(text))
  return results
}
开发者ID:Originate,项目名称:tutorial-runner,代码行数:64,代码来源:run.ts

示例11: printErrorAndExit

export function printErrorAndExit(error: Error) {
  console.error(red((error.stack || error).toString()))
  process.exit(-1)
}
开发者ID:ArchMa9e,项目名称:electron-builder,代码行数:4,代码来源:promise.ts

示例12: printBuildError

 (err: Error) => {
   console.log(chalk.red('Failed to compile.\n'));
   printBuildError(err);
   process.exit(1);
 }
开发者ID:heydoctor,项目名称:medpack,代码行数:5,代码来源:build.ts

示例13: newCommand

export async function newCommand({ workingDir, args, logger }) {
  let type = args['_'][0];
  let name = args['_'][1];
  let contentSrc = args['c'] || args['content'] || "1kLHE2F-ydeTiQtnHKX4PhQy9oSLCTYS0CsoNr5zjx1c";

  // Check for help/all args present
  if (args['h'] || args['help']) {
    console.log(
      `\n${chalk.blue("lede new [type] [name]")}
${chalk.blue('lede new')} creates a new entity of type ${chalk.blue('[type]')} with name ${chalk.blue('[name]')}
Valid types: project|bit
Options: -p --path
  Directory where ${chalk.blue(
        'lede new')} should create the new type. Defaults to env var LEDE_HOME, falls back to '~/LedeProjects'\n`
    );
    return;
  }
  if (!type || !name) {
    console.log(`${chalk.red('[type]')} and ${chalk.red('[name]')} are required parameters -- type ${chalk.blue(
      'lede new -h')} for help`);
    return;
  }

  // Creation logic
  switch (type.toLowerCase()) {
    case 'project':
      let pathToCreate = resolve(workingDir, args['_'][1]);
      let paths = await globProm(`${workingDir}/*`);
      if (paths.indexOf(pathToCreate) > -1) {
        console.log(
          `Project "${chalk.red(name)}" already exists. Use ${chalk.blue('lede ls')} to see all projects.`);
        break;
      } else {
        try {
          console.log("Creating project");
          await copyProm(resolve(__dirname, '../..', 'templates/project'), resolve(workingDir, name));
          await writeProm(
            makeSettings(name, contentSrc),
            resolve(workingDir, name, 'projectSettings.js')
         );
          console.log(`Created ${chalk.green(resolve(workingDir, name))}`)
        } catch(e) {
          console.log(e)
        }
      }
      break;
    case 'bit':
      try {
        let status = await existsProm(resolve(process.cwd(), 'projectSettings.js'))
        if (status.file) {
          await copyProm(resolve(__dirname, '../../templates/bit'), resolve(process.cwd(), 'bits', name))
        }
      } catch (e) {
        if (e.code !== 'ENOENT') {
          console.log(e)
        } else {
          console.log(
`${chalk.blue('lede new bit [name]')} should be run from inside a Lede Project. Use the ${chalk.blue('lede cd')} command to change to a project directory`
          )
        }
      }
      break;
    default:
      console.log(`${chalk.red(type)} is not a valid ${chalk.red('[type]')} param -- type ${chalk.blue('lede new -h')} for help`)

  }
}
开发者ID:tbtimes,项目名称:ledeTwo,代码行数:67,代码来源:newCommand.ts

示例14: log

 .catch(error => {
   log(chalk.red(error.stack));
   process.exit(1);
 });
开发者ID:codeaudit,项目名称:graphql-faker,代码行数:4,代码来源:index.ts

示例15: _handle_OpenSecureChannelRequest

    private _handle_OpenSecureChannelRequest(message: Message, callback: ErrorCallback) {

        const request = message.request as OpenSecureChannelRequest;
        const requestId: number = message.requestId;
        assert(request.schema.name === "OpenSecureChannelRequest");
        assert(requestId !== 0 && requestId > 0);

        this.clientNonce = request.clientNonce;

        this._set_lifetime(request.requestedLifetime);

        this._prepare_security_token(request);

        let serviceResult: StatusCode = StatusCodes.Good;

        const cryptoFactory = this.messageBuilder.cryptoFactory;
        if (cryptoFactory) {
            // serverNonce: A random number that shall not be used in any other request. A new
            //    serverNonce shall be generated for each time a SecureChannel is renewed.
            //    This parameter shall have a length equal to key size used for the symmetric
            //    encryption algorithm that is identified by the securityPolicyUri.
            this.serverNonce = crypto.randomBytes(cryptoFactory.symmetricKeyLength);

            if (this.clientNonce.length !== this.serverNonce.length) {
                console.log(
                  chalk.red("warning client Nonce length doesn't match server nonce length"),
                  this.clientNonce.length,
                  " !== ",
                  this.serverNonce.length
                );
                // what can we do
                // - just ignore it ?
                // - or adapt serverNonce length to clientNonce Length ?
                // xx self.serverNonce = crypto.randomBytes(self.clientNonce.length);
                // - or adapt clientNonce length to serverNonce Length ?
                // xx self.clientNonce = self.clientNonce.slice(0,self.serverNonce.length);
                //
                // - or abort connection ? << LET BE SAFE AND CHOOSE THIS ONE !
                serviceResult = StatusCodes.BadSecurityModeRejected; // ToDo check code
            }
            // expose derivedKey to use for symmetric sign&encrypt
            // to help us decrypting and verifying messages received from client
            this.derivedKeys = computeDerivedKeys(cryptoFactory, this.serverNonce, this.clientNonce);
        }

        const derivedClientKeys = this.derivedKeys ? this.derivedKeys.derivedClientKeys : null;
        this.messageBuilder.pushNewToken(this.securityToken, derivedClientKeys);

        // let prepare self.securityHeader;
        this.securityHeader = this._prepare_security_header(request, message);

        // xx const asymmHeader = this.securityHeader as AsymmetricAlgorithmSecurityHeader;

        assert(this.securityHeader);

        const derivedServerKeys = this.derivedKeys ? this.derivedKeys.derivedServerKeys : undefined;

        this.messageChunker.update({
            // for OPN
            securityHeader: this.securityHeader,

            // derived keys for symmetric encryption of standard MSG
            // to sign and encrypt MSG sent to client
            derivedKeys: derivedServerKeys
        });

        const response: Response = new OpenSecureChannelResponse({
            responseHeader: { serviceResult },

            securityToken: this.securityToken,
            serverNonce: this.serverNonce || undefined,
            serverProtocolVersion: this.protocolVersion
        });

        let description;

        // If the SecurityMode is not None then the Server shall verify that a SenderCertificate and a
        // ReceiverCertificateThumbprint were specified in the SecurityHeader.
        if (this.securityMode !== MessageSecurityMode.None) {
            if (!this.clientSecurityHeader) {
                throw new Error("Internal Error");
            }
            if (!this._check_receiverCertificateThumbprint(this.clientSecurityHeader)) {
                description =
                  "Server#OpenSecureChannelRequest : Invalid receiver certificate thumbprint : the thumbprint doesn't match server certificate !";
                console.log(chalk.cyan(description));
                response.responseHeader.serviceResult = StatusCodes.BadCertificateInvalid;
            }
        }
        this.send_response("OPN", response, message, (/*err*/) => {

            const responseHeader = response.responseHeader;

            if (responseHeader.serviceResult !== StatusCodes.Good) {
                console.log(
                  "OpenSecureChannelRequest Closing communication ",
                  responseHeader.serviceResult.toString()
                );
                this.close();
            }
//.........这里部分代码省略.........
开发者ID:node-opcua,项目名称:node-opcua,代码行数:101,代码来源:server_secure_channel_layer.ts


注:本文中的chalk.red函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。