How to get grant staus from battery optimization permission popup - javascript

I am using https://www.npmjs.com/package/react-native-disable-battery-optimizations-android package for my React Native Android app. This package provides OpenBatteryModal() method to raise popup to get ignore battery optimization permission. But it does not provide how to get permission granted status. So, my question is "Is there any way to get to know what option is selected in permission popup or is there any other workaround in this package to get the grant status? I am struck on this for days. There is not much help also apart from using this package.

It looks like this library (RNDisableBatteryOptimizationsAndroid) has a method to check the status of battery optimization, it's even mentioned on their README under usage. I'm not sure what you've tried, but this is how you can check if the permission was granted using their isBatteryOptimizationEnabled API:
import RNDisableBatteryOptimizationsAndroid from 'react-native-disable-battery-optimizations-android';
RNDisableBatteryOptimizationsAndroid.isBatteryOptimizationEnabled().then((isEnabled)=>{
if(isEnabled){
RNDisableBatteryOptimizationsAndroid.openBatteryModal();
}
});
You can't get the user selected option directly, so in case the above example is not enough - you can write some logic to get the status when your app becomes active (using react-native AppState) after the modal is closed; since the modal is a new activity you should be notified when your activity becomes active again. Optimize it so you only check the status if openBatteryModal was requested.

Related

TikTok Login Kit web flow - keep getting Redirect URI error (code 10006)

