Token passed to createTokenAuth is not a string : octokit, auth-token - node.js

I am trying to build a GitHub App and following the https://probot.github.io/docs/ and https://octokit.github.io/rest.js/v17#authentication. It is basically a nodejs app.
I have no experience working with nodejs or typescript and not even the probot framework.
The PRIVATE_KEY_PATH is in the .env file as follows:
PRIVATE_KEY_PATH=my-app.2020-04-03.private-key.pem
The .pem file is in the root directory of the project
The typeof prints string :
-------------TypeOf token ---- string
index.js
/**
* This is the main entrypoint to your Probot app
* #param {import('probot').Application} app
*/
const{Octokit} = require("#octokit/rest");
const{createAppAuth} = require("#octokit/auth-token");
console.log('PRIVATE_KEY',process.env.PRIVATE_KEY_PATH);
console.log('-------------TypeOf token ----', typeof process.env.PRIVATE_KEY_PATH)
const appOctokit = new Octokit({
authStrategy:createAppAuth,
auth:{
id:12345,
privateKey: process.env.PRIVATE_KEY_PATH,
// privateKey: 'token ${process.env.PRIVATE_KEY_PATH}'
}
});
I keep getting below error :
10:52:51.166Z ERROR probot: [#octokit/auth-token] Token passed to createTokenAuth is not a string
Not able to find much help on this topic over teh internet. I even tried navigating the code of octokit https://github.com/octokit/auth-token.js/blob/master/src/index.ts and it seems I am doing nothing wrong in my code.
There are not much resources to refer for issues for GitHub Apps or probot framework apart from the documentations. StackOverflow too ha just about 20-30 questions related to GitHub Apps or probot framework.
EDIT 1 : START
Running below code :
/**
* This is the main entrypoint to your Probot app
* #param {import('probot').Application} app
*/
const{Octokit} = require("#octokit/rest");
const{createAppAuth} = require("#octokit/auth-token");
console.log('PRIVATE_KEY',process.env.PRIVATE_KEY_PATH);
console.log('-------------TypeOf token ----', typeof process.env.PRIVATE_KEY_PATH)
produces a below error:
ERROR probot: appFn is not a function
TypeError: appFn is not a function
EDIT 1 : END

If you use Probot, you don't need to load your own #octokit/rest or any of the #octokit/auth-* packages, it's all built into Probot
Did you try the example code shown on https://probot.github.io/
module.exports = app => {
app.on('issues.opened', async context => {
const params = context.issue({
body: 'Hello World!'
})
await context.github.issues.createComment(params)
})
}
Probot will automatically read the contents of your .env file, look for the PRIVATE_KEY_PATH environment variable, read out the contents of the file at that location, and setup the JWT/installation authentication for you

Related

Firebase Cloud functions - Failed to load function definition from source: Restful Endpoints - Failed to add the endpoint defined

I am using firebase cloud functions with typescript in node 16.14.
My index.ts look like this:
import { FunctionParser } from "firebase-backend";
exports = new FunctionParser({rootPath: __dirname, exports,
verbose:true}).exports;
Here is the addEvent.endpoint.ts:
import { Request, Response } from "express";
import { Endpoint, RequestType } from "firebase-backend";
// import * as functions from "firebase-functions";
const fs = require('firebase-admin');
const serviceAccount = require('./key.json');
fs.initializeApp({
credential: fs.credential.cert(serviceAccount)
});
const db = fs.firestore();
export default new Endpoint(
"addEvent",
RequestType.POST,
(request: Request, response: Response) => {
const message = request.body["message"];
db.collection("events").doc("adkakjagjh").set("message", message);
return response.status(201).send({
message: message
});
}
)
I have the following file structure as below.
My cloud functions worked just recently but some change that I am not aware of has made them error out with the following error for just this 1 endpoint "addEvent.endpoint.ts": Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: Restful Endpoints - Failed to add the endpoint defined in C:/Development/EventFeeder/Backend/Firebase/functions/lib/users/restful/addEvent.endpoint.js to the users Api.
How can I fix this issue?
I am not sure what I need to try because the error message is not that specific about the problem's root cause.
I did not find any post about this particular problem.
I try to run the functions with "npm run build && firebase emulators:start --only functions" and "firebase emulators:start"
The issue disappear when I remove the addEvent.endpoint.ts file
I was facing the same problem, and I figured out that you shouldn't initialize the app (initializeApp()) in each endpoint, just write it in the index.ts one time and everything will work as expected.

use nodejs in web site online

I have a web site online, on the disk of my freebox (https://www.free.fr/assistance/52.html).
On this web site, i have a page index.html with only one buton. I would like this buton to execute this file index.js :
const ewelink = require('ewelink-api');
/* instantiate class */
(async () => {
const connection = new ewelink({
email: 'XX',
password: 'XX',
region: 'eu'
});
/* Astrolabe id : 1001091c4b */
const status = await connection.setDevicePowerState('1001091c4b', 'toggle', 1);
console.log(status);
})();
This script is functional when i call it " node index.js" in the command line, but i have an issue by execute this js file on my page : "Uncaught ReferenceError: require is not defined".
I already saw topics on this but i don't want a localhost for my site, it's already on the web, isn't it ? Sorry i'm new, maybe it's a basic thing.
Thanks,
Thomas

How to integrate OIDC Provider in Node jS

I tried to Integrate OIDC Provider to Node JS and I have a Sample Code. So, I run this Sample code it's throwing an error(unrecognized route or not allowed method (GET on /api/v1/.well-known/openid-configuration)).The problem is Issuer(https://localhost:3000) this Issuer is working fine. but i will change this Issuer((https://localhost:3000/api/v1/)) it's not working How to fix this Issue and I facing another issue also when I implement oldc-provider in node js. They Routes are override how to fix this issue
Sample.js
const { Provider } = require('oidc-provider');
const configuration = {
// ... see available options /docs
clients: [{
client_id: 'foo',
client_secret: 'bar',
redirect_uris: ['http://localhost:3000/api/v1/'],
true_provider: "pcc"
// + other client properties
}],
};
const oidc = new Provider('http://localhost:3000/api/v1/', configuration);
// express/nodejs style application callback (req, res, next) for use with express apps, see /examples/express.js
oidc.callback()
// or just expose a server standalone, see /examples/standalone.js
const server = oidc.listen(3000, () => {
console.log('oidc-provider listening on port 3000, check http://localhost:3000/api/v1/.well-known/openid-configuration');
});
Error
Defining Issuer Identifier with a path component does not affect anything route-wise.
You have two options, either mount the provider to a path (see docs), or define the actual paths you want for each endpoint to be prefixed (see docs).
I think you're looking for a way to mount, so the first one.

Where to Put Google Maps API Key in NodeJS Project

I have Google Maps API Key and want to use it with google-distance-matrix library. But i don't know where to put my Key and integrate it with above stated library here is my code
const distanceAPI = require('google-distance-matrix')
dispatchers.dispatchers.map( (dispatcher) => {
distanceAPI.matrix(dispatcher.location.coordinates, call.pickupLocationCoordinates.coordinates, mode, function(err, distances) {
console.log("distances")
console.log(distances)
})
})
Following error is still being thrown
error = 'You must use an API key to authenticate each request to Google Maps Platform APIs.'
I have also create a variable in .env file with following
G_API = key
Kindly let me know the right way of using the map service.
As mentioned in the README.md of google-distance-matrix you have to precise your key in distance.key() method.
distance.key('myAPIkey');
If your using a .env file you should call your env variable variable with process.env and dotenv package.
index.js :
require('dotenv').config();
const distance = require('google-distance-matrix');
distance.key(process.env.MY_API_KEY);
// Working example code
var origins = ['San Francisco CA'];
var destinations = ['New York NY', '41.8337329,-87.7321554'];
distance.matrix(origins, destinations, function (err, distances) {
if (!err)
console.log(distances);
})
.env :
MY_API_KEY=1234AEB
You can check a full working example on the google-distance-matrix doc
here

Node modules with sub-directories: "Error parsing triggers: Cannot find module 'ibm-watson'"

I have a Firebase Cloud Function that calls IBM Watson to get a token. I'm updating it from the old username/password auth to the current IAM auth.
Here's the code from the IBM documentation:
const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
When I run firebase deploy --only functions I get this error:
Error: Error parsing triggers: Cannot find module 'ibm-watson'
Require stack:
- /Users/TDK/LanguageTwo/functions/index.js
- /Users/TDK/.nvm/versions/node/v13.10.1/lib/node_modules/firebase-tools/lib/triggerParser.js
ibm-watson is installed in my /functions/node_modules directory:
I reinstalled ibm-watson, and for good measure I ran npm install in my functions directory. Plus I ran npm-check and updated all my node modules.
The specific line that causes the error is:
const watson = require('ibm-watson');
When I comment out that line the functions deploy without error. Unfortunately, the function doesn't run. :-)
This line does not cause the deploy error:
const { IamAuthenticator } = require('ibm-watson/auth');
I use IBM Watson in other Firebase Cloud Functions in the same index.js file. These lines from other functions don't cause deploy errors:
let TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
...
var LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
The problem seems to be that requiring the parent directory ibm-watson fails, but requiring the subdirectories of the parent directory works. Any suggestions?
This is as expected. If you take a look at the GitHub repo for ibm-watson - https://github.com/watson-developer-cloud/node-sdk - you will notice that there is no example requiring the top level library. This stops you from pulling in the full library, when you only need to pull in a small sub-component.

Resources