Fido U2F client side javascript source code - javascript

I'm looking for a JavaScript source code (client side) to make communication between Fido U2F token and Google Chrome (Version 41.0.2272.89 m).
Please help me

Here is an example to getting the Token response for registration using Yubico u2f-api file
var RegistrationData = {"challenge":"dG7vN-E440ZnJaKQ7Ynq8AemLHziJfKrBpIBi5OET_0",
"appId":"https://localhost:8443",
"version":"U2F_V2"};
window.u2f.register([RegistrationData], [],
function(data) {if(data.errorCode) {
alert("U2F failed with error: " + data.errorCode);
return;
}
alert(JSON.stringify(data));
});
you've to include the u2f-api.js and use an Https server

You can perform the registration, and even parse the registrationData using Javascript
let registerRequest = {
challenge: 'RegisterChallenge',
version: 'U2F_V2'
}
u2f.register('https://localhost', [registerRequest], [],
(response) => {
U2FRegistration.parse(response.registrationData);
console.log(U2FRegistration);
}
);
Here is a github repo demonstrating this: https://github.com/infiniteloopltd/U2FJS - and as mentioned, you need a HTTPS server, and include u2f-api.js

Related

Use git credential manager to fetch azure devops api instead of personal access token

I am trying to fetch git azure devops api to get information about repositories and branches in js.
In order to achieve that, I made a little application with the following code :
$(document).ready(function() {
var personalToken = btoa(':'+'<personnalAccessToken>');
fetch('https://dev.azure.com/<company>/<project>/_apis/git/repositories?api-version=5.1', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
'Authorization': 'Basic '+ personalToken
}
}).then(function(response) {
return response.json();
}).then(function(repositories) {
console.log("There are "+repositories.count+" repositories");
}).catch(function(error) {
console.log('Fetch error: ' + error.message);
});
This code is working great but as you can see there is my personnalAccessToken writen directly inside the code... which is really bad...
When I am using git in command line, I don't have to specify any credential information because I use git credential manager for windows. Which means my personnalAccessToken is already stored, cached and automatically used everytime I use a git command, like clone, etc.
So, I would like my js code to use the same thing, I would like it to use my stored credentials automatically to fetch the api without being required to set my personnalAccessToken in code.
I have already searched for hours but can't find out if it is possible.
I have already searched for hours but can't find out if it is
possible.
Sorry but as I know it's impossible. The way you're calling the Rest API is similar to use Invoke-RestMethod to call rest api in Powershell.
In both these two scenarios, the process will try to fetch PAT for authentication in current session/context and it won't even try to search the cache in Git Credential Manager.
You should distinguish the difference between accessing Azure Devops service via Rest API and by Code:
Rest API:
POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1
Request Body:
{
"query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'Task' AND [State] <> 'Closed' AND [State] <> 'Removed' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
}
Corresponding Code in C#:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
//create http client and query for resutls
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
Wiql query = new Wiql() { Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Bug' AND [Assigned To] = #Me" };
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;
Maybe you can consider using a limited PAT, limit its scope to Code only:
I know there exists other Authentication mechanism
:
For Interactive JavaScript project: ADALJS and Microsoft-supported Client Libraries.
You can give it a try but I'm not sure if it works for you since you're not using real Code way to access the Azure Devops Service... Hope it makes some help :)
If you have the script set up in an Azure Runbook you can set it as an encrypted variable there and have it pull it from there before running rather than having it directly written into the code.
$encryptedPatVarName = "ADO_PAT"
$adoPat = Get-AutomationVariable -Name $encryptedPatVarName
$adoPatToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($adoPat)"))
$adoHeader = #{authorization = "Basic $adoPatToken"}
The above is the Powershell version of it. I have seen some people do it with other

PouchDB and React-Native not replicating .to() but .from() is working

For some reason documents created on my app are not showing up on my remote couchdb database.
I am using the following
import PouchDB from 'pouchdb-react-native'
let company_id = await AsyncStorage.getItem('company_id');
let device_db = new PouchDB(company_id, {auto_compaction: true});
let remote_db = new PouchDB('https://'+API_KEY+'#'+SERVER+'/'+company_id, {ajax: {timeout: 180000}});
device_db.replicate.to(remote_db).then((resp) => {
console.log(JSON.stringify(resp));
console.log("Device to Remote Server - Success");
return resp;
}, (error) => {
console.log("Device to Remote Server - Error");
return false;
});
I get a successful response the response:
{
"ok":true,
"start_time":"2018-05-17T15:19:05.179Z",
"docs_read":0,
"docs_written":0,
"doc_write_failures":0,
"errors":[
],
"last_seq":355,
"status":"complete",
"end_time":"2018-05-17T15:19:05.555Z"
}
When I go to my remote database, document_id's that am able to search and grab on the application do not show up.
Is there something I am not taking into account?
Is there anything I can do to check why this might be happening?
This worked when I used the same scripting method in Ionic and when I switched to React-Native I noticed this is the case.
NOTE: When I do .from() and get data from remote to the device, I get the data. For some reason it just isn't pushing data out
"Is there anything I can do to check why this might be happening?"
I would try switching on debugging as outlined here.
PouchDB.debug.enable('*');
This should allow you to view debug messages in your browser's JavaScript console.