I'm having an issue getting Login Kit to work. Similar to the question asked here I have the correct redirect domain listed in tiktok settings and the redirect_uri is basically just "domain/tiktok" but no matter what I do I get the same error message:
Below is my backend code - it's basically exactly the same as what is listed in the tiktok docs. Any help on this would be much appreciated!
const CLIENT_KEY = 'my_key'
const DOMAIN = 'dev.mydomain.com'
const csrfState = Math.random().toString(36).substring(2);
res.cookie('csrfState', csrfState, { maxAge: 60000 });
const redirect = encodeURIComponent(`https://${DOMAIN}/tiktok`)
let url = 'https://www.tiktok.com/auth/authorize/';
url += '?client_key=' + CLIENT_KEY;
url += '&scope=user.info.basic,video.list';
url += '&response_type=code';
url += '&redirect_uri=' + redirect;
url += '&state=' + csrfState;
res.redirect(url);
UPDATE 8/13/2022
I submitted the app for review and was approved so the status is now "Live in production" instead of "staging". The issue is still there - still showing error message no matter what domain / callback URL I use
UPDATE 8/16/2022
OK so I've made some progress on this.
First off - I was able to get the authentication/login screen to finally show up. I realized to do this you need to:
Make sure that the status of your app is "Live in production" and not "Staging". Even though when you create a new app you may see client_key and client_secret show up don't let that fool you - Login Kit WILL NOT WORK unless your app is submitted and approved
The redirect_uri you include in your server flow must match EXACTLY to whatever value you entered in "Registered domains" in the Settings page. So if you entered "dev.mydomain.com" in Settings then redirect_uri can only be "dev.mydomain.com" not "dev.mydomain.com/tiktok".
I think I might know what the issue is. My guess is that before - on the Settings page you had to enter the FULL redirect URL (not just the domain) and whatever redirect uri was included in the authorization query was checked against this value which was saved in TikTok's database (whatever was entered in the Settings page when path/protocol were allowed). At some point recently, the front-end business logic was changed such that you could only enter a domain (e.g., mydomain.com) on the Settings page without any protocols - however TikTok's backend logic was never updated so during the Login flow they are still checking against an EXACT match for whatever was saved in their DB as the redirect uri - this would explain why an app that was previously using the API with a redirect uri that DOES include protocols (e.g., for Later.com their redirect uri is https://app.later.com/users/auth/tiktok/callback) continues to work and why for any app attempting to save redirect WITH protocols are getting the error message screen. My gut feeling is telling me that the error is not on my part and this is actually a bug on TikTok's API - my guess is it can be addressed either by changing the front-end on the Settings page to allow for path/protocols (I think this is the ideal approach) or to change their backend so that any redirect uri is checked such that it must include 1 of the listed redirect domains.
I've been emailing with the TikTok team - their email is tiktokplatform#tiktok.com - and proposed the two solutions I mentioned above. I suggest if you're having the same issue you email them as well and maybe even link this StackOverflow question so that maybe it will get higher priority if enough people message them about it.
If you're looking for a shot-term hack I'd recommend creating a dedicated app on AWS or Heroku with a clean domain (e.g., https://mydomain-tiktok.herokuapp.com) and then redirect to either your dev or production environment by appending a prefix to the "state" query (e.g., "dev_[STATE_ID]"). I'll just reiterate I consider this a very "hacky" approach handling callbacks and would definitely not want to use something like this in production.
In my case, the integration worked after doing following steps:
In TikTok developers page:
Like #eugene-blinn said: make sure your app is in Live in production status (I couldn't find anything in the documentation about why Staging apps don't work);
Add the Login Kit product to your app and set the Redirect domain field with your host domain, for example: mywebsite.com.
In your code:
From my tests, I could add whanever url path I wanted, the only constraint was that the domain should match with step 2. So, yes, you can add https://mywebsite.com/whatever/path/you/want in redirect_url parameter.
That's it. It should work with these 3 steps.
Additionally, I got other issue related to use specific features in the scope property (like upload or read videos, etc), so here the solution as well:
Only add Video Kit product to the TikTok app and set video.upload or video.list in the scope authorize request won't work unless you also add the TikTok API product in your TikTok app as well. Btw, it neeeds to be approved too.
TikTok fixed the bug that resulted in URL mismatch with redirect domain from working. However, they fixed it only for paths (e.g., /auth/tiktok) but PORT additions still result in an error - so www.domain.com:8080/auth/tiktok won't work but www.domain.com/auth/tiktok WILL work
UPDATE 10/3/2022
Got the following response directly from TikTok engineering team:
At this point, we only support production integrations with TikTok for Developers and require that you have a URL without port number. However, we understand from your communication that this makes it harder for you to build, test, and iterate your integration with us. Unfortunately, at this time, we do not have a timeline for when this additional support for development servers will be added. We request that you only redirect to URLs without port numbers. Thank you for the feedback.
The frontend of the developer's dashboard still rejects protocol and path in validation. However, the backend skips the path validation.
To be able to update the "Redirect domain" simply:
Open dev tools in chrome and go to the "Network" tab.
Clic on "Save changes" button on the dashboard.
Right clic on the "publish" request that appeared and copy as cURL.
Modify the "redirect_domains" field in the request before pasting it in the terminal.
I believe the app still needs to be approved and in production to get it to work. I'm still waiting for approval and it has been a couple of weeks.
UPDATE 9/17/2022
Just like #mauricio-ribeiro, my app worked after it was approved to production. Setting up the redirect domain without path and scheme works just fine.
I had the same problem, my solution:
1.- In my TikTok App dashboard, the “redirect_uri” is: mydomain.com, without http/https and without path (/my-redirect-url). Also you can add subdomains using this rule
2.- In my code, I have to add http or https to the redirect_uri, and feel free to use path (/my-redirect-uri)
I hope this help you

About WebAuthn(FIDO)

I was testing out WebAuthn in front side(this means no backend thingy, like challenge, id, etc.)
Why does icon matter?
When I first tried, I could only auth with a security key. But when I added an icon: undefined to publickey.user.icon, I could auth with Windows Hello. And, even if I insert a REAL icon link, it didn't show up. Windows 10 Edu, the latest version
How can I implement it?
I've found that I could use res(navigator.credentials....).response.attestationObject. Is this the right way to use WebAuthn?
About physical security key
Let's say I've got a security key USB with fingerprint support. Then I put my fingerprint then register with WebAuthn. Then my friend comes in, and he does the registration with his fingerprint. Then would the key(.response.attestationObject) be the same together because it's the same physical fingerprint or be different because it's different fingerprints?
[Partial anwser here, I will be happy to see other answers from community members]
The icon parameter has been removed from the new version of the specification.
Webauthn-1: https://www.w3.org/TR/webauthn-1/#dictionary-pkcredentialentity
Webauthn-2: https://www.w3.org/TR/webauthn-2/#dictionary-pkcredentialentity
It was a property with an a priori authenticated URL e.g. data::/ instead of https://
Can you be more precise?
A security key is usually used by only one user. New credentials are generated each time a user uses the key to register on an application. With the use case you mentions, 2 sets of credentials will be generated by the key and associated with biometric data. There is no chance for user 2 to be logged in as user 1

Selenium Tests: Authenticate with Webauthn

In my use case, there is a registration page that triggers the browser-specific webauthn flow. For example in Chrome on a Mac you will see this series of popups:
Pick an option between USB security key and Built-in sensor
MacOS confirmation with Touch ID
Confirmation dialog from Chrome requesting access to your security key
Besides https://w3c.github.io/webauthn/#add-virtual-authenticator I haven't found much documentation about authenticating with webauthn as part of a selenium test. What resources are available to help devs figure out how to test webauthn with Selenium in JavaScript? I have also checked out https://github.com/SeleniumHQ/selenium/issues/7829 but the example test case does not make sense to me. Examples would be hugely appreciated.
Update with solution for js:
import { Command } from 'selenium-webdriver/lib/command';
addVirtualAuthenticator = async () => {
await this.driver.getSession().then(async session => {
this.driver
.getExecutor()
.defineCommand('AddVirtualAuthenticator', 'POST', `/session/${session.id_}/webauthn/authenticator`);
let addVirtualAuthCommand = new Command('AddVirtualAuthenticator');
addVirtualAuthCommand.setParameter('protocol', 'ctap2');
addVirtualAuthCommand.setParameter('transport', 'internal');
addVirtualAuthCommand.setParameter('hasResidentKey', true);
addVirtualAuthCommand.setParameter('isUserConsenting', true);
await this.driver.getExecutor().execute(addVirtualAuthCommand);
});
};
Note that this.driver is of type WebDriver.
Call addVirtualAuthenticator before hitting any code that interacts with navigator (in our case user registration involved a call to navigator.credentials.create). If you need access to the publicKey, i.e. via navigator.credentials.get({ publicKey: options }) during login, then hasResidentKey is critical.
A good resource for an example if you're implementing this in java and using selenium 4 is the tests on selenium itself. You basically need to
Create a virtual authenticator
In your case, you should set the transport to internal and hasUserVerification to true to simulate touchID.
VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
options.setTransport(Transport.INTERNAL)
.hasUserVerification(true)
.isUserVerified(true);
VirtualAuthenticator authenticator =
((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);
Perform the action that triggers registration.
If everything goes right, the browser should not show a dialog. Instead, it should immediately return a credential.
For any other language or selenium version, you will need to drop into calling the WebDriver protocol directly. As you pointed out, the W3C spec has documentation on the protocol endpoints.
For java, it might be something like
browser.driver.getExecutor().defineCommand(
"AddVirtualAuthenticator", "POST", "/session/:sessionId/webauthn/authenticator");
// ...
Command addVirtualAuthCommand = new Command("AddVirtualAuthenticator");
addVirtualAuthCommand.setParameter("protocol", "ctap2");
addVirtualAuthCommand.setParameter("transport", "usb");
browser.driver.getExecutor().execute(addVirtualAuthCommand);
For javascript, you should be able to use defineCommand and webDriver.execute in a similar fashion.
This is worst practice in selenium
Two Factor Authentication shortly know as 2FA is a authorization
mechanism where One Time Password(OTP) is generated using
“Authenticator” mobile apps such as “Google Authenticator”, “Microsoft
Authenticator” etc., or by SMS, e-mail to authenticate. Automating
this seamlessly and consistently is a big challenge in Selenium. There
are some ways to automate this process. But that will be another layer
on top of our Selenium tests and not secured as well. So, you can
avoid automating 2FA.
There are few options to get around 2FA checks:
1.Disable 2FA for certain Users in the test environment, so that you can use those user credentials in the automation.
2.Disable 2FA in your test environment.
3.Disable 2FA if you login from certain IPs. That way we can configure our test machine IPs to avoid this.

Windows 8 Store App, how do I test in-app purchase?

My app is created with Javascript. I need it to support in-app purchase for feature unlocking.
From the documentation, it looks really simple. However, when I tries to implement it. I noticed that after returning S_OK from CurrentAppSimulator.requestProductPurchaseAsync, CurrentAppSimulator.licenseInformation.productLicenses.lookup(main.licenseName).isActive won't be changed to true.
Then I discovered this answer CurrentAppSimulator.RequestProductPurchaseAsync purchasing simulation , mentioning something about calling RequestAppPurchaseAsync once before requestProductPurchaseAsync. I did, and this way, I saw the Store popup twice. And after choosing S_OK twice, isActive is set to true. However, this status is not persistent. Running this app (by pressing F5 to debug) the second time will clear this flag and the entire purchase procedure has to be run again.
The answer also mentioned only about "correct simulation" but said nothing about whether this procedure is correct for live store app. I currently have a Windows Store developer account configured for in-app purchase, but binaries are not uploaded yet. When I try purchase with CurrentApp I got the message that the product is no longer available from Windows Store.
I'd like some viable options to make sure that my in-app purchase is correctly implemented.
Are you updating the WindowsStoreProxy.xml file? You have to do that otherwise the purchase will never be set to active. You don't need to call RequestAppPurchaseAsync... only the requestProductPurchaseAsync. Do this...
Run your app in debug mode breaking anywhere
Open QuickWatch (SHIFT +
F9) and enter
Windows.Storage.ApplicationData.current.roamingFolder.path and copy
the value (mine was C:\Users\jerfost\AppData\Local\Packages\{package
name}\LocalState
Browse to that location and open the Microsoft\Windows Store\ApiData directory
Open the WindowsStoreProxy.xml file in a text editor
Change CurrentApp/LicenseInformation/App/IsTrial to false
Change CurrentApp/ListingInformation/Product/MarketData/Name to your unique product name
That should do it. Hope that helps.

Security in JavaScript Code

I am starting to build/design a new single page web application and really wanted to primarily use client-side technology (HTML, CSS, JavaScript/CoffeScript) for the front-end while having a thin REST API back-end to serve data to the front-end. An issue that has come up is about the security of JavaScript. For example, there are going to be certain links and UI elements that will only be displayed depending on the roles and resources the user has attached to them. When the user logs in, it will make a REST call that will validate the credentials and then return back a json object that has all the permissions for that user which will be stored in a JavaScript object.
Lets take this piece of javascript:
// Generated by CoffeeScript 1.3.3
(function() {
var acl, permissions, root;
root = typeof exports !== "undefined" && exports !== null ? exports : this;
permissions = {
//data…
};
acl = {
hasPermission: function(resource, permission, instanceId) {
//code….
}
};
root.acl = acl;
}).call(this);
Now this code setup make sure even through the console, no one can modify the variable permissions. The issue here is that since this is a single page application, I might want to update the permissions without having to refresh the page (maybe they add a record that then needs to be added to thier permissions). The only way I can think of doing this is by adding something like
setPermission: function(resource, permission, instanceId){
//code…
}
to the acl object however if I do that, that mean someone in the browser console could also use that to add permissions to themself that they should not have. Is there any way to add code that can not be accessed from the browser console however can be accessed from code in the JavaScript files?
Now even if I could prevent the issue described above, I still have a bigger one. No matter what I am going to need to have the hasPermission functionality however when it is declared this way, I can in the browser console overwrite that method by just doing:
acl.hasPermission(resource, permission, instanceId){return true;}
and now I would be able to see everything. Is there anyway to define this method is such a way that a user can not override it (like marking it as final or something)?
Something to note is that every REST API call is also going to check the permissions too so even if they were to see something they should not, they would still not be able to do anything and the REST API would regret the request because of permissions issue. One suggestion has been made to generate the template on the server side however I really don't like that idea as it is creating a very strong coupling between the front-end and back-end technology stacks. If for example for whatever reason we need to move form PHP to Python or Ruby, if the templates are built on the client-side in JavaScript, I only have to re-build the REST API and all the front-end code can stay the same but that is not the case if I am generating templates on the server side.
Whatever you do: you have to check all the permissions on the server-side as well (in your REST backend, as you noted). No matter what hoops you jump through, someone will be able to make a REST call that they are not supposed to make.
This effectively makes your client-side security system an optimization: you try to display only allowed operations to the user and you try to avoid round-trips to the server to fetch what is allowed.
As such you don't really need to care if a user can "hack" it: if they break your application, they can keep both parts. Nothing wrong can happen, because the server won't let them execute an action that they are not authorized to.
However, I'd still write the client-side code in a way that it expect an "access denied" as a valid answer (and not necessary an exception). There are many reasons why that response might come: If the permissions of the logged-in user are changed while he has a browser open, then the security descriptions of the client no longer match the server and that situation should be handled gracefully (display "Sorry, this operation is not permitted" and reload the security descriptions, for example).
Don't ever trust Javascript code or the front-end in general. People can even modify the code before it reaches your browser (sniffers etc) and most variables are accessible and modifiable anyways... Trust me: you are never going to be safe on the front-end :)
Always check credentials on the server-side, never only on the front-end!
In modern browsers, you can use Object.freeze or Object.defineProperty to make sure the hasPermission method cannot be redefined.
I don't know yet how to overcome the problem with setPermission. Maybe it's best to just rely on the server-side security there, which as you said you have anyway.

Categories