Best JavaScript code snippet using puppeteer
certificate-raw.js
Source:certificate-raw.js
1/*2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the "License").5 * You may not use this file except in compliance with the License.6 * A copy of the License is located at7 *8 * http://aws.amazon.com/apache2.09 *10 * or in the "license" file accompanying this file. This file is distributed11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either12 * express or implied. See the License for the specific language governing13 * permissions and limitations under the License.14 */15/* eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }] */16import { getRegionalAcm } from './aws';17import { deepEqualObjectProperties, fnFail, mayBeArn, isObjectEmpty, sleep } from './util';18import { logDebug, logInfo } from './log';19import { CustomResource } from './custom-resource';20function convertTags(tags) {21 return Object.entries(tags).map(([Key, Value]) => ({ Key, Value }));22}23function computeTagsChange(tags, oldTags) {24 const tagsToRemove = {};25 const tagsToAdd = {};26 const tagNames = new Set();27 Object.keys(tags).forEach(name => tagNames.add(name));28 const oldTagNames = new Set();29 Object.keys(oldTags).forEach(name => oldTagNames.add(name));30 for (const name of oldTagNames) {31 if (!tagNames.has(name)) {32 tagsToRemove[name] = oldTags[name];33 }34 }35 for (const name of tagNames) {36 tagsToAdd[name] = tags[name]; // update unconditionally!37 }38 return { tagsToRemove, tagsToAdd };39}40class CertificateRaw extends CustomResource {41 // constructor(event, workspace) {42 // super(event, workspace);43 // }44 pickProperties(from) {45 // return ({ ...({ DomainName, HostedZoneId, Tags = {} } = from) }); // why is this not working???46 const { DomainName, SubjectAlternativeNames, Tags = {}, Region } = from;47 return { DomainName, SubjectAlternativeNames, Tags, Region };48 }49 validateProperties(props) {50 ['DomainName'].forEach(prop => {51 if (props[prop] === undefined) fnFail(`Missing '${prop}' property`);52 if (typeof props[prop] !== 'string') fnFail(`Property ${prop} should be a string`);53 });54 const san = props.SubjectAlternativeNames;55 if (san) {56 if (!Array.isArray(san)) fnFail(`SubjectAlternativeNames should be an array; got ${JSON.stringify(san)}`);57 san.forEach(entry => {58 if (typeof entry !== 'string')59 fnFail(`Entries in SubjectAlternativeNames should be strings; '${JSON.stringify(entry)}' isn not a string`);60 });61 }62 }63 async waitForNotInUse(CertificateArn, acm) {64 const isInUse = async idx => {65 // call describeCertificate return InUseBy.length !== 066 const result = await acm.describeCertificate({ CertificateArn }).promise();67 logDebug(`waitForNotInUse: idx-${idx}: describeCertificate: result: ${JSON.stringify(result)}`);68 const { Certificate: certificate } = result;69 const { InUseBy: inUseBy } = certificate;70 return inUseBy.length !== 0;71 };72 // this is a polling affair...73 // call describeCertificate until InUseBy is an empty array74 // worst case scenario it will take 15 mins; alas, the lambda execution is also 15 minutes; race condition?75 // for the first 1 minutes check once every 10 seconds76 for (let idx = 0; idx < 6; ++idx) {77 // 6 times78 if (!(await isInUse(idx))) return;79 await sleep(10000); // every 10 seconds80 }81 // for next 12 minutes check once every 60 seconds82 for (let idx = 6; idx < 6 + 12; ++idx) {83 // 12 times84 if (!(await isInUse(idx))) return;85 await sleep(60000); // every 60 seconds86 }87 // for next 1 minutes check once every 10 seconds88 for (let idx = 6 + 12; idx < 6 + 12 + 6; ++idx) {89 // 6 times90 if (!(await isInUse(idx))) return;91 await sleep(10000); // every 10 seconds92 }93 // for next 1 minutes check once every 1 seconds94 for (let idx = 6 + 12 + 6; idx < 6 + 12 + 6 + 60 - 1; ++idx) {95 // 59 times96 if (!(await isInUse(idx))) return;97 await sleep(1000); // every 1 second98 }99 // try one last time100 if (!(await isInUse(6 + 12 + 6 + 60))) return;101 // by the time got here almost 15 minutes passed (all but a bit less than a second)102 // if got here fail103 fnFail('timeout in waiting for certificate not be in use in preparation for deletion');104 }105 needNewResource(properties, oldProperties) {106 return properties.DomainName !== oldProperties.DomainName || properties.Region !== oldProperties.Region;107 }108 updateResourceInPlace(properties, oldProperties) {109 return !deepEqualObjectProperties(properties.Tags || {}, oldProperties.Tags || {});110 }111 async create() {112 logDebug('In CertificateRaw::create');113 const workspace = this.workspace;114 logDebug(`Workspace is ${JSON.stringify(workspace)}`);115 const { requestId, stackArn } = workspace;116 const properties = this.pickProperties(workspace.properties || {});117 logDebug(`Props: ${JSON.stringify(properties)}`);118 this.validateProperties(properties);119 // fetch stackTags120 const stackTags = await this.fetchStackTags(stackArn);121 // request the certificate122 const { DomainName, SubjectAlternativeNames, Tags } = properties;123 const domainNames = new Set([DomainName, ...(SubjectAlternativeNames || [])]);124 const requestCertificateParams = {125 DomainName,126 DomainValidationOptions: [...domainNames].map(item => ({127 DomainName: item,128 ValidationDomain: item,129 })),130 ValidationMethod: 'DNS',131 SubjectAlternativeNames,132 IdempotencyToken: requestId,133 Tags: convertTags({ ...stackTags, ...Tags }),134 };135 const acm = getRegionalAcm(properties);136 const { CertificateArn } = await acm.requestCertificate(requestCertificateParams).promise();137 logDebug(`Requested certificate with ARN: '${CertificateArn}'`);138 workspace.physicalResourceId = CertificateArn;139 }140 async update() {141 logDebug('In CertificateRaw::update');142 const workspace = this.workspace;143 logDebug(`Workspace is ${JSON.stringify(workspace)}`);144 const { physicalResourceId: CertificateArn } = workspace;145 const properties = this.pickProperties(workspace.properties || {});146 logDebug(`Props: ${JSON.stringify(properties)}`);147 this.validateProperties(properties);148 const oldProperties = this.pickProperties(workspace.oldProperties || {});149 logDebug(`OldProps: ${JSON.stringify(oldProperties)}`);150 if (this.needNewResource(properties, oldProperties)) {151 logDebug('Creating new resource');152 // wipe off the old resourceId, in case creating a new one fails153 delete workspace.physicalResourceId;154 await this.create();155 } else if (this.updateResourceInPlace(properties, oldProperties)) {156 logDebug('Updating resource in place');157 // ignoring stack tags158 const { tagsToRemove, tagsToAdd } = computeTagsChange(properties.Tags || {}, oldProperties.Tags || {});159 const acm = getRegionalAcm(properties);160 if (!isObjectEmpty(tagsToRemove)) {161 // Remove tags that must vanish162 logDebug(`tagsToRemove: ${JSON.stringify(tagsToRemove)}`);163 const removeTagsParams = {164 CertificateArn,165 Tags: convertTags(tagsToRemove),166 };167 await acm.removeTagsFromCertificate(removeTagsParams).promise();168 logDebug('Tags removed');169 }170 if (!isObjectEmpty(tagsToAdd)) {171 // update/create tags that are new or changed172 logDebug(`tagsToAdd: ${JSON.stringify(tagsToAdd)}`);173 const addTagsParams = {174 CertificateArn,175 Tags: convertTags(tagsToAdd), // this will not update stack tags; may or may not consider that176 };177 await acm.addTagsToCertificate(addTagsParams).promise();178 logDebug('Tags added/updated');179 }180 } else {181 logDebug('No meaningful properties difference; nothing to update!');182 }183 }184 async remove() {185 logDebug('In CertificateRaw::remove');186 const workspace = this.workspace;187 logDebug(`Workspace is ${JSON.stringify(workspace)}`);188 const { physicalResourceId: CertificateArn } = workspace;189 const properties = this.pickProperties(workspace.properties || {});190 logDebug(`Props: ${JSON.stringify(properties)}`);191 this.validateProperties(properties);192 logDebug(`Initiate deleting certificate with ARN: '${CertificateArn}'`);193 if (mayBeArn(CertificateArn)) {194 const acm = getRegionalAcm(properties);195 await this.waitForNotInUse(CertificateArn, acm);196 await acm.deleteCertificate({ CertificateArn }).promise();197 } else {198 logInfo('Not a valid ARN; skip deleting');199 }200 }201}...
certificateCreateParameters.js
Source:certificateCreateParameters.js
1/*2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for4 * license information.5 *6 * Code generated by Microsoft (R) AutoRest Code Generator.7 * Changes may cause incorrect behavior and will be lost if the code is8 * regenerated.9 */10'use strict';11const models = require('./index');12/**13 * The certificate create parameters.14 *15 */16class CertificateCreateParameters {17 /**18 * Create a CertificateCreateParameters.19 * @member {object} [certificatePolicy] The management policy for the20 * certificate.21 * @member {string} [certificatePolicy.id] The certificate id.22 * @member {object} [certificatePolicy.keyProperties] Properties of the key23 * backing a certificate.24 * @member {boolean} [certificatePolicy.keyProperties.exportable] Indicates25 * if the private key can be exported.26 * @member {string} [certificatePolicy.keyProperties.keyType] The type of key27 * pair to be used for the certificate. Possible values include: 'EC',28 * 'EC-HSM', 'RSA', 'RSA-HSM', 'oct'29 * @member {number} [certificatePolicy.keyProperties.keySize] The key size in30 * bits. For example: 2048, 3072, or 4096 for RSA.31 * @member {boolean} [certificatePolicy.keyProperties.reuseKey] Indicates if32 * the same key pair will be used on certificate renewal.33 * @member {string} [certificatePolicy.keyProperties.curve] Elliptic curve34 * name. For valid values, see JsonWebKeyCurveName. Possible values include:35 * 'P-256', 'P-384', 'P-521', 'P-256K'36 * @member {object} [certificatePolicy.secretProperties] Properties of the37 * secret backing a certificate.38 * @member {string} [certificatePolicy.secretProperties.contentType] The39 * media type (MIME type).40 * @member {object} [certificatePolicy.x509CertificateProperties] Properties41 * of the X509 component of a certificate.42 * @member {string} [certificatePolicy.x509CertificateProperties.subject] The43 * subject name. Should be a valid X509 distinguished Name.44 * @member {array} [certificatePolicy.x509CertificateProperties.ekus] The45 * enhanced key usage.46 * @member {object}47 * [certificatePolicy.x509CertificateProperties.subjectAlternativeNames] The48 * subject alternative names.49 * @member {array}50 * [certificatePolicy.x509CertificateProperties.subjectAlternativeNames.emails]51 * Email addresses.52 * @member {array}53 * [certificatePolicy.x509CertificateProperties.subjectAlternativeNames.dnsNames]54 * Domain names.55 * @member {array}56 * [certificatePolicy.x509CertificateProperties.subjectAlternativeNames.upns]57 * User principal names.58 * @member {array} [certificatePolicy.x509CertificateProperties.keyUsage]59 * List of key usages.60 * @member {number}61 * [certificatePolicy.x509CertificateProperties.validityInMonths] The62 * duration that the ceritifcate is valid in months.63 * @member {array} [certificatePolicy.lifetimeActions] Actions that will be64 * performed by Key Vault over the lifetime of a certificate.65 * @member {object} [certificatePolicy.issuerParameters] Parameters for the66 * issuer of the X509 component of a certificate.67 * @member {string} [certificatePolicy.issuerParameters.name] Name of the68 * referenced issuer object or reserved names; for example, 'Self' or69 * 'Unknown'.70 * @member {string} [certificatePolicy.issuerParameters.certificateType] Type71 * of certificate to be requested from the issuer provider.72 * @member {boolean}73 * [certificatePolicy.issuerParameters.certificateTransparency] Indicates if74 * the certificates generated under this policy should be published to75 * certificate transparency logs.76 * @member {object} [certificatePolicy.attributes] The certificate77 * attributes.78 * @member {string} [certificatePolicy.attributes.recoveryLevel] Reflects the79 * deletion recovery level currently in effect for certificates in the80 * current vault. If it contains 'Purgeable', the certificate can be81 * permanently deleted by a privileged user; otherwise, only the system can82 * purge the certificate, at the end of the retention interval. Possible83 * values include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable',84 * 'Recoverable+ProtectedSubscription'85 * @member {object} [certificateAttributes] The attributes of the certificate86 * (optional).87 * @member {string} [certificateAttributes.recoveryLevel] Reflects the88 * deletion recovery level currently in effect for certificates in the89 * current vault. If it contains 'Purgeable', the certificate can be90 * permanently deleted by a privileged user; otherwise, only the system can91 * purge the certificate, at the end of the retention interval. Possible92 * values include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable',93 * 'Recoverable+ProtectedSubscription'94 * @member {object} [tags] Application specific metadata in the form of95 * key-value pairs.96 */97 constructor() {98 }99 /**100 * Defines the metadata of CertificateCreateParameters101 *102 * @returns {object} metadata of CertificateCreateParameters103 *104 */105 mapper() {106 return {107 required: false,108 serializedName: 'CertificateCreateParameters',109 type: {110 name: 'Composite',111 className: 'CertificateCreateParameters',112 modelProperties: {113 certificatePolicy: {114 required: false,115 serializedName: 'policy',116 type: {117 name: 'Composite',118 className: 'CertificatePolicy'119 }120 },121 certificateAttributes: {122 required: false,123 serializedName: 'attributes',124 type: {125 name: 'Composite',126 className: 'CertificateAttributes'127 }128 },129 tags: {130 required: false,131 serializedName: 'tags',132 type: {133 name: 'Dictionary',134 value: {135 required: false,136 serializedName: 'StringElementType',137 type: {138 name: 'String'139 }140 }141 }142 }143 }144 }145 };146 }147}...
certificatePolicy.js
Source:certificatePolicy.js
1/*2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for4 * license information.5 *6 * Code generated by Microsoft (R) AutoRest Code Generator.7 * Changes may cause incorrect behavior and will be lost if the code is8 * regenerated.9 */10'use strict';11const models = require('./index');12/**13 * Management policy for a certificate.14 *15 */16class CertificatePolicy {17 /**18 * Create a CertificatePolicy.19 * @member {string} [id] The certificate id.20 * @member {object} [keyProperties] Properties of the key backing a21 * certificate.22 * @member {boolean} [keyProperties.exportable] Indicates if the private key23 * can be exported.24 * @member {string} [keyProperties.keyType] The type of key pair to be used25 * for the certificate. Possible values include: 'EC', 'EC-HSM', 'RSA',26 * 'RSA-HSM', 'oct'27 * @member {number} [keyProperties.keySize] The key size in bits. For28 * example: 2048, 3072, or 4096 for RSA.29 * @member {boolean} [keyProperties.reuseKey] Indicates if the same key pair30 * will be used on certificate renewal.31 * @member {string} [keyProperties.curve] Elliptic curve name. For valid32 * values, see JsonWebKeyCurveName. Possible values include: 'P-256',33 * 'P-384', 'P-521', 'P-256K'34 * @member {object} [secretProperties] Properties of the secret backing a35 * certificate.36 * @member {string} [secretProperties.contentType] The media type (MIME37 * type).38 * @member {object} [x509CertificateProperties] Properties of the X50939 * component of a certificate.40 * @member {string} [x509CertificateProperties.subject] The subject name.41 * Should be a valid X509 distinguished Name.42 * @member {array} [x509CertificateProperties.ekus] The enhanced key usage.43 * @member {object} [x509CertificateProperties.subjectAlternativeNames] The44 * subject alternative names.45 * @member {array} [x509CertificateProperties.subjectAlternativeNames.emails]46 * Email addresses.47 * @member {array}48 * [x509CertificateProperties.subjectAlternativeNames.dnsNames] Domain names.49 * @member {array} [x509CertificateProperties.subjectAlternativeNames.upns]50 * User principal names.51 * @member {array} [x509CertificateProperties.keyUsage] List of key usages.52 * @member {number} [x509CertificateProperties.validityInMonths] The duration53 * that the ceritifcate is valid in months.54 * @member {array} [lifetimeActions] Actions that will be performed by Key55 * Vault over the lifetime of a certificate.56 * @member {object} [issuerParameters] Parameters for the issuer of the X50957 * component of a certificate.58 * @member {string} [issuerParameters.name] Name of the referenced issuer59 * object or reserved names; for example, 'Self' or 'Unknown'.60 * @member {string} [issuerParameters.certificateType] Type of certificate to61 * be requested from the issuer provider.62 * @member {boolean} [issuerParameters.certificateTransparency] Indicates if63 * the certificates generated under this policy should be published to64 * certificate transparency logs.65 * @member {object} [attributes] The certificate attributes.66 * @member {string} [attributes.recoveryLevel] Reflects the deletion recovery67 * level currently in effect for certificates in the current vault. If it68 * contains 'Purgeable', the certificate can be permanently deleted by a69 * privileged user; otherwise, only the system can purge the certificate, at70 * the end of the retention interval. Possible values include: 'Purgeable',71 * 'Recoverable+Purgeable', 'Recoverable',72 * 'Recoverable+ProtectedSubscription'73 */74 constructor() {75 }76 /**77 * Defines the metadata of CertificatePolicy78 *79 * @returns {object} metadata of CertificatePolicy80 *81 */82 mapper() {83 return {84 required: false,85 serializedName: 'CertificatePolicy',86 type: {87 name: 'Composite',88 className: 'CertificatePolicy',89 modelProperties: {90 id: {91 required: false,92 readOnly: true,93 serializedName: 'id',94 type: {95 name: 'String'96 }97 },98 keyProperties: {99 required: false,100 serializedName: 'key_props',101 type: {102 name: 'Composite',103 className: 'KeyProperties'104 }105 },106 secretProperties: {107 required: false,108 serializedName: 'secret_props',109 type: {110 name: 'Composite',111 className: 'SecretProperties'112 }113 },114 x509CertificateProperties: {115 required: false,116 serializedName: 'x509_props',117 type: {118 name: 'Composite',119 className: 'X509CertificateProperties'120 }121 },122 lifetimeActions: {123 required: false,124 serializedName: 'lifetime_actions',125 type: {126 name: 'Sequence',127 element: {128 required: false,129 serializedName: 'LifetimeActionElementType',130 type: {131 name: 'Composite',132 className: 'LifetimeAction'133 }134 }135 }136 },137 issuerParameters: {138 required: false,139 serializedName: 'issuer',140 type: {141 name: 'Composite',142 className: 'IssuerParameters'143 }144 },145 attributes: {146 required: false,147 serializedName: 'attributes',148 type: {149 name: 'Composite',150 className: 'CertificateAttributes'151 }152 }153 }154 }155 };156 }157}...
acm-manager.js
Source:acm-manager.js
1'use strict';2const ACM = require('aws-sdk/clients/acm'),3 R53 = require('aws-sdk/clients/route53'),4 logger = require('./logger');5function sleep (ms) {6 return new Promise(resolve => {7 setTimeout(resolve, ms);8 });9}10function checkIfCertificateIsIssued ({ cfg }) {11 if (cfg.service && cfg.service.certificateArn) {12 cfg.certificateArn = cfg.service.certificateArn;13 return new Promise((resolve) => { return resolve({ cfg, status: 'EXISTS' }); });14 }15 logger.action(`Checking if existing certificate has already been issued...`);16 const acm = new ACM({ region: cfg.region });17 return acm.listCertificates({ CertificateStatuses: ['ISSUED'] }).promise()18 .then((data) => {19 const matchingCerts = data.CertificateSummaryList.filter((cert) => { return cert.DomainName === cfg.certificate.DomainName; });20 if (matchingCerts.length > 0) {21 if (cfg.certificate.SubjectAlternativeNames === undefined) {22 cfg.certificateArn = matchingCerts[0].CertificateArn;23 return { cfg, status: 'EXISTS' };24 }25 logger.result(`Found ${matchingCerts.length} candidate.`);26 logger.action('Confirming SubjectAlternativeNames also match...');27 return Promise.all(matchingCerts.map((cert) => { return acm.describeCertificate({ CertificateArn: cert.CertificateArn }).promise(); }))28 .then((datas) => {29 const exactMatch = datas.filter((data) => {30 if (data.Certificate.SubjectAlternativeNames === undefined) return false;31 const sanMinusDomainName = data.Certificate.SubjectAlternativeNames.filter((name) => { return name !== cfg.certificate.DomainName; });32 return (sanMinusDomainName.length === cfg.certificate.SubjectAlternativeNames.length && sanMinusDomainName.every((v, i) => v === cfg.certificate.SubjectAlternativeNames[i]));33 });34 if (exactMatch.length === 1) {35 cfg.certificateArn = exactMatch[0].Certificate.CertificateArn;36 logger.result(cfg.certificateArn);37 return { cfg, status: 'EXISTS' };38 }39 logger.result('No match for SAN.');40 return { cfg, status: 'DOESNOTEXIST' };41 });42 }43 logger.result('No match for domain name.');44 return { cfg, status: 'DOESNOTEXIST' };45 });46}47module.exports.ensureCertificateIsIssued = function ({ cfg }) {48 if (!cfg.service || !cfg.service.hostedZoneId) return { cfg };49 if (cfg.service && cfg.service.certificateArn) {50 cfg.certificateArn = cfg.service.certificateArn;51 return new Promise((resolve) => { return resolve({ cfg }); });52 }53 return checkIfCertificateIsIssued({ cfg })54 .then(({ cfg, status }) => {55 if (status === 'EXISTS') return { cfg };56 const acm = new ACM({ region: cfg.region });57 const r53 = new R53({ region: cfg.region });58 logger.action('Requesting certificate...');59 return acm.requestCertificate({60 DomainName: cfg.certificate.DomainName,61 DomainValidationOptions: cfg.certificate.DomainValidationOptions,62 SubjectAlternativeNames: cfg.certificate.SubjectAlternativeNames,63 ValidationMethod: 'DNS'64 }).promise()65 .then(function (data) {66 cfg.certificateArn = data.CertificateArn;67 logger.result(cfg.certificateArn);68 logger.action('Waiting a bit for AWS to generate validation records...');69 return sleep(10000);70 })71 .then(() => {72 logger.result('Proceeding.');73 return acm.describeCertificate({ CertificateArn: cfg.certificateArn }).promise();74 })75 .then((certData) => {76 logger.action('Creating validation records...');77 let validationChanges = [];78 let namesToCreate = [];79 certData.Certificate.DomainValidationOptions.forEach((option) => {80 if (namesToCreate.indexOf(option.ResourceRecord.Name) >= 0) return;81 namesToCreate.push(option.ResourceRecord.Name);82 const change = {83 Action: 'UPSERT',84 ResourceRecordSet: {85 Name: option.ResourceRecord.Name,86 ResourceRecords: [{ Value: option.ResourceRecord.Value }],87 TTL: 300,88 Type: option.ResourceRecord.Type89 }90 };91 validationChanges.push(change);92 });93 const params = {94 ChangeBatch: {95 Changes: validationChanges,96 Comment: 'Created by ecs-publish'97 },98 HostedZoneId: cfg.service.hostedZoneId99 };100 return r53.changeResourceRecordSets(params).promise();101 })102 .then((changeData) => {103 logger.result(`Status: ${changeData.ChangeInfo.Status}`);104 logger.action('It can take 30 minutes or longer for the changes to propagate and for AWS to validate the domain and issue the certificate.');105 return { cfg };106 });107 });108};109module.exports.confirmCertificateIsIssued = function ({ cfg }) {110 if (!cfg.service || !cfg.service.hostedZoneId) return { cfg };111 return checkIfCertificateIsIssued({ cfg })112 .then(({ cfg, status }) => {113 if (status === 'EXISTS') return { cfg };114 throw new Error('Certificate not issued. Please obtain a certificate using \'ecs-publish obtain-certificate\'');115 });...
acm.js
Source:acm.js
1'use strict'2var debug = require('debug')('aws-promises:acm')3var { arnMask, awsify } = require('../utils/awsify')4var certificateArnMask = arnMask({ type: 'certificate' })5const acmPromises = awsify('ACM', {6 deleteCertificate: null,7 describeCertificate: 'Certificate',8 listCertificates: 'CertificateSummaryList',9 requestCertificate: 'CertificateArn'10})11function ACM (options) {12 const acm = acmPromises(options)13 return {14 describeCertificate (domainOrCertArn) {15 return this.getCertificateArn(domainOrCertArn)16 .then(CertificateArn =>17 (CertificateArn)18 ? acm.describeCertificate({ CertificateArn })19 : null20 )21 },22 deleteCertificate (domainOrCertArn) {23 return this.getCertificateArn(domainOrCertArn)24 .then(CertificateArn => {25 if (CertificateArn) {26 debug(`Deleting Certificate [${CertificateArn}]`)27 return acm.deleteCertificate({ CertificateArn })28 .then(() => {29 debug(`Successfully deleted Certificate [${CertificateArn}]`)30 })31 } else {32 debug(`Certificate [${domainOrCertArn}] does not exist`)33 }34 })35 },36 getCertificateArn (domainOrCertArn) {37 if (certificateArnMask.test(domainOrCertArn)) {38 return Promise.resolve(domainOrCertArn)39 } else {40 var domain = domainOrCertArn.toLowerCase()41 return acm.listCertificates({42 test: certificate => (certificate.DomainName.toLowerCase() === domain)43 })44 .then(certificate => certificate && certificate.CertificateArn)45 }46 },47 listCertificates (domain) {48 var result = acm.listCertificates()49 if (domain) {50 domain = domain.toLowerCase()51 result = result52 .then(certificates => certificates.filter(certificate => certificate.DomainName.toLowerCase() === domain))53 }54 return result55 },56 requestCertificate (DomainName, subdomains, ValidationDomain) {57 return this.getCertificateArn(DomainName)58 .then(CertificateArn =>59 (CertificateArn)60 ? this.describeCertificate(CertificateArn)61 .then(Certificate =>62 (subdomains.find(subdomain => Certificate.SubjectAlternativeNames.indexOf(`*.${subdomain}.${DomainName}`) < 0))63 ? null64 : Certificate65 )66 : null67 )68 .then(Certificate => {69 if (Certificate) {70 debug(`Certificate already exists [${Certificate.CertificateArn}]`)71 return Certificate72 } else {73 var params = { DomainName }74 if (!(subdomains instanceof Array)) {75 subdomains = subdomains ? [subdomains] : []76 }77 params.SubjectAlternativeNames = subdomains.map(subdomain => `*.${subdomain}.${DomainName}`)78 params.SubjectAlternativeNames.unshift(`*.${DomainName}`)79 if (ValidationDomain) {80 params.DomainValidationOptions = [{81 DomainName,82 ValidationDomain83 }]84 }85 debug(`Creating Certificate [${DomainName}]`)86 return acm.requestCertificate(params)87 .then(CertificateArn => {88 debug(`Successfully created Certificate [${CertificateArn}]`)89 return this.describeCertificate(CertificateArn)90 })91 }92 })93 }94 }95}...
certificate.js
Source:certificate.js
1import Ember from 'ember';2import Resource from 'ember-api-store/models/resource';3export default Resource.extend({4 modalService: Ember.inject.service('modal'),5 actions: {6 edit: function() {7 this.get('modalService').toggleModal('edit-certificate', this);8 },9 },10 availableActions: function() {11 var a = this.get('actionLinks');12 if ( !a )13 {14 return [];15 }16 var choices = [17 { label: 'action.remove', icon: 'icon icon-trash', action: 'promptDelete', enabled: !!a.remove, altAction: 'delete' },18 { label: 'action.restore', icon: 'icon icon-medicalcross', action: 'restore', enabled: !!a.restore },19 { label: 'action.purge', icon: '', action: 'purge', enabled: !!a.purge },20 { divider: true },21 { label: 'action.viewInApi', icon: 'icon icon-external-link', action: 'goToApi', enabled: true },22 { divider: true },23 { label: 'action.edit', icon: 'icon icon-edit', action: 'edit', enabled: !!a.update },24 ];25 return choices;26 }.property('actionLinks.{remove,restore,purge,update}'),27 issuedDate: function() {28 return new Date(this.get('issuedAt'));29 }.property('issuedAt'),30 expiresDate: function() {31 return new Date(this.get('expiresAt'));32 }.property('expiresAt'),33 expiresSoon: function() {34 var diff = (this.get('expiresDate')).getTime() - (new Date()).getTime();35 var days = diff/(86400*1000);36 return days <= 8;37 }.property('expiresDate'),38 displayIssuer: function() {39 return (this.get('issuer')||'').split(/,/)[0].replace(/^CN=/i,'');40 }.property('issuer'),41 isValid: function() {42 var now = new Date();43 return this.get('expiresDate') > now && this.get('issuedDate') < now;44 }.property('expiresDate','issuedDate'),45 displaySans: function() {46 // subjectAlternativeNames can be null:47 return (this.get('subjectAlternativeNames')||[])48 .slice()49 .removeObject(this.get('CN'))50 .filter((san) => {51 return (san+'').indexOf('@') === -1;52 });53 }.property('CN','subjectAlternativeNames.[]'),54 countableSans: function() {55 var sans = this.get('displaySans').slice();56 if ( this.get('CN') )57 {58 sans.pushObject(this.get('CN'));59 }60 var commonBases = sans.filter((name) => {61 return name.indexOf('*.') === 0 || name.indexOf('www.') === 0;62 }).map((name) => {63 return name.substr(2);64 });65 return this.get('displaySans').slice().removeObjects(commonBases);66 }.property('displaySans.[]','CN'),67 displayDetailedName: function() {68 var name = (this.get('name') || '('+this.get('id')+')');69 var str = name;70 var cn = this.get('CN');71 var sans = this.get('countableSans.length');72 var more = '';73 if ( cn )74 {75 if ( cn !== name )76 {77 more += cn;78 }79 if ( sans > 0 )80 {81 more += ' + ' + sans + ' other' + (sans === 1 ? '' : 's');82 }83 }84 if ( more )85 {86 str += ' (' + more + ')';87 }88 return str;89 }.property('id','name','CN','countableSans.length')...
x509CertificateProperties.js
Source:x509CertificateProperties.js
1/*2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for4 * license information.5 *6 * Code generated by Microsoft (R) AutoRest Code Generator.7 * Changes may cause incorrect behavior and will be lost if the code is8 * regenerated.9 */10'use strict';11const models = require('./index');12/**13 * Properties of the X509 component of a certificate.14 *15 */16class X509CertificateProperties {17 /**18 * Create a X509CertificateProperties.19 * @member {string} [subject] The subject name. Should be a valid X50920 * distinguished Name.21 * @member {array} [ekus] The enhanced key usage.22 * @member {object} [subjectAlternativeNames] The subject alternative names.23 * @member {array} [subjectAlternativeNames.emails] Email addresses.24 * @member {array} [subjectAlternativeNames.dnsNames] Domain names.25 * @member {array} [subjectAlternativeNames.upns] User principal names.26 * @member {array} [keyUsage] List of key usages.27 * @member {number} [validityInMonths] The duration that the ceritifcate is28 * valid in months.29 */30 constructor() {31 }32 /**33 * Defines the metadata of X509CertificateProperties34 *35 * @returns {object} metadata of X509CertificateProperties36 *37 */38 mapper() {39 return {40 required: false,41 serializedName: 'X509CertificateProperties',42 type: {43 name: 'Composite',44 className: 'X509CertificateProperties',45 modelProperties: {46 subject: {47 required: false,48 serializedName: 'subject',49 type: {50 name: 'String'51 }52 },53 ekus: {54 required: false,55 serializedName: 'ekus',56 type: {57 name: 'Sequence',58 element: {59 required: false,60 serializedName: 'StringElementType',61 type: {62 name: 'String'63 }64 }65 }66 },67 subjectAlternativeNames: {68 required: false,69 serializedName: 'sans',70 type: {71 name: 'Composite',72 className: 'SubjectAlternativeNames'73 }74 },75 keyUsage: {76 required: false,77 serializedName: 'key_usage',78 type: {79 name: 'Sequence',80 element: {81 required: false,82 serializedName: 'StringElementType',83 type: {84 name: 'String'85 }86 }87 }88 },89 validityInMonths: {90 required: false,91 serializedName: 'validity_months',92 constraints: {93 InclusiveMinimum: 094 },95 type: {96 name: 'Number'97 }98 }99 }100 }101 };102 }103}...
subjectAlternativeNames.js
Source:subjectAlternativeNames.js
1/*2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for4 * license information.5 *6 * Code generated by Microsoft (R) AutoRest Code Generator.7 * Changes may cause incorrect behavior and will be lost if the code is8 * regenerated.9 */10'use strict';11/**12 * The subject alternate names of a X509 object.13 *14 */15class SubjectAlternativeNames {16 /**17 * Create a SubjectAlternativeNames.18 * @member {array} [emails] Email addresses.19 * @member {array} [dnsNames] Domain names.20 * @member {array} [upns] User principal names.21 */22 constructor() {23 }24 /**25 * Defines the metadata of SubjectAlternativeNames26 *27 * @returns {object} metadata of SubjectAlternativeNames28 *29 */30 mapper() {31 return {32 required: false,33 serializedName: 'SubjectAlternativeNames',34 type: {35 name: 'Composite',36 className: 'SubjectAlternativeNames',37 modelProperties: {38 emails: {39 required: false,40 serializedName: 'emails',41 type: {42 name: 'Sequence',43 element: {44 required: false,45 serializedName: 'StringElementType',46 type: {47 name: 'String'48 }49 }50 }51 },52 dnsNames: {53 required: false,54 serializedName: 'dns_names',55 type: {56 name: 'Sequence',57 element: {58 required: false,59 serializedName: 'StringElementType',60 type: {61 name: 'String'62 }63 }64 }65 },66 upns: {67 required: false,68 serializedName: 'upns',69 type: {70 name: 'Sequence',71 element: {72 required: false,73 serializedName: 'StringElementType',74 type: {75 name: 'String'76 }77 }78 }79 }80 }81 }82 };83 }84}...
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page.screenshot({path: 'google.png'});5 await browser.close();6})();
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 const client = await page.target().createCDPSession();5 const { data } = await client.send('Network.getCertificate', {6 });7 console.log(data);8 await browser.close();9})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const devices = require('puppeteer/DeviceDescriptors');4const iPhone = devices['iPhone 6'];5const path = require('path');6(async() => {7 const browser = await puppeteer.launch({
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!