Get Github repo data after authenticating with OAuth and Auth0

What i want to do, is to get private repo datas (issues amount) from a small application.
Since I don't want to expose my personal github access_token in the request I searched another solution which I think is OAuth.
So i setted up an OAuth following these and these steps.
And setted the permissions in Auth0 in the social github settings to repo (grants read/write access for repos).
Until now everything works fine, I'm able to authenticate with my github account.
But now I don't know which token I have to use for my request to the github API.
Here is the relevant code I have so far:
const handleAuthentication = () => {
webAuth.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
setSession(authResult);
//here the call to the relevant function
getIssues('my-element', /*here i should pass the correct token*/); //tryed all tokens i found in authResult
} else if (err) {
alert(
`Error: ${err.error} . Check the console for further details.`
);
}
});
}
const getIssues = (element, token) => {
const request = new XMLHttpRequest();
request.open('GET', `https://api.github.com/repos/my_organization/element-${element}/issues?access_token=${token}`, true);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
const data = JSON.parse(request.responseText);
//use the data
} else {
console.log('error');
}
};
request.onerror = function(e) {
console.log('connection error: ', e)
};
request.send();
}
But this results to a 401 (Unauthorized) response.
I didn't use XMLHttpRequests a lot and I'm sure, that I'm missing something fundamental here.
And now i'm not even sure if oAuth is the correct way to achieve what I want.
Any help would be greatly appreciated.
Edit:
Meanwhile I did some more research and found out (here), that there are some steps missing to get the correct user access_token for connecting to the github api.
I'll try to complete these steps and will post an answer if it works.
Would still appreciate a clear answer if somebody knows how to do it exactly.
To get list of issues of a repo, call this API endpoint:
https://api.github.com/repos/${owner}/${repository}/issues
Where the ${owner} is the organization name (NOT your github username), and ${repo} is the repo that you want to list the issues.
For reference, the documentation is here: https://developer.github.com/v3/issues/#list-issues-for-a-repository. However like a lot OAuth endpoint documentation, this is cryptic, thus requires hours of tinkering.
There is a live working code snippet so that you can see the sample code, test and tweak it: https://jsfiddle.net/son74dj2/
The code snippet explanation follows.
It uses https://oauth.io service and its SDK (the OAuth class in the code below), which is not required. However OAuth.io enables you to implement OAuth flow with just front-end, e.g., Javascript, so the live working code snippet can be self-contained in a jsfiddle that can be easily shared, tweaked, tested and even just cut-and-pasted on your website.
$('#github-button').on('click', function() {
// Initialize with your OAuth.io app public key
OAuth.initialize('YOUR OAUTH.IO PUBLIC KEY');
// Use popup for oauth
OAuth.popup('github').then(provider => {
const repository = 'YOUR REPOSITORY';
const owner = 'REPOSITORY OWNER';
provider.get(`/repos/${owner}/${repository}/issues`).then(data => {
alert('Now you could see list of issues in the console!')
console.log('Issue list:', data);
})
});
})
Hope this is useful to help you understand and test the endpoint without spending hours figuring out the documentation, and tinkering with the url and parameters.
NOTE: You need to have access to the repo, which the repo owner needs to grant you. See the original article for screenshot details: https://tome.oauth.io/providers/github/get-repository-issue-list

Meteor login via Third party library

I'm trying to login to my meteor site via a third party library like this one:
https://gist.github.com/gabrielhpugliese/4188927
In my server.js i have:
Meteor.methods({
facebook_login: function (fbUser, accessToken) {
var options, serviceData, userId;
serviceData = {
id: fbUser.id,
accessToken: accessToken,
email: fbUser.email
};
options = {
profile: {
name: fbUser.name
}
};
userId = Accounts.updateOrCreateUserFromExternalService('facebook', serviceData, options);
return userId;
}, ......
In my client.js I have:
facebookLogin: function () {
if (Meteor.user())
return;
if (!Session.equals("deviceready", true))
return;
if (!Session.equals("meteorLoggingIn", false))
return;
// Do not run if plugin not available
if (typeof window.plugins === 'undefined')
return;
if (typeof window.plugins.facebookConnect === 'undefined')
return;
// After device ready, create a local alias
var facebookConnect = window.plugins.facebookConnect;
console.log('Begin activity');
Session.equals("meteorLoggingIn", true);
Accounts._setLoggingIn(true);
facebookConnect.login({
permissions: ["email", "user_about_me"],
appId: "123456789012345"
}, function (result) {
console.log("FacebookConnect.login:" + JSON.stringify(result));
// Check for cancellation/error
if (result.cancelled || result.error) {
console.log("FacebookConnect.login:failedWithError:" + result.message);
Accounts._setLoggingIn(false);
Session.equals("meteorLoggingIn", false);
return;
}
var access_token = result.accessToken;
Meteor.call('facebook_login', result, access_token, function (error, user) {
Accounts._setLoggingIn(false);
Session.equals("meteorLoggingIn", false);
if (!error) {
var id = Accounts._makeClientLoggedIn(user.id, user.token);
console.log("FacebookConnect.login: Account activated " + JSON.stringify(Meteor.user()));
} else {
// Accounts._makeClientLoggedOut();
}
});
});
}, // login
facebookLogout: function () {
Meteor.logout();
// var facebookConnect = window.plugins.facebookConnect;
// facebookConnect.logout();
},
The third party library (Facebook Android SDK in my case) works fine. My problem is after the "var id = Accounts._makeClientLoggedIn(user.id, user.token);" the Meteor.user() returns Undefined. However If I do a page refresh in the browser works fine and the template renders as a logged in user.
Anyone knows how to fix the 'Undefined' on client ??
PS. On server side the users collection looks fine. The meteor token and everything else are there.
Solved. I had to add : this.setUserId(userId.id);
after userId = Accounts.updateOrCreateUserFromExternalService('facebook', serviceData, options); at server.js
Meteor's client side javascript can't run fibers. Fibers allows synchronous code to be used with javascript since by design js is asynchronous. This means there are callbacks that need to be used to let you know when the task is complete.
From what it looks like Accounts._makeClientLoggedIn doesn't take a callback & unfortunately and doesn't return any data looking at its source. I can't say i've tried this myself because I can't test your code without the android sdk but have you tried using Deps.flush to do a reactive flush?
Also Meteor also has very clean and easy facbeook integration. If you simply add the facebook meteor package
meteor add accounts-facebook
You can get access to a lovely Meteor.loginWithFacebook method that can make everything reactive and your code simpler and really easy. If you need to modify it to use the Android SDK Dialog instead you can easily modify the code out as the code for the module is out there for you to hack up to your spec
Edit: If you're using an external SDK such as the java SDK/cordova plugin
Set your plugin so that it redirects to the following URL (set up for meteor.com hosting):
http://yourmeteorapp.meteor.com/_oauth/facebook?display=touch&scope=your_scope_request_params&state=state&code=yourOAuthCodeFromJava&redirect=YourAPP
So in the querystring we have:
scope= Contains your facebook scope params (for permissions)
code= Your OAuth code from the java sdk
redirect=Where to redirect to after once logged in instead of the window.close
state= A cros site forgery state value, any random value will do
This url is basically used to mimic would what be given to the REDIRECT_URI at : https://developers.facebook.com/docs/reference/dialogs/oauth/
This will redirect to meteor's OAuth helper (at https://github.com/meteor/meteor/blob/master/packages/accounts-oauth-helper/oauth_server.js)
So what would happen is you give the OAuth code from Java to meteor, it fetches the OAuth token and the user's data, then redirect the user to a URL in your app

How to use Google Chrome Remote Debugging Protocol in HTTP?

I referred http://code.google.com/chrome/devtools/docs/remote-debugging.html.
First, I started a new chrome process.
chrome --remote-debugging-port=9222 --user-data-dir=remote-profile
Then I want to try some options written in http://code.google.com/intl/ja/chrome/devtools/docs/protocol/tot/index.html, but how can I use them?
I already know how to use those methods in WebSocket, but I have to use it in HTTP.
I tried this nodejs code but failed.
var http = require('http');
var options = {
host: 'localhost',
port: 9222,
path: '/devtools/page/0',
method: 'POST'
};
var req = http.request(options, function (res) {
console.log(res.headers);
res.on('data', function (chunk) {
console.log(chunk);
});
});
req.on('error', function (e) { console.log('problem' + e.message); });
req.write(JSON.stringify({
'id': 1,
'method': "Page.enable"
}));
req.end();
Is it wrong?
I know this is a fairly old question, but I ran into it when I was trying to do something similar.
There's an npm module called chrome-remote-interface, which makes using the Chrome Remote Debugging API a lot easier: https://github.com/cyrus-and/chrome-remote-interface
npm install chrome-remote-interface
Then you can use the module in your code like this:
var Chrome = require('chrome-remote-interface');
Chrome(function (chrome) {
with (chrome) {
on('Network.requestWillBeSent', function (message) {
console.log(message.request.url);
});
on('Page.loadEventFired', close);
Network.enable();
Page.enable();
Page.navigate({'url': 'https://github.com'});
}
}).on('error', function () {
console.error('Cannot connect to Chrome');
});
I think it says "Note that we are currently working on exposing an HTTP-based protocol that does not require client WebSocket implementation."
I'm not sure it means that you can have HTTP instead of WebSocket now.
There is also a fantastic NPM module called Weinre that allows you to easily use the Chrome debugging/ remote debugging tools. If you have to test cross browser too it allows you to use the Chrome tools even on certain versions of IE. There is some more information on the MSDN blog.

Categories

Resources