;
15 | }
16 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/.gitignore:
--------------------------------------------------------------------------------
1 | # Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
2 |
3 | # dependencies
4 | node_modules/
5 |
6 | # Expo
7 | .expo/
8 | dist/
9 | web-build/
10 |
11 | # Native
12 | *.orig.*
13 | *.jks
14 | *.p8
15 | *.p12
16 | *.key
17 | *.mobileprovision
18 |
19 | # Metro
20 | .metro-health-check*
21 |
22 | # debug
23 | npm-debug.*
24 | yarn-debug.*
25 | yarn-error.*
26 |
27 | # macOS
28 | .DS_Store
29 | *.pem
30 |
31 | # local env files
32 | .env*.local
33 |
34 | # typescript
35 | *.tsbuildinfo
36 |
--------------------------------------------------------------------------------
/TestingApp/test/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rishabhpoddar/supertokens_node_driver_testing
2 |
3 | RUN apt-get update
4 |
5 | RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libatk-bridge2.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
--------------------------------------------------------------------------------
/TestingApp/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/docs/assets/highlight.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --light-code-background: #FFFFFF;
3 | --dark-code-background: #1E1E1E;
4 | }
5 |
6 | @media (prefers-color-scheme: light) { :root {
7 | --code-background: var(--light-code-background);
8 | } }
9 |
10 | @media (prefers-color-scheme: dark) { :root {
11 | --code-background: var(--dark-code-background);
12 | } }
13 |
14 | :root[data-theme='light'] {
15 | --code-background: var(--light-code-background);
16 | }
17 |
18 | :root[data-theme='dark'] {
19 | --code-background: var(--dark-code-background);
20 | }
21 |
22 | pre, code { background: var(--code-background); }
23 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # react-native-reanimated
11 | -keep class com.swmansion.reanimated.** { *; }
12 | -keep class com.facebook.react.turbomodule.** { *; }
13 |
14 | # Add any project specific keep options here:
15 |
--------------------------------------------------------------------------------
/test/playground/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "esnext",
4 | "strictNullChecks": true,
5 | "module": "commonJS",
6 | "moduleResolution": "Node",
7 | "skipLibCheck": true,
8 | "noFallthroughCasesInSwitch": true,
9 | "lib": ["ES2017"],
10 | "noEmit": true,
11 | "strict": true,
12 | "jsx": "react-native",
13 | "esModuleInterop": true,
14 | "isolatedModules": true,
15 | "allowJs": true,
16 | "allowSyntheticDefaultImports": true,
17 | },
18 | "include": ["./**/*"],
19 | "exclude": ["build"],
20 | "compileOnSave": true
21 | }
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'with-thirdparty'
2 |
3 | apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle");
4 | useExpoModules()
5 |
6 | apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
7 | applyNativeModulesSettingsGradle(settings)
8 |
9 | include ':app'
10 | includeBuild(new File(["node", "--print", "require.resolve('@react-native/gradle-plugin/package.json')"].execute(null, rootDir).text.trim()).getParentFile())
11 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | buildscript {
3 | repositories {
4 | jcenter()
5 | }
6 |
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.3.1'
9 | }
10 | }
11 |
12 | apply plugin: 'com.android.library'
13 |
14 | android {
15 | compileSdkVersion 23
16 | buildToolsVersion "23.0.1"
17 |
18 | defaultConfig {
19 | minSdkVersion 16
20 | targetSdkVersion 22
21 | versionCode 1
22 | versionName "1.0"
23 | }
24 | lintOptions {
25 | abortOnError false
26 | }
27 | }
28 |
29 | repositories {
30 | mavenCentral()
31 | }
32 |
33 | dependencies {
34 | compile 'com.facebook.react:react-native:+'
35 | }
36 |
--------------------------------------------------------------------------------
/TestingApp/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/android/src/main/java/com/reactlibrary/RNSuperTokensModule.java:
--------------------------------------------------------------------------------
1 |
2 | package com.reactlibrary;
3 |
4 | import com.facebook.react.bridge.ReactApplicationContext;
5 | import com.facebook.react.bridge.ReactContextBaseJavaModule;
6 | import com.facebook.react.bridge.ReactMethod;
7 | import com.facebook.react.bridge.Callback;
8 |
9 | public class RNSuperTokensModule extends ReactContextBaseJavaModule {
10 |
11 | private final ReactApplicationContext reactContext;
12 |
13 | public RNSuperTokensModule(ReactApplicationContext reactContext) {
14 | super(reactContext);
15 | this.reactContext = reactContext;
16 | }
17 |
18 | @Override
19 | public String getName() {
20 | return "RNSuperTokens";
21 | }
22 | }
--------------------------------------------------------------------------------
/lib/build/types.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | export {};
16 |
--------------------------------------------------------------------------------
/.github/workflows/pre-commit-hook-run.yml:
--------------------------------------------------------------------------------
1 | name: "Pre commit hook check"
2 |
3 | on:
4 | pull_request:
5 | types:
6 | - opened
7 | - reopened
8 | - edited
9 | - synchronize
10 |
11 | jobs:
12 | pre-commit-check:
13 | name: Pre commit hook check
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v4
17 | - name: Set up node
18 | uses: actions/setup-node@v1
19 | with:
20 | node-version: 16
21 | - run: rm -rf .git && git init && git add --all && git -c user.name='test' -c user.email='test@example.com' commit -m 'init for pr action'
22 | - run: npm i --force
23 | - run: ./hooks/pre-commit.sh
--------------------------------------------------------------------------------
/TestingApp/ios/TestingApp/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | /ios/Pods
3 | /ios/Podflie.lock
4 | /node_modules
5 | .DS_Store
6 | /.history
7 | .vscode
8 | coverage
9 | apiPassword
10 | releasePassword
11 |
12 |
13 | # OSX
14 | #
15 | .DS_Store
16 |
17 | # node.js
18 | #
19 | node_modules/
20 | npm-debug.log
21 | yarn-error.log
22 | yarn.lock
23 |
24 |
25 | # Xcode
26 | #
27 | build/
28 | *.pbxuser
29 | !default.pbxuser
30 | *.mode1v3
31 | !default.mode1v3
32 | *.mode2v3
33 | !default.mode2v3
34 | *.perspectivev3
35 | !default.perspectivev3
36 | xcuserdata
37 | *.xccheckout
38 | *.moved-aside
39 | DerivedData
40 | *.hmap
41 | *.ipa
42 | *.xcuserstate
43 | project.xcworkspace
44 |
45 |
46 | # Android/IntelliJ
47 | #
48 | build/
49 | .idea
50 | .gradle
51 | local.properties
52 | *.iml
53 |
54 | # BUCK
55 | buck-out/
56 | \.buckd/
57 | *.keystore
58 |
59 | !lib/build/
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | import SuperTokens from "./lib/build/index.js";
17 | export default SuperTokens;
18 |
--------------------------------------------------------------------------------
/android/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | android
4 | Project android created by Buildship.
5 |
6 |
7 |
8 |
9 | org.eclipse.buildship.core.gradleprojectbuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.buildship.core.gradleprojectnature
16 |
17 |
18 |
19 | 1715234366601
20 |
21 | 30
22 |
23 | org.eclipse.core.resources.regexFilterMatcher
24 | node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/utils/error/index.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | import SuperTokens from "../../lib/build/error.js";
17 | export default SuperTokens;
18 |
--------------------------------------------------------------------------------
/ios/RNSuperTokens.podspec:
--------------------------------------------------------------------------------
1 |
2 | Pod::Spec.new do |s|
3 | s.name = "RNSuperTokens"
4 | s.version = "0.0.1"
5 | s.summary = "RNSuperTokens"
6 | s.description = <<-DESC
7 | RNSuperTokens
8 | DESC
9 | s.homepage = "https://github.com/supertokens/supertokens-react-native"
10 | s.license = "Apache 2.0"
11 | # s.license = { :type => "MIT", :file => "FILE_LICENSE" }
12 | s.author = { "author" => "team@supertokens.io" }
13 | s.platform = :ios, "7.0"
14 | s.source = { :git => "https://github.com/supertokens/supertokens-react-native.git", :tag => "master" }
15 | s.source_files = "./**/*.{h,m}"
16 | s.requires_arc = true
17 |
18 |
19 | s.dependency "React"
20 | s.dependency "SuperTokensSession",'~> 1.1.0'
21 | #s.dependency "others"
22 |
23 | end
24 |
25 |
--------------------------------------------------------------------------------
/TestingApp/ios/TestingAppTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/release/java/com/supertokens/supertokensexample/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.supertokens.supertokensexample;
8 |
9 | import android.content.Context;
10 | import com.facebook.react.ReactInstanceManager;
11 |
12 | /**
13 | * Class responsible of loading Flipper inside your React Native application. This is the release
14 | * flavor of it so it's empty as we don't want to load Flipper.
15 | */
16 | public class ReactNativeFlipper {
17 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
18 | // Do nothing as we don't want to initialize Flipper on Release.
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/lib/build/version.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | export const package_version = "5.1.5";
16 | export const supported_fdi = ["1.16", "1.17", "1.18", "1.19", "2.0", "3.0", "3.1", "4.0", "4.1"];
17 |
--------------------------------------------------------------------------------
/lib/ts/version.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | export const package_version = "5.1.5";
16 |
17 | export const supported_fdi = ["1.16", "1.17", "1.18", "1.19", "2.0", "3.0", "3.1", "4.0", "4.1"];
18 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/backend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "supertokens-node",
3 | "version": "0.0.1",
4 | "private": true,
5 | "description": "",
6 | "main": "index.js",
7 | "scripts": {
8 | "start": "npx ts-node-dev --project ./tsconfig.json ./index.ts"
9 | },
10 | "dependencies": {
11 | "cors": "^2.8.5",
12 | "express": "^4.18.1",
13 | "helmet": "^5.1.0",
14 | "morgan": "^1.10.0",
15 | "npm-run-all": "^4.1.5",
16 | "supertokens-node": "latest",
17 | "ts-node-dev": "^2.0.0",
18 | "typescript": "^4.7.2"
19 | },
20 | "devDependencies": {
21 | "@types/cors": "^2.8.12",
22 | "@types/express": "^4.17.17",
23 | "@types/morgan": "^1.9.3",
24 | "@types/node": "^16.11.38",
25 | "nodemon": "^2.0.16"
26 | },
27 | "keywords": [],
28 | "author": "",
29 | "license": "ISC"
30 | }
31 |
--------------------------------------------------------------------------------
/TestingApp/ios/Podfile:
--------------------------------------------------------------------------------
1 | require_relative '../node_modules/react-native/scripts/react_native_pods'
2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
3 |
4 | platform :ios, '11.0'
5 |
6 | target 'TestingApp' do
7 | config = use_native_modules!
8 |
9 | use_react_native!(
10 | :path => config[:reactNativePath],
11 | # to enable hermes on iOS, change `false` to `true` and then install pods
12 | :hermes_enabled => false
13 | )
14 |
15 | target 'TestingAppTests' do
16 | inherit! :complete
17 | # Pods for testing
18 | end
19 |
20 | # Enables Flipper.
21 | #
22 | # Note that if you have use_frameworks! enabled, Flipper will not work and
23 | # you should disable the next line.
24 | use_flipper!()
25 |
26 | post_install do |installer|
27 | react_native_post_install(installer)
28 | __apply_Xcode_12_5_M1_post_install_workaround(installer)
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "with-thirdparty",
4 | "slug": "with-thirdparty",
5 | "version": "1.0.0",
6 | "orientation": "portrait",
7 | "icon": "./assets/icon.png",
8 | "userInterfaceStyle": "light",
9 | "splash": {
10 | "image": "./assets/splash.png",
11 | "resizeMode": "contain",
12 | "backgroundColor": "#ffffff"
13 | },
14 | "assetBundlePatterns": ["**/*"],
15 | "ios": {
16 | "supportsTablet": true,
17 | "bundleIdentifier": "com.supertokens.with-thirdparty"
18 | },
19 | "android": {
20 | "adaptiveIcon": {
21 | "foregroundImage": "./assets/adaptive-icon.png",
22 | "backgroundColor": "#ffffff"
23 | },
24 | "package": "com.supertokens.supertokensexample"
25 | },
26 | "web": {
27 | "favicon": "./assets/favicon.png"
28 | },
29 | "plugins": ["@react-native-google-signin/google-signin"]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ios/RNSuperTokens.h:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | #if __has_include("RCTBridgeModule.h")
17 | #import "RCTBridgeModule.h"
18 | #else
19 | #import
20 | #endif
21 |
22 | @interface RNSuperTokens : NSObject
23 |
24 | @end
25 |
26 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
14 |
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # SuperTokens React Native SDK
4 |
5 |
6 |
8 |
9 | ## About
10 | This is a react native SDK that is responsible for maintaining a SuperTokens session for mobile apps.
11 |
12 | Learn more at https://supertokens.io
13 |
14 | ## Documentation
15 | To see documentation, please click [here](https://supertokens.io/docs/community/introduction).
16 |
17 | ## Contributing
18 | Please refer to the [CONTRIBUTING.md](https://github.com/supertokens/supertokens-react-native/blob/master/CONTRIBUTING.md) file in this repo.
19 |
20 | ## Contact us
21 | For any queries, or support requests, please email us at team@supertokens.io, or join our [Discord](supertokens.io/discord) server.
22 |
23 | ## Authors
24 | Created with :heart: by the folks at SuperTokens.io.
--------------------------------------------------------------------------------
/android/src/main/java/com/reactlibrary/RNSuperTokensPackage.java:
--------------------------------------------------------------------------------
1 |
2 | package com.reactlibrary;
3 |
4 | import java.util.Arrays;
5 | import java.util.Collections;
6 | import java.util.List;
7 |
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.bridge.NativeModule;
10 | import com.facebook.react.bridge.ReactApplicationContext;
11 | import com.facebook.react.uimanager.ViewManager;
12 | import com.facebook.react.bridge.JavaScriptModule;
13 | public class RNSuperTokensPackage implements ReactPackage {
14 | @Override
15 | public List createNativeModules(ReactApplicationContext reactContext) {
16 | return Arrays.asList(new RNSuperTokensModule(reactContext));
17 | }
18 |
19 | // Deprecated from RN 0.47
20 | public List> createJSModules() {
21 | return Collections.emptyList();
22 | }
23 |
24 | @Override
25 | public List createViewManagers(ReactApplicationContext reactContext) {
26 | return Collections.emptyList();
27 | }
28 | }
--------------------------------------------------------------------------------
/TestingApp/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/TestingApp/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 |
24 | # Android/IntelliJ
25 | #
26 | build/
27 | .idea
28 | .gradle
29 | local.properties
30 | *.iml
31 | *.hprof
32 |
33 | # node.js
34 | #
35 | node_modules/
36 | npm-debug.log
37 | yarn-error.log
38 |
39 | # BUCK
40 | buck-out/
41 | \.buckd/
42 | *.keystore
43 | !debug.keystore
44 |
45 | # fastlane
46 | #
47 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
48 | # screenshots whenever they are needed.
49 | # For more information about the recommended setup visit:
50 | # https://docs.fastlane.tools/best-practices/source-control/
51 |
52 | */fastlane/report.xml
53 | */fastlane/Preview.html
54 | */fastlane/screenshots
55 |
56 | # Bundle artifact
57 | *.jsbundle
58 |
59 | # CocoaPods
60 | /ios/Pods/
61 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "with-thirdparty",
3 | "version": "1.0.0",
4 | "main": "node_modules/expo/AppEntry.js",
5 | "scripts": {
6 | "start": "expo start",
7 | "android": "expo run:android",
8 | "ios": "expo run:ios",
9 | "web": "expo start --web"
10 | },
11 | "dependencies": {
12 | "@invertase/react-native-apple-authentication": "^2.3.0",
13 | "@react-native-async-storage/async-storage": "^1.18.2",
14 | "@react-native-google-signin/google-signin": "^10.1.0",
15 | "@react-navigation/native": "^6.1.9",
16 | "@react-navigation/native-stack": "^6.9.17",
17 | "expo": "~49.0.15",
18 | "expo-splash-screen": "~0.20.5",
19 | "expo-status-bar": "~1.6.0",
20 | "react": "18.2.0",
21 | "react-native": "0.72.6",
22 | "react-native-app-auth": "^7.1.0",
23 | "react-native-safe-area-context": "4.6.3",
24 | "react-native-screens": "~3.22.0",
25 | "supertokens-react-native": "^4.0.8"
26 | },
27 | "devDependencies": {
28 | "@babel/core": "^7.20.0",
29 | "@types/react": "~18.2.14",
30 | "typescript": "^5.1.3"
31 | },
32 | "private": true
33 | }
34 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/splash.tsx:
--------------------------------------------------------------------------------
1 | import { NativeStackScreenProps } from "@react-navigation/native-stack";
2 | import { useEffect } from "react";
3 | import { View, Text, StyleSheet } from "react-native";
4 | import SuperTokens from "supertokens-react-native";
5 |
6 | type Props = NativeStackScreenProps;
7 |
8 | export const SplashScreen = ({ navigation }: Props) => {
9 | const checkSessionExists = async () => {
10 | const sessionExists = await SuperTokens.doesSessionExist();
11 |
12 | if (sessionExists) {
13 | navigation.replace("Home");
14 | } else {
15 | navigation.replace("Login");
16 | }
17 | };
18 |
19 | useEffect(() => {
20 | checkSessionExists();
21 | }, []);
22 |
23 | return (
24 |
25 | SuperTokens Example
26 |
27 | );
28 | };
29 |
30 | const styles = StyleSheet.create({
31 | container: {
32 | flex: 1,
33 | backgroundColor: "#fff",
34 | alignItems: "center",
35 | justifyContent: "center",
36 | },
37 | text: {
38 | fontSize: 32,
39 | fontWeight: "bold",
40 | },
41 | });
42 |
--------------------------------------------------------------------------------
/.circleci/updateDocsInWebsite.sh:
--------------------------------------------------------------------------------
1 | # get driver version
2 | version=`cat ../package.json | grep -e '"version":'`
3 | while IFS='"' read -ra ADDR; do
4 | counter=0
5 | for i in "${ADDR[@]}"; do
6 | if [ $counter == 3 ]
7 | then
8 | version=$i
9 | fi
10 | counter=$(($counter+1))
11 | done
12 | done <<< "$version"
13 |
14 | # replace path version with X
15 | IFS='.' read -r -a array <<< "$version"
16 | versionFolder="${array[0]}"."${array[1]}".X
17 |
18 | # create react-native docs dir in repo if not exists
19 | (cd ../../supertokens-backend-website && mkdir -p ./app/docs/sdk/docs/react-native/${versionFolder})
20 |
21 | # copy docs content from this repo to the supertokens-backend-website repo
22 | cp -r ../docs/* ../../supertokens-backend-website/app/docs/sdk/docs/react-native/
23 | cp -r ../docs/* ../../supertokens-backend-website/app/docs/sdk/docs/react-native/${versionFolder}
24 |
25 | # push to git
26 | git config --global user.email "$EMAIL"
27 | git config --global user.name "$NAME"
28 | (cd ../../supertokens-backend-website && git add --all && git commit -m"updates react-native docs" && git pull && git push && ./releaseDev.sh)
--------------------------------------------------------------------------------
/TestingApp/test/setup.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | import MockStorage from "./asyncStorage";
17 |
18 | jest.mock("react-native", () => {
19 | return {
20 | Platform: {},
21 | NativeModules: {}
22 | };
23 | });
24 |
25 | // React native async storage eposes a mocked version to use (Refer to the "../__mocks__/" folder )
26 | // jest.mock("@react-native-async-storage/async-storage", () => {
27 | // return new MockStorage({});
28 | // });
29 |
--------------------------------------------------------------------------------
/lib/build/index.d.ts:
--------------------------------------------------------------------------------
1 | import { InputType, RecipeInterface } from "./types";
2 | export default class AuthHttpRequest {
3 | private static axiosInterceptorQueue;
4 | static init(options: InputType): void;
5 | static getUserId(): Promise;
6 | static getAccessTokenPayloadSecurely(): Promise;
7 | static attemptRefreshingSession: () => Promise;
8 | static doesSessionExist: () => Promise;
9 | static addAxiosInterceptors: (axiosInstance: any) => void;
10 | static signOut: () => Promise;
11 | static getAccessToken: () => Promise;
12 | }
13 | export declare let init: typeof AuthHttpRequest.init;
14 | export declare let getUserId: typeof AuthHttpRequest.getUserId;
15 | export declare let getAccessTokenPayloadSecurely: typeof AuthHttpRequest.getAccessTokenPayloadSecurely;
16 | export declare let attemptRefreshingSession: () => Promise;
17 | export declare let doesSessionExist: () => Promise;
18 | export declare let addAxiosInterceptors: (axiosInstance: any) => void;
19 | export declare let signOut: () => Promise;
20 | export declare let getAccessToken: () => Promise;
21 | export { RecipeInterface, InputType };
22 |
--------------------------------------------------------------------------------
/TestingApp/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "30.0.2"
6 | minSdkVersion = 21
7 | compileSdkVersion = 30
8 | targetSdkVersion = 30
9 | ndkVersion = "21.4.7075529"
10 | }
11 | repositories {
12 | google()
13 | mavenCentral()
14 | }
15 | dependencies {
16 | classpath("com.android.tools.build:gradle:4.2.2")
17 | // NOTE: Do not place your application dependencies here; they belong
18 | // in the individual module build.gradle files
19 | }
20 | }
21 |
22 | allprojects {
23 | repositories {
24 | mavenCentral()
25 | mavenLocal()
26 | maven {
27 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
28 | url("$rootDir/../node_modules/react-native/android")
29 | }
30 | maven {
31 | // Android JSC is installed from npm
32 | url("$rootDir/../node_modules/jsc-android/dist")
33 | }
34 |
35 | google()
36 | maven { url 'https://www.jitpack.io' }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/lib/build/error.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | /**
16 | * This error usually indicates that the API exposed by the backend SDKs responded
17 | * with `{status: "GENERAL_ERROR"}`. This should be used to show errors to the user
18 | * in your frontend application.
19 | */
20 | export class SuperTokensGeneralError extends Error {
21 | constructor(message) {
22 | super(message);
23 | this.isSuperTokensGeneralError = true;
24 | }
25 | static isThisError(err) {
26 | return err.isSuperTokensGeneralError === true;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/google.ts:
--------------------------------------------------------------------------------
1 | import { GoogleSignin } from "@react-native-google-signin/google-signin";
2 | import { API_DOMAIN } from "./constants";
3 |
4 | export const performGoogleSignIn = async (): Promise => {
5 | GoogleSignin.configure({
6 | webClientId: "GOOGLE_WEB_CLIENT_ID",
7 | iosClientId: "GOOGLE_IOS_CLIENT_ID",
8 | });
9 |
10 | try {
11 | const user = await GoogleSignin.signIn({});
12 |
13 | const response = await fetch(API_DOMAIN + "/auth/signinup", {
14 | method: "POST",
15 | headers: {
16 | 'Content-Type': 'application/json; charset=utf-8'
17 | },
18 | body: JSON.stringify({
19 | thirdPartyId: "google",
20 | redirectURIInfo: {
21 | redirectURIOnProviderDashboard: "https://example.com", // this value doesn't matter cause it's mobile login, and Google doesn't check it, but our APIs need some value for it.
22 | redirectURIQueryParams: {
23 | code: user.serverAuthCode,
24 | },
25 | },
26 | }),
27 | });
28 |
29 | if (response.status !== 200) {
30 | throw new Error();
31 | }
32 |
33 | return true;
34 | } catch (e) {
35 | console.log("Google sign in failed with error", e);
36 | }
37 |
38 | return false;
39 | };
40 |
--------------------------------------------------------------------------------
/lib/ts/error.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | /**
17 | * This error usually indicates that the API exposed by the backend SDKs responded
18 | * with `{status: "GENERAL_ERROR"}`. This should be used to show errors to the user
19 | * in your frontend application.
20 | */
21 | export class SuperTokensGeneralError extends Error {
22 | isSuperTokensGeneralError = true;
23 |
24 | constructor(message: string) {
25 | super(message);
26 | }
27 |
28 | static isThisError(err: any): err is SuperTokensGeneralError {
29 | return err.isSuperTokensGeneralError === true;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/lib/build/axios.d.ts:
--------------------------------------------------------------------------------
1 | import { AxiosPromise, AxiosRequestConfig as OriginalAxiosRequestConfig, AxiosResponse } from "axios";
2 | type AxiosRequestConfig = OriginalAxiosRequestConfig & {
3 | __supertokensSessionRefreshAttempts?: number;
4 | __supertokensAddedAuthHeader?: boolean;
5 | };
6 | export declare function interceptorFunctionRequestFulfilled(config: AxiosRequestConfig): Promise;
7 | export declare function responseInterceptor(axiosInstance: any): (response: AxiosResponse) => Promise>;
8 | export declare function responseErrorInterceptor(axiosInstance: any): (error: any) => Promise>;
9 | /**
10 | * @class AuthHttpRequest
11 | * @description wrapper for common http methods.
12 | */
13 | export default class AuthHttpRequest {
14 | /**
15 | * @description sends the actual http request and returns a response if successful/
16 | * If not successful due to session expiry reasons, it
17 | * attempts to call the refresh token API and if that is successful, calls this API again.
18 | * @throws Error
19 | */
20 | static doRequest: (httpCall: (config: AxiosRequestConfig) => AxiosPromise, config: AxiosRequestConfig, url?: string, prevResponse?: AxiosResponse, prevError?: any, viaInterceptor?: boolean) => Promise>;
21 | }
22 | export {};
23 |
--------------------------------------------------------------------------------
/lib/build/fetch.d.ts:
--------------------------------------------------------------------------------
1 | import { InputType, NormalisedInputType, RecipeInterface } from "./types";
2 | import { LocalSessionState } from "./utils";
3 | /**
4 | * @class AuthHttpRequest
5 | * @description wrapper for common http methods.
6 | */
7 | export default class AuthHttpRequest {
8 | static refreshTokenUrl: string;
9 | static signOutUrl: string;
10 | static initCalled: boolean;
11 | static rid: string;
12 | static env: any;
13 | static recipeImpl: RecipeInterface;
14 | static config: NormalisedInputType;
15 | static init(options: InputType): void;
16 | /**
17 | * @description sends the actual http request and returns a response if successful/
18 | * If not successful due to session expiry reasons, it
19 | * attempts to call the refresh token API and if that is successful, calls this API again.
20 | * @throws Error
21 | */
22 | static doRequest: (httpCall: (config?: RequestInit) => Promise, config?: RequestInit, url?: any) => Promise;
23 | static attemptRefreshingSession: () => Promise;
24 | }
25 | export declare function onUnauthorisedResponse(preRequestLocalSessionState: LocalSessionState): Promise<{
26 | result: "SESSION_EXPIRED";
27 | error?: any;
28 | } | {
29 | result: "API_ERROR";
30 | error: any;
31 | } | {
32 | result: "RETRY";
33 | }>;
34 |
--------------------------------------------------------------------------------
/lib/build/logger.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | import { package_version as version } from "./version";
16 | const SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens";
17 | let __supertokensWebsiteLogging = false;
18 | export function enableLogging() {
19 | __supertokensWebsiteLogging = true;
20 | }
21 | export function disableLogging() {
22 | __supertokensWebsiteLogging = false;
23 | }
24 | export function logDebugMessage(message) {
25 | if (__supertokensWebsiteLogging) {
26 | console.log(
27 | `${SUPERTOKENS_DEBUG_NAMESPACE} {t: "${new Date().toISOString()}", message: \"${message}\", supertokens-react-native: "${version}"}`
28 | );
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/TestingApp/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 | # Automatically convert third-party libraries to use AndroidX
25 | android.enableJetifier=true
26 |
27 | # Version of flipper SDK to use with React Native
28 | FLIPPER_VERSION=0.99.0
29 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## Summary of change
2 | (A few sentences about this PR)
3 |
4 | ## Related issues
5 | - Link to issue1 here
6 | - Link to issue1 here
7 |
8 | ## Test Plan
9 | (Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Bonus points for screenshots and videos!)
10 |
11 | ## Documentation changes
12 | (If relevant, please create a PR in our [docs repo](https://github.com/supertokens/docs), or create a checklist here highlighting the necessary changes)
13 |
14 | ## Checklist for important updates
15 | - [ ] Changelog has been updated
16 | - [ ] `frontendDriverInterfaceSupported.json` file has been updated (if needed)
17 | - Along with the associated array in `lib/ts/version.ts`
18 | - [ ] Changes to the version if needed
19 | - In `package.json`
20 | - In `package-lock.json`
21 | - In `lib/ts/version.ts`
22 | - [ ] Had run `npm run build-pretty`
23 | - [ ] Had installed and ran the pre-commit hook
24 | - [ ] Issue this PR against the latest non released version branch.
25 | - To know which one it is, run find the latest released tag (`git tag`) in the format `vX.Y.Z`, and then find the latest branch (`git branch --all`) whose `X.Y` is greater than the latest released tag.
26 | - If no such branch exists, then create one from the latest released branch.
27 |
28 | ## Remaining TODOs for this PR
29 | - [ ] Item1
30 | - [ ] Item2
--------------------------------------------------------------------------------
/lib/ts/logger.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | import { package_version as version } from "./version";
17 |
18 | const SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens";
19 |
20 | let __supertokensWebsiteLogging = false;
21 |
22 | export function enableLogging() {
23 | __supertokensWebsiteLogging = true;
24 | }
25 |
26 | export function disableLogging() {
27 | __supertokensWebsiteLogging = false;
28 | }
29 |
30 | export function logDebugMessage(message: string) {
31 | if (__supertokensWebsiteLogging) {
32 | console.log(
33 | `${SUPERTOKENS_DEBUG_NAMESPACE} {t: "${new Date().toISOString()}", message: \"${message}\", supertokens-react-native: "${version}"}`
34 | );
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/apple.ts:
--------------------------------------------------------------------------------
1 | import { appleAuth } from "@invertase/react-native-apple-authentication";
2 | import { API_DOMAIN } from "./constants";
3 |
4 | export const performAppleLogin = async (): Promise => {
5 | try {
6 | const appleAuthRequestResponse = await appleAuth.performRequest({
7 | requestedOperation: appleAuth.Operation.LOGIN,
8 | // Note: it appears putting FULL_NAME first is important, see issue https://github.com/invertase/react-native-apple-authentication/issues/293
9 | requestedScopes: [appleAuth.Scope.EMAIL],
10 | });
11 |
12 | const response = await fetch(API_DOMAIN + "/auth/signinup", {
13 | method: "POST",
14 | headers: {
15 | 'Content-Type': 'application/json; charset=utf-8'
16 | },
17 | body: JSON.stringify({
18 | thirdPartyId: "apple",
19 | redirectURIInfo: {
20 | redirectURIOnProviderDashboard: "https://example.com", // this value doesn't matter cause it's mobile login, and Google doesn't check it, but our APIs need some value for it.
21 | redirectURIQueryParams: {
22 | code: appleAuthRequestResponse.authorizationCode,
23 | },
24 | },
25 | }),
26 | });
27 |
28 | if (response.status !== 200) {
29 | throw new Error();
30 | }
31 |
32 | return true;
33 | } catch (e) {
34 | console.log("Apple sign in failed with error", e);
35 | }
36 |
37 | return false;
38 | };
39 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/backend/index.ts:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | import cors from "cors";
3 | import supertokens from "supertokens-node";
4 | import { verifySession } from "supertokens-node/recipe/session/framework/express";
5 | import { middleware, errorHandler, SessionRequest } from "supertokens-node/framework/express";
6 | import { SuperTokensConfig } from "./config";
7 | import Multitenancy from "supertokens-node/recipe/multitenancy";
8 |
9 | supertokens.init(SuperTokensConfig);
10 |
11 | const app = express();
12 |
13 | app.use(
14 | cors({
15 | origin: "http://localhost:3000",
16 | allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],
17 | methods: ["GET", "PUT", "POST", "DELETE"],
18 | credentials: true,
19 | })
20 | );
21 |
22 | // This exposes all the APIs from SuperTokens to the client.
23 | app.use(middleware());
24 |
25 | // An example API that requires session verification
26 | app.get("/sessioninfo", verifySession(), async (req: SessionRequest, res) => {
27 | let session = req.session;
28 | res.send({
29 | sessionHandle: session!.getHandle(),
30 | userId: session!.getUserId(),
31 | accessTokenPayload: session!.getAccessTokenPayload(),
32 | });
33 | });
34 |
35 | // In case of session related errors, this error handler
36 | // returns 401 to the client.
37 | app.use(errorHandler());
38 |
39 | app.listen(3001, () => console.log(`API Server listening on port 3001`));
40 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/App.tsx:
--------------------------------------------------------------------------------
1 | import SuperTokens from "supertokens-react-native";
2 | import { API_DOMAIN } from "./constants";
3 | import { createNativeStackNavigator } from "@react-navigation/native-stack";
4 | import { NavigationContainer } from "@react-navigation/native";
5 | import { SplashScreen } from "./splash";
6 | import { LoginSreen } from "./login";
7 | import { HomeScreen } from "./home";
8 | import { SafeAreaProvider } from "react-native-safe-area-context";
9 |
10 | SuperTokens.init({
11 | apiDomain: API_DOMAIN,
12 | });
13 |
14 | const Stack = createNativeStackNavigator();
15 |
16 | export default function App() {
17 | return (
18 |
19 |
20 |
21 |
28 |
35 |
42 |
43 |
44 |
45 | );
46 | }
47 |
--------------------------------------------------------------------------------
/.circleci/markDevTagAsTestNotPassed.sh:
--------------------------------------------------------------------------------
1 | # get git branch name-----------
2 | branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
3 | branch_name="(unnamed branch)" # detached HEAD
4 |
5 | branch_name=${branch_name##refs/heads/}
6 |
7 | if [[ $branch_name =~ ^test-cicd/.*$ ]]
8 | then
9 | echo "This is a ci testing branch ($branch_name), exiting early"
10 | exit 0
11 | fi
12 |
13 | frontendDriverJson=`cat ../frontendDriverInterfaceSupported.json`
14 | frontendDriverLength=`echo $frontendDriverJson | jq ".versions | length"`
15 | frontendDriverArray=`echo $frontendDriverJson | jq ".versions"`
16 | echo "got frontend driver relations"
17 |
18 | # get sdk version
19 | version=`cat ../package.json | grep -e '"version":'`
20 | while IFS='"' read -ra ADDR; do
21 | counter=0
22 | for i in "${ADDR[@]}"; do
23 | if [ $counter == 3 ]
24 | then
25 | version=$i
26 | fi
27 | counter=$(($counter+1))
28 | done
29 | done <<< "$version"
30 |
31 | responseStatus=`curl -s -o /dev/null -w "%{http_code}" -X PUT \
32 | https://api.supertokens.io/0/frontend \
33 | -H 'Content-Type: application/json' \
34 | -H 'api-version: 0' \
35 | -d "{
36 | \"password\": \"$SUPERTOKENS_API_KEY\",
37 | \"version\":\"$version\",
38 | \"name\": \"react-native\",
39 | \"frontendDriverInterfaces\": $frontendDriverArray
40 | }"`
41 | if [ $responseStatus -ne "200" ]
42 | then
43 | echo "failed core PUT API status code: $responseStatus. Exiting!"
44 | exit 1
45 | fi
--------------------------------------------------------------------------------
/examples/with-thirdparty/github.ts:
--------------------------------------------------------------------------------
1 | import { authorize } from "react-native-app-auth";
2 | import { API_DOMAIN } from "./constants";
3 |
4 | export const performGithubLogin = async (): Promise => {
5 | try {
6 | const result = await authorize({
7 | serviceConfiguration: {
8 | authorizationEndpoint: "https://github.com/login/oauth/authorize",
9 | tokenEndpoint: "https://github.com/login/oauth/access_token",
10 | revocationEndpoint:
11 | "https://github.com/settings/connections/applications/",
12 | },
13 | additionalHeaders: { Accept: "application/json" },
14 | clientId: "GITHUB_CLIENT_ID",
15 | redirectUrl: "com.supertokens.supertokensexample://oauthredirect",
16 | scopes: ["user"],
17 | skipCodeExchange: true,
18 | });
19 |
20 | const response = await fetch(API_DOMAIN + "/auth/signinup", {
21 | method: "POST",
22 | body: JSON.stringify({
23 | thirdPartyId: "github",
24 | redirectURIInfo: {
25 | redirectURIOnProviderDashboard: "com.supertokens.supertokensexample://oauthredirect",
26 | redirectURIQueryParams: {
27 | code: result.authorizationCode,
28 | },
29 | },
30 | }),
31 | });
32 |
33 | if (response.status !== 200) {
34 | throw new Error();
35 | }
36 |
37 | return true;
38 | } catch (e) {
39 | console.log("Github login failed with error", e);
40 | }
41 |
42 | return false;
43 | };
44 |
--------------------------------------------------------------------------------
/.circleci/markAsSuccess.sh:
--------------------------------------------------------------------------------
1 | # get git branch name-----------
2 | branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
3 | branch_name="(unnamed branch)" # detached HEAD
4 |
5 | branch_name=${branch_name##refs/heads/}
6 |
7 | if [[ $branch_name =~ ^test-cicd/.*$ ]]
8 | then
9 | echo "This is a ci testing branch ($branch_name), exiting early"
10 | exit 0
11 | fi
12 |
13 | frontendDriverJson=`cat ../frontendDriverInterfaceSupported.json`
14 | frontendDriverLength=`echo $frontendDriverJson | jq ".versions | length"`
15 | frontendDriverArray=`echo $frontendDriverJson | jq ".versions"`
16 | echo "got frontend driver relations"
17 |
18 | # get sdk version
19 | version=`cat ../package.json | grep -e '"version":'`
20 | while IFS='"' read -ra ADDR; do
21 | counter=0
22 | for i in "${ADDR[@]}"; do
23 | if [ $counter == 3 ]
24 | then
25 | version=$i
26 | fi
27 | counter=$(($counter+1))
28 | done
29 | done <<< "$version"
30 |
31 | echo "calling /frontend PATCH to make testing passed"
32 | responseStatus=`curl -s -o /dev/null -w "%{http_code}" -X PATCH \
33 | https://api.supertokens.io/0/frontend \
34 | -H 'Content-Type: application/json' \
35 | -H 'api-version: 0' \
36 | -d "{
37 | \"password\": \"$SUPERTOKENS_API_KEY\",
38 | \"version\":\"$version\",
39 | \"name\": \"react-native\",
40 | \"testPassed\": true
41 | }"`
42 | if [ $responseStatus -ne "200" ]
43 | then
44 | echo "patch api failed"
45 | exit 1
46 | fi
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015, Salesforce.com, Inc.
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5 |
6 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7 |
8 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9 |
10 | 3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11 |
12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13 |
--------------------------------------------------------------------------------
/TestingApp/android/app/_BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.testingapp",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.testingapp",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/TestingApp/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | ; We fork some components by platform
3 | .*/*[.]android.js
4 |
5 | ; Ignore "BUCK" generated dirs
6 | /\.buckd/
7 |
8 | ; Ignore polyfills
9 | node_modules/react-native/Libraries/polyfills/.*
10 |
11 | ; Flow doesn't support platforms
12 | .*/Libraries/Utilities/LoadingView.js
13 |
14 | [untyped]
15 | .*/node_modules/@react-native-community/cli/.*/.*
16 |
17 | [include]
18 |
19 | [libs]
20 | node_modules/react-native/interface.js
21 | node_modules/react-native/flow/
22 |
23 | [options]
24 | emoji=true
25 |
26 | exact_by_default=true
27 |
28 | format.bracket_spacing=false
29 |
30 | module.file_ext=.js
31 | module.file_ext=.json
32 | module.file_ext=.ios.js
33 |
34 | munge_underscores=true
35 |
36 | module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1'
37 | module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub'
38 |
39 | suppress_type=$FlowIssue
40 | suppress_type=$FlowFixMe
41 | suppress_type=$FlowFixMeProps
42 | suppress_type=$FlowFixMeState
43 |
44 | [lints]
45 | sketchy-null-number=warn
46 | sketchy-null-mixed=warn
47 | sketchy-number=warn
48 | untyped-type-import=warn
49 | nonstrict-import=warn
50 | deprecated-type=warn
51 | unsafe-getters-setters=warn
52 | unnecessary-invariant=warn
53 | signature-verification-failure=warn
54 |
55 | [strict]
56 | deprecated-type
57 | nonstrict-import
58 | sketchy-null
59 | unclear-type
60 | unsafe-getters-setters
61 | untyped-import
62 | untyped-type-import
63 |
64 | [version]
65 | ^0.158.0
66 |
--------------------------------------------------------------------------------
/TestingApp/test/server/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/TestingApp/ios/TestingApp/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | TestingApp
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 | NSExceptionDomains
30 |
31 | localhost
32 |
33 | NSExceptionAllowsInsecureHTTPLoads
34 |
35 |
36 |
37 |
38 | NSLocationWhenInUseUsageDescription
39 |
40 | UILaunchStoryboardName
41 | LaunchScreen
42 | UIRequiredDeviceCapabilities
43 |
44 | armv7
45 |
46 | UISupportedInterfaceOrientations
47 |
48 | UIInterfaceOrientationPortrait
49 | UIInterfaceOrientationLandscapeLeft
50 | UIInterfaceOrientationLandscapeRight
51 |
52 | UIViewControllerBasedStatusBarAppearance
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/lib/build/utils.d.ts:
--------------------------------------------------------------------------------
1 | import { InputType, NormalisedInputType, TokenType } from "./types";
2 | export declare function isAnIpAddress(ipaddress: string): boolean;
3 | export declare function normaliseURLDomainOrThrowError(input: string): string;
4 | export declare function normaliseURLPathOrThrowError(input: string): string;
5 | export declare function normaliseSessionScopeOrThrowError(cookieDomain: string): string;
6 | export declare function validateAndNormaliseInputOrThrowError(options: InputType): NormalisedInputType;
7 | export declare function setToken(tokenType: TokenType, value: string): Promise;
8 | export declare function storeInStorage(name: string, value: string, expiry: number): Promise;
9 | /**
10 | * Last access token update is used to record the last time the access token had changed.
11 | * This is used to synchronise parallel calls to the refresh API to prevent multiple calls
12 | * to the refresh endpoint
13 | */
14 | export declare function saveLastAccessTokenUpdate(): Promise;
15 | export declare function getStorageNameForToken(tokenType: TokenType): "st-access-token" | "st-refresh-token";
16 | export declare function getTokenForHeaderAuth(tokenType: TokenType): Promise;
17 | export type LocalSessionState = {
18 | status: "NOT_EXISTS" | "MAY_EXIST";
19 | } | {
20 | status: "EXISTS";
21 | lastAccessTokenUpdate: string;
22 | };
23 | /**
24 | * The web SDK has additional checks for this function. This difference is because
25 | * for the mobile SDKs there will never be a case where the fronttoken is undefined
26 | * but a session may still exist
27 | */
28 | export declare function getLocalSessionState(): Promise;
29 | export declare function fireSessionUpdateEventsIfNecessary(wasLoggedIn: boolean, status: number, frontTokenHeaderFromResponse: string | null | undefined): void;
30 |
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/lib/pubsuffix-psl.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Copyright (c) 2018, Salesforce.com, Inc.
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions are met:
7 | *
8 | * 1. Redistributions of source code must retain the above copyright notice,
9 | * this list of conditions and the following disclaimer.
10 | *
11 | * 2. Redistributions in binary form must reproduce the above copyright notice,
12 | * this list of conditions and the following disclaimer in the documentation
13 | * and/or other materials provided with the distribution.
14 | *
15 | * 3. Neither the name of Salesforce.com nor the names of its contributors may
16 | * be used to endorse or promote products derived from this software without
17 | * specific prior written permission.
18 | *
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 | * POSSIBILITY OF SUCH DAMAGE.
30 | */
31 | "use strict";
32 | var psl = require("psl");
33 |
34 | function getPublicSuffix(domain) {
35 | return psl.get(domain);
36 | }
37 |
38 | exports.getPublicSuffix = getPublicSuffix;
39 |
--------------------------------------------------------------------------------
/TestingApp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Example",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "android": "react-native run-android",
7 | "ios": "react-native run-ios",
8 | "start": "react-native start",
9 | "test": "npx jest test/*.spec.js --runInBand --silent=false",
10 | "test-ci": "npx jest --listTests test/*.spec.js | circleci tests run --command=\"JEST_JUNIT_ADD_FILE_ATTRIBUTE=true xargs npx jest --ci --reporters=default --reporters=jest-junit --runInBand --\" --verbose --split-by=timings",
11 | "lint": "eslint ."
12 | },
13 | "dependencies": {
14 | "@react-native-async-storage/async-storage": "^1.12.1",
15 | "axios": "0.19.2",
16 | "headers-polyfill": "^4.0.3",
17 | "react": "17.0.2",
18 | "react-native": "0.66.1",
19 | "supertokens-react-native": "github:supertokens/supertokens-react-native#5.1"
20 | },
21 | "devDependencies": {
22 | "@babel/core": "^7.12.9",
23 | "@babel/runtime": "^7.12.5",
24 | "@react-native-community/eslint-config": "^2.0.0",
25 | "axios-cookiejar-support": "github:supertokens/axios-cookiejar-support#0.5.1",
26 | "babel-jest": "^26.6.3",
27 | "babel-preset-react-app": "7.0.0",
28 | "eslint": "7.14.0",
29 | "fetch-cookie": "^3.1.0",
30 | "isomorphic-fetch": "^3.0.0",
31 | "jest": "^26.6.3",
32 | "jest-junit": "^16.0.0",
33 | "metro-react-native-babel-preset": "^0.66.2",
34 | "node-fetch": "^2.7.0",
35 | "react-test-renderer": "17.0.2",
36 | "ts-jest": "^26.5.6"
37 | },
38 | "jest": {
39 | "preset": "react-native",
40 | "setupFiles": [
41 | "./test/setup.js"
42 | ],
43 | "testEnvironment": "node",
44 | "transform": {
45 | "^.+\\.(ts|tsx)?$": "ts-jest",
46 | "^.*\\.(js|jsx)$": "babel-jest"
47 | },
48 | "transformIgnorePatterns": [
49 | "/node_modules/.+\\.(js | ts | jsx | tsx)"
50 | ]
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/login.tsx:
--------------------------------------------------------------------------------
1 | import { View, StyleSheet, Button, Platform } from "react-native";
2 | import { performGoogleSignIn } from "./google";
3 | import { NativeStackScreenProps } from "@react-navigation/native-stack";
4 | import { performGithubLogin } from "./github";
5 | import { performAppleLogin } from "./apple";
6 |
7 | type Props = NativeStackScreenProps;
8 |
9 | export const LoginSreen = ({ navigation }: Props) => {
10 | const onGoogleClicked = async () => {
11 | const result = await performGoogleSignIn();
12 |
13 | if (result) {
14 | navigation.replace("Home");
15 | } else {
16 | navigation.replace("Splash");
17 | }
18 | };
19 | const onGithubClicked = async () => {
20 | const result = await performGithubLogin();
21 |
22 | if (result) {
23 | navigation.replace("Home");
24 | } else {
25 | navigation.replace("Splash");
26 | }
27 | };
28 | const onAppleClicked = async () => {
29 | const result = await performAppleLogin();
30 |
31 | if (result) {
32 | navigation.replace("Home");
33 | } else {
34 | navigation.replace("Splash");
35 | }
36 | };
37 |
38 | return (
39 |
40 |
41 |
42 |
43 |
44 | {Platform.OS === "ios" && (
45 |
46 | )}
47 |
48 | );
49 | };
50 |
51 | const styles = StyleSheet.create({
52 | container: {
53 | flex: 1,
54 | backgroundColor: "#fff",
55 | alignItems: "center",
56 | justifyContent: "center",
57 | },
58 | text: {
59 | fontSize: 32,
60 | fontWeight: "bold",
61 | },
62 | spacer: {
63 | height: 16,
64 | },
65 | });
66 |
--------------------------------------------------------------------------------
/otherInfo.txt:
--------------------------------------------------------------------------------
1 | Structure:
2 | There will be a pure JS implementation and a native implementation.
3 |
4 | If the user links the lib, then ONLY the native implementation will work, else only the pure JS implementation will work.
5 |
6 | Both the implementation's data - cookies, storage items, should be "in sync". If the user moves from one to the other, it should not break things and should not cause user logouts.
7 |
8 |
9 | Parts of readme:
10 | ---------------------------------
11 |
12 | ## Getting started
13 |
14 | `$ npm install react-native-lib --save`
15 |
16 | ### Mostly automatic installation
17 |
18 | `$ react-native link react-native-lib`
19 |
20 | ### Manual installation
21 |
22 |
23 | #### iOS
24 |
25 | 1. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]`
26 | 2. Go to `node_modules` ➜ `react-native-lib` and add `RNSuperTokens.xcodeproj`
27 | 3. In XCode, in the project navigator, select your project. Add `libRNSuperTokens.a` to your project's `Build Phases` ➜ `Link Binary With Libraries`
28 | 4. Run your project (`Cmd+R`)<
29 |
30 | #### Android
31 |
32 | 1. Open up `android/app/src/main/java/[...]/MainActivity.java`
33 | - Add `import io.supertokens.reactnative.RNSuperTokensPackage;` to the imports at the top of the file
34 | - Add `new RNSuperTokensPackage()` to the list returned by the `getPackages()` method
35 | 2. Append the following lines to `android/settings.gradle`:
36 | ```
37 | include ':react-native-lib'
38 | project(':react-native-lib').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-lib/android')
39 | ```
40 | 3. Insert the following lines inside the dependencies block in `android/app/build.gradle`:
41 | ```
42 | compile project(':react-native-lib')
43 | ```
44 |
45 | ## Usage
46 | ```javascript
47 | import RNSuperTokens from 'react-native-lib';
48 |
49 | // TODO: What to do with the module?
50 | RNSuperTokens;
51 | ```
52 |
--------------------------------------------------------------------------------
/TestingApp/test/asyncStorage.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | export default class MockStorage {
17 | constructor(cache = {}) {
18 | this.storageCache = cache;
19 | }
20 |
21 | setItem = jest.fn((key, value) => {
22 | return new Promise((resolve, reject) => {
23 | return typeof key !== "string" || typeof value !== "string"
24 | ? reject(new Error("key and value must be string"))
25 | : resolve((this.storageCache[key] = value));
26 | });
27 | });
28 |
29 | getItem = jest.fn(key => {
30 | return new Promise(resolve => {
31 | return this.storageCache.hasOwnProperty(key) ? resolve(this.storageCache[key]) : resolve(null);
32 | });
33 | });
34 |
35 | removeItem = jest.fn(key => {
36 | return new Promise((resolve, reject) => {
37 | return this.storageCache.hasOwnProperty(key) ? resolve(delete this.storageCache[key]) : resolve(null);
38 | });
39 | });
40 |
41 | clear = jest.fn(key => {
42 | return new Promise((resolve, reject) => resolve((this.storageCache = {})));
43 | });
44 |
45 | getAllKeys = jest.fn(key => {
46 | return new Promise((resolve, reject) => resolve(Object.keys(this.storageCache)));
47 | });
48 | }
49 |
--------------------------------------------------------------------------------
/TestingApp/ios/TestingAppTests/TestingAppTests.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import
6 |
7 | #define TIMEOUT_SECONDS 600
8 | #define TEXT_TO_LOOK_FOR @"Welcome to React"
9 |
10 | @interface TestingAppTests : XCTestCase
11 |
12 | @end
13 |
14 | @implementation TestingAppTests
15 |
16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
17 | {
18 | if (test(view)) {
19 | return YES;
20 | }
21 | for (UIView *subview in [view subviews]) {
22 | if ([self findSubviewInView:subview matching:test]) {
23 | return YES;
24 | }
25 | }
26 | return NO;
27 | }
28 |
29 | - (void)testRendersWelcomeScreen
30 | {
31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33 | BOOL foundElement = NO;
34 |
35 | __block NSString *redboxError = nil;
36 | #ifdef DEBUG
37 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
38 | if (level >= RCTLogLevelError) {
39 | redboxError = message;
40 | }
41 | });
42 | #endif
43 |
44 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
45 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
46 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47 |
48 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
49 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
50 | return YES;
51 | }
52 | return NO;
53 | }];
54 | }
55 |
56 | #ifdef DEBUG
57 | RCTSetLogFunction(RCTDefaultLogFunction);
58 | #endif
59 |
60 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
61 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
62 | }
63 |
64 |
65 | @end
66 |
--------------------------------------------------------------------------------
/docs/assets/search.js:
--------------------------------------------------------------------------------
1 | window.searchData = "eJytWV1v4ygU/S/01WoD5Put86WptKMZdWb2xapW1JDGqmMswN1WVf/7yjYJYLBDPfuUyL7nnGtzuFzDKxD8Xwm26St4zEsKthCtE1CSAwNbQNmO1IUCCahFAbYgK4iUTF7p65d7dShAcrwMtgC8JUeeBUQnnoyXUok6U1yMcl24gRZvAioiWKmspIwUms1NzoTS6+ecy5tSMZGxSnEhx0UJpaRB5C5imrpS7FCpW7YTTO7z8uEnkzLn5ZkMOpQ4oeQJNSkLypnUwp+fczk+gBdNtBZkOnqS6gNT11nGpPzFH9mZJ35girSxSsf+D4o/yEvBCf3Jslqw4uU9CVQdVBro1Hx+SyZu6FntWjKR06k6eZmfGVMdMYld5g/l9/qMQBPE6/dpbFZwYYrCTVnV6tdLxU5C6qVi8up0fbS8wBmam1lX5R+IZD+I2o+SXZAqvyeSVV1gOHOT17DaJ34geXlWix7DpirVil9T+lEwykqVk0KekawVJ5RmTvxEbVaS+4J9Yvf1w1/84YxwF0yb4KILnqh6IM+3TImX664iyi9c6EKmS+p4HgfyLBq4Lqhyx4WubOIEn5gZL7+Skhbs81MDGM2Cl/s2lOnQqYpPTIicjs+PCytqok4l2PWPm6+cP44rVYKRKt93cRO15HFVqnLB6E9FVC0/8nPPeFqdWpRsURn/k2fWjO268YFkj6ykMXNaw9o1476D/ekcb7l+CVLKHRPfmNpzOp5DC1AacDgC4tX7dfiWZXnF2nZpR7L+SPTuvqMmj/Vhw9zv68b6uQ/n8oWpbG/ncl3SW6ZqUX7jNN/lrIuIzHDXxNoZkpKKlu2g2Xaa7Y/yHuzjRrKL7uYic4jrsUYSmtZpxWfX67jGMznTd0Wq9jukEc1zfdKwotuT7Xld0E/85OCcl03LQ7+Xv0URlUjLQHluMTS9EOVlLYoJ+WEUN9efiMib7kBehcJGC4otce7DypIZCI2VGpx1RqIfEks98IlkiN2AabRDc3RIpRf/DtHe1HMEunuxZM4XjeFpLsdS9CelYdF3QkR3CchLyp7B9hU8MdE6agvQJb7cgATsclbQZnOk00hAxg+HrqejPKvbv3c67G+Wtbbfpl301Qwk6SzB6HKxhnd3SXoEtzfaC0cOc6UFQpCkMASEHhA6QASSFCVofglnaweIPCBygBgkKU7Q6nK+wg4Qe0DsAOcgSechxbkHnDvABUjSRUhx4QEXDnAJknQZUlx6wKUDXIEkXYWAKw+4coBrkKTrUKprD7h2gBuQpJuQ4sYDblwDNH6AQe9A3zyw557WPmH/BAzkOgg2voAoCPZNBF0XwcYbEAfBvpGg6yTY+APOg2DfTNB1E2w8AhdBsG8o6DoKNj6ByyDYNxV0XQUbr8BVEOwbC7rOgo1f4DoI9s0FXXfBxjNwEwT7BoOuw1DjGRR0GPIdhlyHocYzKOgw5DsM9WpUW6SCDkOBMuU6DOHBCucbDLkGQ41lUNCdyDcYcg2GFkOFDvn+Qq6/0GDJQr69kGsvNFi1kO8u5LoLrYfqD/LNhVxzocYuKDgbkW8u5JoLz4ZGCfvewq63MBxcinxrYddaGA0NEvadhXsrIB5akHBgDXSdhedDA4x9Y2HXWHgxNMDYNxZ2jYWXQysT9o2FXWPh1ZA5sG8sfantlZ6YUIzedD1TmoLw5/or+Ee3Vaf+7BUgsH19SwDC3S+eNb9vpqlqr576quZek8V7vrYtWWzpzuOE7L1hwwShYYIwlum4K2TxWG8CojiewWMhQ2s95/G9RiYZ2Cu2srV4IY4idM7uLCaLKIrndOhoOGaGI840/iaIIZsbsrl25EK/ubhh8Ta7rYe1yGGc7fonYYZsYbiOCcaNxJkdF6OwNApL/Sr0L45O/rijYlhXhnWlWfUvXkSxdh+DhnBtCNeaaBlJVNVKtUdM1hhZboJxdoo4VrD4rXGDcQ/cOzCwuKwRgnHPbM4DLBprSOAqisbe7LeIrKGA6ygi0W4g5WZ72SrS9uIQN/eGTwKsJDdWkpv30Ib29a10LeOgOOOc23SzyK3KgSKTPm4tGhbryTd66h1nTNywBw8XrCytao4iyvldAqq8YkVeMrBN797e/gNTNVaL";
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = findProperty('android.buildToolsVersion') ?: '33.0.0'
6 | minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '21')
7 | compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '33')
8 | targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '33')
9 | kotlinVersion = findProperty('android.kotlinVersion') ?: '1.8.10'
10 | frescoVersion = findProperty('expo.frescoVersion') ?: '2.5.0'
11 | googlePlayServicesAuthVersion = "20.7.0"
12 |
13 | // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
14 | ndkVersion = "23.1.7779620"
15 | }
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | dependencies {
21 | classpath('com.android.tools.build:gradle:7.4.2')
22 | classpath('com.facebook.react:react-native-gradle-plugin')
23 | classpath 'com.google.gms:google-services:4.4.0'
24 | }
25 | }
26 |
27 | allprojects {
28 | repositories {
29 | maven {
30 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
31 | url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
32 | }
33 | maven {
34 | // Android JSC is installed from npm
35 | url(new File(['node', '--print', "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), '../dist'))
36 | }
37 |
38 | maven {
39 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
40 | url "$rootDir/../node_modules/react-native/android"
41 | }
42 |
43 | google()
44 | mavenCentral()
45 | maven { url 'https://www.jitpack.io' }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
21 |
22 |
23 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | # this allows you to use CircleCI's dynamic configuration feature
4 | setup: true
5 |
6 | orbs:
7 | continuation: circleci/continuation@0.1.2
8 | slack: circleci/slack@3.4.2
9 | jq: circleci/jq@2.2.0
10 | jobs:
11 | publish:
12 | docker:
13 | - image: rishabhpoddar/supertokens_website_sdk_testing
14 | steps:
15 | - checkout
16 | - run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
17 | - run:
18 | name: Publish
19 | command: |
20 | cd .circleci
21 | ./publish.sh
22 | - slack/status
23 | test:
24 | machine:
25 | image: ubuntu-2204:2024.04.4
26 | steps:
27 | - checkout
28 | - run:
29 | name: Generate config
30 | command: cd .circleci && ./generateConfig.sh
31 | - continuation/continue:
32 | configuration_path: .circleci/config_continue.yml
33 | update-docs:
34 | docker:
35 | - image: rishabhpoddar/supertokens_website_sdk_testing_node_16
36 | steps:
37 | - run: git config --global url."https://github.com/".insteadOf ssh://git@github.com/ # This makes npm use http instead of ssh (required for node 16)
38 | - checkout
39 | - run: cd ../ && git clone git@github.com:supertokens/supertokens-backend-website.git
40 | - run: (cd .circleci && ./updateDocsInWebsite.sh)
41 | - slack/status
42 |
43 | workflows:
44 | version: 2
45 | tagged-build:
46 | jobs:
47 | - publish:
48 | context:
49 | - slack-notification
50 | filters:
51 | tags:
52 | only: /v[0-9]+(\.[0-9]+)*/
53 | branches:
54 | ignore: /.*/
55 | - test:
56 | context:
57 | - slack-notification
58 | filters:
59 | tags:
60 | only: /dev-v[0-9]+(\.[0-9]+)*/
61 | branches:
62 | only: /test-cicd\/.*/
63 | - update-docs:
64 | context:
65 | - slack-notification
66 | filters:
67 | branches:
68 | only:
69 | - master
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "supertokens-react-native",
3 | "version": "5.1.5",
4 | "description": "React Native SDK for SuperTokens",
5 | "main": "index.js",
6 | "scripts": {
7 | "build-check": "cd lib && npx tsc -p tsconfig.json --skipLibCheck --noEmit",
8 | "build": "cd lib && npx tsc -p tsconfig.json --skipLibCheck && cd ../ && cd test/playground && npx tsc -p tsconfig.json",
9 | "pretty": "npx prettier --write --config .prettierrc \"lib/ts/**/*.ts\" \"lib/build/**/*.js\" \"TestingApp/**/*.js\" \"examples/**/*.js\"",
10 | "build-pretty": "npm run build && npm run pretty",
11 | "pretty-check": "npx prettier --check --config .prettierrc \"lib/ts/**/*.ts\" \"lib/build/**/*.js\" \"TestingApp/**/*.js\" \"examples/**/*.js\"",
12 | "set-up-hooks": "cp hooks/pre-commit.sh .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit",
13 | "build-docs": "rm -rf ./docs && npx typedoc --out ./docs --tsconfig ./lib/tsconfig.json ./lib/ts/index.ts",
14 | "size": "size-limit"
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "git+https://github.com/supertokens/supertokens-react-native.git"
19 | },
20 | "keywords": [
21 | "react-native",
22 | "authentication",
23 | "authorisation",
24 | "supertokens",
25 | "ios",
26 | "android"
27 | ],
28 | "author": "rishabhpoddar",
29 | "license": "Apache 2.0",
30 | "bugs": {
31 | "url": "https://github.com/supertokens/supertokens-react-native/issues"
32 | },
33 | "homepage": "https://github.com/supertokens/supertokens-react-native#readme",
34 | "peerDependencies": {
35 | "axios": "*",
36 | "react-native": ">=0.61.5 <1.0.x",
37 | "@react-native-async-storage/async-storage": ">=1.13.0 <=2.2.x"
38 | },
39 | "devDependencies": {
40 | "@react-native-async-storage/async-storage": "^1.13.0",
41 | "@size-limit/preset-small-lib": "^6.0.4",
42 | "@types/base-64": "^1.0.0",
43 | "@types/react-native": "0.62.0",
44 | "axios": "*",
45 | "prettier": "1.18.2",
46 | "size-limit": "^6.0.4",
47 | "typescript": "5.8.3",
48 | "typedoc": "0.28.5"
49 | },
50 | "dependencies": {
51 | "base-64": "^1.0.0",
52 | "supertokens-js-override": "^0.0.4"
53 | },
54 | "size-limit": [
55 | {
56 | "path": "lib/build/index.js",
57 | "limit": "28kb"
58 | }
59 | ]
60 | }
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/backend/config.ts:
--------------------------------------------------------------------------------
1 | import ThirdParty from "supertokens-node/recipe/thirdparty";
2 | import Session from "supertokens-node/recipe/session";
3 | import { TypeInput } from "supertokens-node/types";
4 | import Dashboard from "supertokens-node/recipe/dashboard";
5 |
6 | export const SuperTokensConfig: TypeInput = {
7 | supertokens: {
8 | // this is the location of the SuperTokens core.
9 | connectionURI: "https://try.supertokens.com",
10 | },
11 | appInfo: {
12 | appName: "SuperTokens Demo App",
13 | apiDomain: "http://192.168.29.87:3001",
14 | websiteDomain: "http://localhost:3000", // this value does not matter for the android app
15 | },
16 | // recipeList contains all the modules that you want to
17 | // use from SuperTokens. See the full list here: https://supertokens.com/docs/guides
18 | recipeList: [
19 | ThirdParty.init({
20 | signInAndUpFeature: {
21 | providers: [
22 | // We have provided you with development keys which you can use for testing.
23 | // IMPORTANT: Please replace them with your own OAuth keys for production use.
24 | {
25 | config: {
26 | thirdPartyId: "google",
27 | clients: [
28 | {
29 | clientId: "GOOGLE_WEB_CLIENT_ID",
30 | clientSecret: "GOOGLE_WEB_CLIENT_SECRET",
31 | },
32 | ],
33 | },
34 | },
35 | {
36 | config: {
37 | thirdPartyId: "github",
38 | clients: [
39 | {
40 | clientId: "GITHUB_CLIENT_ID",
41 | clientSecret: "GITHUB_CLIENT_SECRET",
42 | },
43 | ],
44 | },
45 | },
46 | {
47 | config: {
48 | thirdPartyId: "apple",
49 | clients: [
50 | {
51 | clientId: "APPLE_CLIENT_ID",
52 | additionalConfig: {
53 | keyId: "APPLE_KEY_ID",
54 | privateKey: "APPLE_PRIVATE_KEY",
55 | teamId: "APPLE_TEAM_ID",
56 | },
57 | },
58 | ],
59 | },
60 | },
61 | ],
62 | },
63 | }),
64 | Session.init(),
65 | Dashboard.init(),
66 | ],
67 | };
68 |
--------------------------------------------------------------------------------
/TestingApp/test/logger.spec.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | import SuperTokens from "supertokens-react-native";
16 | import { disableLogging } from "supertokens-react-native/lib/build/logger";
17 | import { setupFetchWithCookieJar } from "./utils";
18 | // jest does not call setupFiles properly with the new react-native init, so doing it this way instead
19 | import "./setup";
20 |
21 | process.env.TEST_MODE = "testing";
22 |
23 | describe("Logger test", () => {
24 | const consoleSpy = jest.spyOn(console, "log");
25 |
26 | beforeEach(() => {
27 | disableLogging();
28 | setupFetchWithCookieJar();
29 | });
30 |
31 | afterEach(() => {
32 | jest.clearAllMocks();
33 | });
34 |
35 | it("should log to console when debug logging is enabled", async () => {
36 | SuperTokens.init({
37 | apiDomain: "http://localhost:3000",
38 | enableDebugLogs: true
39 | });
40 |
41 | expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("init: called"));
42 | });
43 |
44 | it("should not log to console when debug logging is disabled", async () => {
45 | SuperTokens.init({
46 | apiDomain: "http://localhost:3000",
47 | enableDebugLogs: false
48 | });
49 |
50 | expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining("init: called"));
51 | });
52 |
53 | it("should not log to console when no argument is passed for enableDebugLogs", async () => {
54 | SuperTokens.init({
55 | apiDomain: "http://localhost:3000"
56 | });
57 |
58 | expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining("init: called"));
59 | });
60 | });
61 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 |
25 | # Automatically convert third-party libraries to use AndroidX
26 | android.enableJetifier=true
27 |
28 | # Version of flipper SDK to use with React Native
29 | FLIPPER_VERSION=0.182.0
30 |
31 | # Use this property to specify which architecture you want to build.
32 | # You can also override it from the CLI using
33 | # ./gradlew -PreactNativeArchitectures=x86_64
34 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
35 |
36 | # Use this property to enable support to the new architecture.
37 | # This will allow you to use TurboModules and the Fabric render in
38 | # your application. You should enable this flag either if you want
39 | # to write custom TurboModules/Fabric components OR use libraries that
40 | # are providing them.
41 | newArchEnabled=false
42 |
43 | # Use this property to enable or disable the Hermes JS engine.
44 | # If set to false, you will be using JSC instead.
45 | hermesEnabled=true
46 |
47 | # Enable GIF support in React Native images (~200 B increase)
48 | expo.gif.enabled=true
49 | # Enable webp support in React Native images (~85 KB increase)
50 | expo.webp.enabled=true
51 | # Enable animated webp support (~3.4 MB increase)
52 | # Disabled by default because iOS doesn't support animated webp
53 | expo.webp.animated=false
54 |
55 | # Enable network inspector
56 | EX_DEV_CLIENT_NETWORK_INSPECTOR=true
57 |
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/lib/permuteDomain.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Copyright (c) 2015, Salesforce.com, Inc.
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions are met:
7 | *
8 | * 1. Redistributions of source code must retain the above copyright notice,
9 | * this list of conditions and the following disclaimer.
10 | *
11 | * 2. Redistributions in binary form must reproduce the above copyright notice,
12 | * this list of conditions and the following disclaimer in the documentation
13 | * and/or other materials provided with the distribution.
14 | *
15 | * 3. Neither the name of Salesforce.com nor the names of its contributors may
16 | * be used to endorse or promote products derived from this software without
17 | * specific prior written permission.
18 | *
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 | * POSSIBILITY OF SUCH DAMAGE.
30 | */
31 | "use strict";
32 | var pubsuffix = require("./pubsuffix-psl");
33 |
34 | // Gives the permutation of all possible domainMatch()es of a given domain. The
35 | // array is in shortest-to-longest order. Handy for indexing.
36 | function permuteDomain(domain) {
37 | var pubSuf = pubsuffix.getPublicSuffix(domain);
38 | if (!pubSuf) {
39 | return null;
40 | }
41 | if (pubSuf == domain) {
42 | return [domain];
43 | }
44 |
45 | var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
46 | var parts = prefix.split(".").reverse();
47 | var cur = pubSuf;
48 | var permutations = [cur];
49 | while (parts.length) {
50 | cur = parts.shift() + "." + cur;
51 | permutations.push(cur);
52 | }
53 | return permutations;
54 | }
55 |
56 | exports.permuteDomain = permuteDomain;
57 |
--------------------------------------------------------------------------------
/TestingApp/ios/TestingApp/AppDelegate.m:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 | #import
5 | #import
6 |
7 | #ifdef FB_SONARKIT_ENABLED
8 | #import
9 | #import
10 | #import
11 | #import
12 | #import
13 | #import
14 |
15 | static void InitializeFlipper(UIApplication *application) {
16 | FlipperClient *client = [FlipperClient sharedClient];
17 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
18 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
19 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
20 | [client addPlugin:[FlipperKitReactPlugin new]];
21 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
22 | [client start];
23 | }
24 | #endif
25 |
26 | @implementation AppDelegate
27 |
28 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
29 | {
30 | #ifdef FB_SONARKIT_ENABLED
31 | InitializeFlipper(application);
32 | #endif
33 |
34 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
35 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
36 | moduleName:@"TestingApp"
37 | initialProperties:nil];
38 |
39 | if (@available(iOS 13.0, *)) {
40 | rootView.backgroundColor = [UIColor systemBackgroundColor];
41 | } else {
42 | rootView.backgroundColor = [UIColor whiteColor];
43 | }
44 |
45 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
46 | UIViewController *rootViewController = [UIViewController new];
47 | rootViewController.view = rootView;
48 | self.window.rootViewController = rootViewController;
49 | [self.window makeKeyAndVisible];
50 | return YES;
51 | }
52 |
53 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
54 | {
55 | #if DEBUG
56 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
57 | #else
58 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
59 | #endif
60 | }
61 |
62 | @end
63 |
--------------------------------------------------------------------------------
/ios/RNSuperTokens.m:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | #import "RNSuperTokens.h"
17 | #import "SuperTokensSession-Swift.h"
18 |
19 | @implementation RNSuperTokens
20 |
21 | - (dispatch_queue_t)methodQueue
22 | {
23 | return dispatch_get_main_queue();
24 | }
25 | RCT_EXPORT_MODULE()
26 |
27 |
28 | //RCT_EXPORT_METHOD(initLib: (NSString *)refreshTokenEndpoint:
29 | // (int)sessionExpiryStatusCode:
30 | // (NSDictionary *)refreshAPICustomHeaders:
31 | // (RCTPromiseResolveBlock)resolve
32 | // rejecter:(RCTPromiseRejectBlock)reject)
33 | //{
34 | // NSError *error = nil;
35 | // [SuperTokens initialiseWithRefreshTokenEndpoint:refreshTokenEndpoint sessionExpiryStatusCode:sessionExpiryStatusCode refreshAPICustomHeaders:refreshAPICustomHeaders error:&error];
36 | //
37 | // if (error) {
38 | // reject(@"init_failed", @"Call to initialising native SDK failed", error);
39 | // } else {
40 | // resolve(nil);
41 | // }
42 | //}
43 | //
44 | //RCT_EXPORT_METHOD(doesSessionExist:
45 | // (RCTPromiseResolveBlock)resolve:
46 | // (RCTPromiseRejectBlock)reject)
47 | //{
48 | // NSNumber *result = [SuperTokens doesSessionExist] ? [NSNumber numberWithBool:YES] : [NSNumber numberWithBool:NO];
49 | // resolve(result);
50 | //}
51 | //
52 | //RCT_EXPORT_METHOD(dataTask:
53 | // (NSURLRequest *)request:
54 | // (RCTPromiseResolveBlock)resolve
55 | // rejecter:(RCTPromiseRejectBlock)reject)
56 | //{
57 | // [SuperTokensURLSession
58 | // dataTaskWithRequest:request
59 | // completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
60 | // if (error) {
61 | // reject(@"network_failed", @"Network request failed", error);
62 | // } else {
63 | //
64 | // }
65 | // }];
66 | //}
67 |
68 | @end
69 |
70 |
--------------------------------------------------------------------------------
/.circleci/setupAndTestWithFreeCore.sh:
--------------------------------------------------------------------------------
1 | coreInfo=`curl -s -X GET \
2 | "https://api.supertokens.io/0/core/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$1" \
3 | -H 'api-version: 0'`
4 | if [[ `echo $coreInfo | jq .tag` == "null" ]]
5 | then
6 | echo "fetching latest X.Y.Z version for core, X.Y version: $1, planType: FREE gave response: $coreInfo"
7 | exit 1
8 | fi
9 | coreTag=$(echo $coreInfo | jq .tag | tr -d '"')
10 | coreVersion=$(echo $coreInfo | jq .version | tr -d '"')
11 |
12 | pluginInterfaceVersionXY=`curl -s -X GET \
13 | "https://api.supertokens.io/0/core/dependency/plugin-interface/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$1" \
14 | -H 'api-version: 0'`
15 | if [[ `echo $pluginInterfaceVersionXY | jq .pluginInterface` == "null" ]]
16 | then
17 | echo "fetching latest X.Y version for plugin-interface, given core X.Y version: $1, planType: FREE gave response: $pluginInterfaceVersionXY"
18 | exit 1
19 | fi
20 | pluginInterfaceVersionXY=$(echo $pluginInterfaceVersionXY | jq .pluginInterface | tr -d '"')
21 |
22 | pluginInterfaceInfo=`curl -s -X GET \
23 | "https://api.supertokens.io/0/plugin-interface/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$pluginInterfaceVersionXY" \
24 | -H 'api-version: 0'`
25 | if [[ `echo $pluginInterfaceInfo | jq .tag` == "null" ]]
26 | then
27 | echo "fetching latest X.Y.Z version for plugin-interface, X.Y version: $pluginInterfaceVersionXY, planType: FREE gave response: $pluginInterfaceInfo"
28 | exit 1
29 | fi
30 | pluginInterfaceTag=$(echo $pluginInterfaceInfo | jq .tag | tr -d '"')
31 | pluginInterfaceVersion=$(echo $pluginInterfaceInfo | jq .version | tr -d '"')
32 |
33 | echo "Testing with node driver: $2, FREE core: $coreVersion, plugin-interface: $pluginInterfaceVersion"
34 |
35 | cd ../../
36 | git clone git@github.com:supertokens/supertokens-root.git
37 | cd supertokens-root
38 | echo -e "core,$1\nplugin-interface,$pluginInterfaceVersionXY" > modules.txt
39 | ./loadModules --ssh
40 | cd supertokens-core
41 | git checkout $coreTag
42 | cd ../supertokens-plugin-interface
43 | git checkout $pluginInterfaceTag
44 | cd ../
45 | echo $SUPERTOKENS_API_KEY > apiPassword
46 | ./utils/setupTestEnvLocal
47 | cd ../project/TestingApp/test/server/
48 | npm i -d
49 | npm i git+https://github.com:supertokens/supertokens-node.git#$2
50 | cd ../../
51 | npm i -d
52 | cp -r ./test/tough-cookie ./node_modules/
53 | npm i git+https://github.com:supertokens/supertokens-react-native.git#dev-v$3
54 | SUPERTOKENS_CORE_TAG=$coreTag INSTALL_PATH=../../supertokens-root npm run test-ci
55 | if [[ $? -ne 0 ]]
56 | then
57 | echo "test failed... exiting!"
58 | exit 1
59 | fi
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/main/java/com/supertokens/supertokensexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.supertokens.supertokensexample;
2 |
3 | import android.os.Build;
4 | import android.os.Bundle;
5 |
6 | import com.facebook.react.ReactActivity;
7 | import com.facebook.react.ReactActivityDelegate;
8 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
9 | import com.facebook.react.defaults.DefaultReactActivityDelegate;
10 |
11 | import expo.modules.ReactActivityDelegateWrapper;
12 |
13 | public class MainActivity extends ReactActivity {
14 | @Override
15 | protected void onCreate(Bundle savedInstanceState) {
16 | // Set the theme to AppTheme BEFORE onCreate to support
17 | // coloring the background, status bar, and navigation bar.
18 | // This is required for expo-splash-screen.
19 | setTheme(R.style.AppTheme);
20 | super.onCreate(null);
21 | }
22 |
23 | /**
24 | * Returns the name of the main component registered from JavaScript.
25 | * This is used to schedule rendering of the component.
26 | */
27 | @Override
28 | protected String getMainComponentName() {
29 | return "main";
30 | }
31 |
32 | /**
33 | * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
34 | * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
35 | * (aka React 18) with two boolean flags.
36 | */
37 | @Override
38 | protected ReactActivityDelegate createReactActivityDelegate() {
39 | return new ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, new DefaultReactActivityDelegate(
40 | this,
41 | getMainComponentName(),
42 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
43 | DefaultNewArchitectureEntryPoint.getFabricEnabled()));
44 | }
45 |
46 | /**
47 | * Align the back button behavior with Android S
48 | * where moving root activities to background instead of finishing activities.
49 | * @see onBackPressed
50 | */
51 | @Override
52 | public void invokeDefaultOnBackPressed() {
53 | if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
54 | if (!moveTaskToBack(false)) {
55 | // For non-root activities, use the default implementation to finish them.
56 | super.invokeDefaultOnBackPressed();
57 | }
58 | return;
59 | }
60 |
61 | // Use the default back button implementation on Android S
62 | // because it's doing more than {@link Activity#moveTaskToBack} in fact.
63 | super.invokeDefaultOnBackPressed();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/lib/pathMatch.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Copyright (c) 2015, Salesforce.com, Inc.
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions are met:
7 | *
8 | * 1. Redistributions of source code must retain the above copyright notice,
9 | * this list of conditions and the following disclaimer.
10 | *
11 | * 2. Redistributions in binary form must reproduce the above copyright notice,
12 | * this list of conditions and the following disclaimer in the documentation
13 | * and/or other materials provided with the distribution.
14 | *
15 | * 3. Neither the name of Salesforce.com nor the names of its contributors may
16 | * be used to endorse or promote products derived from this software without
17 | * specific prior written permission.
18 | *
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 | * POSSIBILITY OF SUCH DAMAGE.
30 | */
31 | "use strict";
32 | /*
33 | * "A request-path path-matches a given cookie-path if at least one of the
34 | * following conditions holds:"
35 | */
36 | function pathMatch(reqPath, cookiePath) {
37 | // "o The cookie-path and the request-path are identical."
38 | if (cookiePath === reqPath) {
39 | return true;
40 | }
41 |
42 | var idx = reqPath.indexOf(cookiePath);
43 | if (idx === 0) {
44 | // "o The cookie-path is a prefix of the request-path, and the last
45 | // character of the cookie-path is %x2F ("/")."
46 | if (cookiePath.substr(-1) === "/") {
47 | return true;
48 | }
49 |
50 | // " o The cookie-path is a prefix of the request-path, and the first
51 | // character of the request-path that is not included in the cookie- path
52 | // is a %x2F ("/") character."
53 | if (reqPath.substr(cookiePath.length, 1) === "/") {
54 | return true;
55 | }
56 | }
57 |
58 | return false;
59 | }
60 |
61 | exports.pathMatch = pathMatch;
62 |
--------------------------------------------------------------------------------
/lib/build/locking.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | /*
16 | WARNING: Do not acquire a lock and then re acquire the same lock without
17 | releasing that lock first!!
18 | */
19 | class Locking {
20 | constructor() {
21 | this.locked = new Map();
22 | this.addToLocked = (key, toAdd) => {
23 | let callbacks = this.locked.get(key);
24 | if (callbacks === undefined) {
25 | if (toAdd === undefined) {
26 | this.locked.set(key, []);
27 | } else {
28 | this.locked.set(key, [toAdd]);
29 | }
30 | } else {
31 | if (toAdd !== undefined) {
32 | callbacks.unshift(toAdd);
33 | this.locked.set(key, callbacks);
34 | }
35 | }
36 | };
37 | this.isLocked = key => {
38 | return this.locked.has(key);
39 | };
40 | this.lock = key => {
41 | return new Promise((resolve, reject) => {
42 | if (this.isLocked(key)) {
43 | this.addToLocked(key, resolve);
44 | } else {
45 | this.addToLocked(key);
46 | resolve();
47 | }
48 | });
49 | };
50 | this.unlock = key => {
51 | let callbacks = this.locked.get(key);
52 | if (callbacks === undefined || callbacks.length === 0) {
53 | this.locked.delete(key);
54 | return;
55 | }
56 | let toCall = callbacks.pop();
57 | this.locked.set(key, callbacks);
58 | if (toCall !== undefined) {
59 | setImmediate(toCall);
60 | }
61 | };
62 | }
63 | static getInstance() {
64 | if (Locking.instance === undefined) {
65 | Locking.instance = new Locking();
66 | }
67 | return Locking.instance;
68 | }
69 | }
70 | export default function getLock() {
71 | return Locking.getInstance();
72 | }
73 |
--------------------------------------------------------------------------------
/lib/ts/locking.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | /*
17 | WARNING: Do not acquire a lock and then re acquire the same lock without
18 | releasing that lock first!!
19 | */
20 | class Locking {
21 | static instance: undefined | Locking;
22 | private locked: Map void)[]> = new Map void)[]>();
23 |
24 | static getInstance() {
25 | if (Locking.instance === undefined) {
26 | Locking.instance = new Locking();
27 | }
28 | return Locking.instance;
29 | }
30 |
31 | private addToLocked = (key: string, toAdd?: () => void) => {
32 | let callbacks = this.locked.get(key);
33 | if (callbacks === undefined) {
34 | if (toAdd === undefined) {
35 | this.locked.set(key, []);
36 | } else {
37 | this.locked.set(key, [toAdd]);
38 | }
39 | } else {
40 | if (toAdd !== undefined) {
41 | callbacks.unshift(toAdd);
42 | this.locked.set(key, callbacks);
43 | }
44 | }
45 | };
46 |
47 | isLocked = (key: string): boolean => {
48 | return this.locked.has(key);
49 | };
50 |
51 | lock = (key: string): Promise => {
52 | return new Promise((resolve, reject) => {
53 | if (this.isLocked(key)) {
54 | this.addToLocked(key, resolve);
55 | } else {
56 | this.addToLocked(key);
57 | resolve();
58 | }
59 | });
60 | };
61 |
62 | unlock = (key: string) => {
63 | let callbacks = this.locked.get(key);
64 | if (callbacks === undefined || callbacks.length === 0) {
65 | this.locked.delete(key);
66 | return;
67 | }
68 | let toCall = callbacks.pop();
69 | this.locked.set(key, callbacks);
70 | if (toCall !== undefined) {
71 | setImmediate(toCall);
72 | }
73 | };
74 | }
75 |
76 | export default function getLock(): Locking {
77 | return Locking.getInstance();
78 | }
79 |
--------------------------------------------------------------------------------
/lib/ts/processState.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | export enum PROCESS_STATE {
17 | //CALLING_INTERCEPTION_REQUEST : Process state for the request interceptor.
18 | //CALLING_INTERCEPTION_RESOPONSE : Process state for the response interceptor.
19 | CALLING_INTERCEPTION_REQUEST,
20 | CALLING_INTERCEPTION_RESPONSE
21 | }
22 |
23 | declare let process: any;
24 |
25 | export class ProcessState {
26 | history: PROCESS_STATE[] = [];
27 | private static instance: ProcessState | undefined;
28 |
29 | static getInstance() {
30 | if (ProcessState.instance == undefined) {
31 | ProcessState.instance = new ProcessState();
32 | }
33 | return ProcessState.instance;
34 | }
35 |
36 | addState = (state: PROCESS_STATE) => {
37 | if (process !== undefined && process.env !== undefined && process.env.TEST_MODE === "testing") {
38 | this.history.push(state);
39 | }
40 | };
41 |
42 | private getEventByLastEventByName = (state: PROCESS_STATE) => {
43 | for (let i = this.history.length - 1; i >= 0; i--) {
44 | if (this.history[i] == state) {
45 | return this.history[i];
46 | }
47 | }
48 | return undefined;
49 | };
50 |
51 | reset = () => {
52 | this.history = [];
53 | };
54 |
55 | waitForEvent = async (state: PROCESS_STATE, timeInMS = 7000) => {
56 | let startTime = Date.now();
57 | return new Promise(resolve => {
58 | let actualThis = this;
59 | function tryAndGet() {
60 | let result = actualThis.getEventByLastEventByName(state);
61 | if (result === undefined) {
62 | if (Date.now() - startTime > timeInMS) {
63 | resolve(undefined);
64 | } else {
65 | setTimeout(tryAndGet, 1000);
66 | }
67 | } else {
68 | resolve(result);
69 | }
70 | }
71 | tryAndGet();
72 | });
73 | };
74 | }
75 |
--------------------------------------------------------------------------------
/lib/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "jsRules": {
3 | "class-name": true,
4 | "comment-format": [
5 | true,
6 | "check-space"
7 | ],
8 | "indent": [
9 | true,
10 | "spaces"
11 | ],
12 | "no-duplicate-variable": true,
13 | "no-eval": true,
14 | "no-trailing-whitespace": true,
15 | "no-unsafe-finally": true,
16 | "one-line": [
17 | true,
18 | "check-open-brace",
19 | "check-whitespace"
20 | ],
21 | "quotemark": [
22 | true,
23 | "double"
24 | ],
25 | "semicolon": [
26 | true,
27 | "always"
28 | ],
29 | "triple-equals": [
30 | true,
31 | "allow-null-check"
32 | ],
33 | "variable-name": [
34 | true,
35 | "ban-keywords"
36 | ],
37 | "whitespace": [
38 | true,
39 | "check-branch",
40 | "check-decl",
41 | "check-operator",
42 | "check-separator",
43 | "check-type"
44 | ]
45 | },
46 | "rules": {
47 | "class-name": true,
48 | "comment-format": [
49 | true,
50 | "check-space"
51 | ],
52 | "indent": [
53 | true,
54 | "spaces"
55 | ],
56 | "no-eval": true,
57 | "no-internal-module": true,
58 | "no-trailing-whitespace": true,
59 | "no-unsafe-finally": true,
60 | "no-var-keyword": true,
61 | "one-line": [
62 | true,
63 | "check-open-brace",
64 | "check-whitespace"
65 | ],
66 | "quotemark": [
67 | true,
68 | "double"
69 | ],
70 | "semicolon": [
71 | true,
72 | "always"
73 | ],
74 | "triple-equals": [
75 | true,
76 | "allow-null-check"
77 | ],
78 | "typedef-whitespace": [
79 | true,
80 | {
81 | "call-signature": "nospace",
82 | "index-signature": "nospace",
83 | "parameter": "nospace",
84 | "property-declaration": "nospace",
85 | "variable-declaration": "nospace"
86 | }
87 | ],
88 | "variable-name": [
89 | true,
90 | "ban-keywords"
91 | ],
92 | "whitespace": [
93 | true,
94 | "check-branch",
95 | "check-decl",
96 | "check-operator",
97 | "check-separator",
98 | "check-type"
99 | ]
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/ios/withthirdparty/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CADisableMinimumFrameDurationOnPhone
6 |
7 | CFBundleDevelopmentRegion
8 | $(DEVELOPMENT_LANGUAGE)
9 | CFBundleDisplayName
10 | with-thirdparty
11 | CFBundleExecutable
12 | $(EXECUTABLE_NAME)
13 | CFBundleIdentifier
14 | $(PRODUCT_BUNDLE_IDENTIFIER)
15 | CFBundleInfoDictionaryVersion
16 | 6.0
17 | CFBundleName
18 | $(PRODUCT_NAME)
19 | CFBundlePackageType
20 | $(PRODUCT_BUNDLE_PACKAGE_TYPE)
21 | CFBundleShortVersionString
22 | 1.0.0
23 | CFBundleSignature
24 | ????
25 | CFBundleURLTypes
26 |
27 |
28 | CFBundleURLSchemes
29 |
30 | com.supertokens.supertokensexample
31 | GOOGLE_IOS_URL_SCHEME
32 | com.supertokens.with-thirdparty
33 |
34 |
35 |
36 | CFBundleVersion
37 | 1
38 | GIDClientID
39 | GOOGLE_IOS_CLIENT_ID
40 | GIDServerClientID
41 | GOOGLE_WEB_CLIENT_ID
42 | LSRequiresIPhoneOS
43 |
44 | NSAppTransportSecurity
45 |
46 | NSAllowsArbitraryLoads
47 |
48 | NSExceptionDomains
49 |
50 | localhost
51 |
52 | NSExceptionAllowsInsecureHTTPLoads
53 |
54 |
55 |
56 |
57 | UILaunchStoryboardName
58 | SplashScreen
59 | UIRequiredDeviceCapabilities
60 |
61 | armv7
62 |
63 | UIRequiresFullScreen
64 |
65 | UIStatusBarStyle
66 | UIStatusBarStyleDefault
67 | UISupportedInterfaceOrientations
68 |
69 | UIInterfaceOrientationPortrait
70 | UIInterfaceOrientationPortraitUpsideDown
71 |
72 | UISupportedInterfaceOrientations~ipad
73 |
74 | UIInterfaceOrientationPortrait
75 | UIInterfaceOrientationPortraitUpsideDown
76 | UIInterfaceOrientationLandscapeLeft
77 | UIInterfaceOrientationLandscapeRight
78 |
79 | UIUserInterfaceStyle
80 | Light
81 | UIViewControllerBasedStatusBarAppearance
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "_args": [
3 | [
4 | "tough-cookie@3.0.1",
5 | "/Users/rishabhpoddar/Desktop/supertokens/supertokens-react-native/Example"
6 | ]
7 | ],
8 | "_development": true,
9 | "_from": "tough-cookie@3.0.1",
10 | "_id": "tough-cookie@3.0.1",
11 | "_inBundle": false,
12 | "_integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==",
13 | "_location": "/tough-cookie",
14 | "_phantomChildren": {},
15 | "_requested": {
16 | "type": "version",
17 | "registry": true,
18 | "raw": "tough-cookie@3.0.1",
19 | "name": "tough-cookie",
20 | "escapedName": "tough-cookie",
21 | "rawSpec": "3.0.1",
22 | "saveSpec": null,
23 | "fetchSpec": "3.0.1"
24 | },
25 | "_requiredBy": [
26 | "/jsdom"
27 | ],
28 | "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz",
29 | "_spec": "3.0.1",
30 | "_where": "/Users/rishabhpoddar/Desktop/supertokens/supertokens-react-native/Example",
31 | "author": {
32 | "name": "Jeremy Stashewsky",
33 | "email": "jstash@gmail.com"
34 | },
35 | "bugs": {
36 | "url": "https://github.com/salesforce/tough-cookie/issues"
37 | },
38 | "contributors": [
39 | {
40 | "name": "Alexander Savin"
41 | },
42 | {
43 | "name": "Ian Livingstone"
44 | },
45 | {
46 | "name": "Ivan Nikulin"
47 | },
48 | {
49 | "name": "Lalit Kapoor"
50 | },
51 | {
52 | "name": "Sam Thompson"
53 | },
54 | {
55 | "name": "Sebastian Mayr"
56 | }
57 | ],
58 | "dependencies": {
59 | "ip-regex": "^2.1.0",
60 | "psl": "^1.1.28",
61 | "punycode": "^2.1.1"
62 | },
63 | "description": "RFC6265 Cookies and Cookie Jar for node.js",
64 | "devDependencies": {
65 | "async": "^1.4.2",
66 | "genversion": "^2.1.0",
67 | "nyc": "^11.6.0",
68 | "string.prototype.repeat": "^0.2.0",
69 | "vows": "^0.8.2"
70 | },
71 | "engines": {
72 | "node": ">=6"
73 | },
74 | "files": [
75 | "lib"
76 | ],
77 | "homepage": "https://github.com/salesforce/tough-cookie",
78 | "keywords": [
79 | "HTTP",
80 | "cookie",
81 | "cookies",
82 | "set-cookie",
83 | "cookiejar",
84 | "jar",
85 | "RFC6265",
86 | "RFC2965"
87 | ],
88 | "license": "BSD-3-Clause",
89 | "main": "./lib/cookie",
90 | "name": "tough-cookie",
91 | "repository": {
92 | "type": "git",
93 | "url": "git://github.com/salesforce/tough-cookie.git"
94 | },
95 | "scripts": {
96 | "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js",
97 | "test": "vows test/*_test.js",
98 | "version": "genversion lib/version.js && git add lib/version.js"
99 | },
100 | "version": "3.0.1"
101 | }
102 |
--------------------------------------------------------------------------------
/.circleci/config_continue.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 | orbs:
3 | continuation: circleci/continuation@0.1.2
4 | slack: circleci/slack@3.4.2
5 | jq: circleci/jq@2.2.0
6 | jobs:
7 | test-dev-tag-as-not-passed:
8 | docker:
9 | - image: rishabhpoddar/supertokens_website_sdk_testing_node_16
10 | steps:
11 | - run: git config --global url."https://github.com/".insteadOf ssh://git@github.com/ # This makes npm use http instead of ssh (required for node 16)
12 | - checkout
13 | - run: (cd .circleci/ && ./markDevTagAsTestNotPassed.sh)
14 | test-unit:
15 | docker:
16 | - image: rishabhpoddar/supertokens_website_sdk_testing_node_16
17 | parameters:
18 | fdi-version:
19 | type: string
20 | parallelism: 4
21 | steps:
22 | - run: mkdir -p ~/reports/
23 | - run: git config --global url."https://github.com/".insteadOf ssh://git@github.com/ # This makes npm use http instead of ssh (required for node 16)
24 | - checkout
25 | - run: echo "127.0.0.1 localhost.org" >> /etc/hosts
26 | - run: npm i -d
27 | - run:
28 | command: for i in $(seq 1 5); do (cd .circleci/ && ./doTests.sh << parameters.fdi-version >>) && s=0 && break || s=$? && sleep 10; done; (exit $s) # https://support.circleci.com/hc/en-us/articles/5728720104347-How-To-Retry-an-Intermittently-Failing-Step
29 | environment:
30 | JEST_JUNIT_OUTPUT_DIR: ~/reports/
31 | - run: npm run size
32 | - store_test_results:
33 | path: ~/reports/
34 | when: always
35 | test-success:
36 | docker:
37 | - image: rishabhpoddar/supertokens_website_sdk_testing_node_16
38 | steps:
39 | - run: git config --global url."https://github.com/".insteadOf ssh://git@github.com/ # This makes npm use http instead of ssh (required for node 16)
40 | - checkout
41 | - run: (cd .circleci/ && ./markAsSuccess.sh)
42 | - slack/status
43 |
44 | workflows:
45 | version: 2
46 | tagged-build:
47 | jobs:
48 | - test-dev-tag-as-not-passed:
49 | filters:
50 | tags:
51 | only: /dev-v[0-9]+(\.[0-9]+)*/
52 | branches:
53 | only: /test-cicd\/.*/
54 |
55 | - test-unit:
56 | requires:
57 | - test-dev-tag-as-not-passed
58 | context:
59 | - slack-notification
60 | filters:
61 | tags:
62 | only: /dev-v[0-9]+(\.[0-9]+)*/
63 | branches:
64 | only: /test-cicd\/.*/
65 | matrix:
66 | parameters:
67 | fdi-version: placeholder
68 | - test-success:
69 | requires:
70 | - test-unit
71 | context:
72 | - slack-notification
73 | filters:
74 | tags:
75 | only: /dev-v[0-9]+(\.[0-9]+)*/
76 | branches:
77 | ignore: /.*/
--------------------------------------------------------------------------------
/TestingApp/android/app/src/main/java/com/testingapp/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.testingapp;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.soloader.SoLoader;
11 | import java.lang.reflect.InvocationTargetException;
12 | import java.util.List;
13 |
14 | public class MainApplication extends Application implements ReactApplication {
15 |
16 | private final ReactNativeHost mReactNativeHost =
17 | new ReactNativeHost(this) {
18 | @Override
19 | public boolean getUseDeveloperSupport() {
20 | return BuildConfig.DEBUG;
21 | }
22 |
23 | @Override
24 | protected List getPackages() {
25 | @SuppressWarnings("UnnecessaryLocalVariable")
26 | List packages = new PackageList(this).getPackages();
27 | // Packages that cannot be autolinked yet can be added manually here, for example:
28 | // packages.add(new MyReactNativePackage());
29 | return packages;
30 | }
31 |
32 | @Override
33 | protected String getJSMainModuleName() {
34 | return "index";
35 | }
36 | };
37 |
38 | @Override
39 | public ReactNativeHost getReactNativeHost() {
40 | return mReactNativeHost;
41 | }
42 |
43 | @Override
44 | public void onCreate() {
45 | super.onCreate();
46 | SoLoader.init(this, /* native exopackage */ false);
47 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
48 | }
49 |
50 | /**
51 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
52 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
53 | *
54 | * @param context
55 | * @param reactInstanceManager
56 | */
57 | private static void initializeFlipper(
58 | Context context, ReactInstanceManager reactInstanceManager) {
59 | if (BuildConfig.DEBUG) {
60 | try {
61 | /*
62 | We use reflection here to pick up the class that initializes Flipper,
63 | since Flipper library is not available in release mode
64 | */
65 | Class> aClass = Class.forName("com.testingapp.ReactNativeFlipper");
66 | aClass
67 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
68 | .invoke(null, context, reactInstanceManager);
69 | } catch (ClassNotFoundException e) {
70 | e.printStackTrace();
71 | } catch (NoSuchMethodException e) {
72 | e.printStackTrace();
73 | } catch (IllegalAccessException e) {
74 | e.printStackTrace();
75 | } catch (InvocationTargetException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/.circleci/doTests.sh:
--------------------------------------------------------------------------------
1 | echo "Starting tests for FDI $1";
2 |
3 | if [ -z "$SUPERTOKENS_API_KEY" ]; then
4 | echo "SUPERTOKENS_API_KEY not set"
5 | exit 1
6 | fi
7 | frontendDriverVersion=$1
8 |
9 | # get sdk version
10 | version=`cat ../package.json | grep -e '"version":'`
11 | while IFS='"' read -ra ADDR; do
12 | counter=0
13 | for i in "${ADDR[@]}"; do
14 | if [ $counter == 3 ]
15 | then
16 | version=$i
17 | fi
18 | counter=$(($counter+1))
19 | done
20 | done <<< "$version"
21 |
22 | driverVersionXY=`curl -s -X GET \
23 | "https://api.supertokens.io/0/frontend-driver-interface/dependency/driver/latest?password=$SUPERTOKENS_API_KEY&mode=DEV&version=$frontendDriverVersion&driverName=node" \
24 | -H 'api-version: 0'`
25 | if [[ `echo $driverVersionXY | jq .driver` == "null" ]]
26 | then
27 | echo "fetching latest X.Y version for driver given frontend-driver-interface X.Y version: $frontendDriverVersion gave response: $driverVersionXY. Please make sure all relevant drivers have been pushed."
28 | exit 1
29 | fi
30 | driverVersionXY=$(echo $driverVersionXY | jq .driver | tr -d '"')
31 |
32 | driverInfo=`curl -s -X GET \
33 | "https://api.supertokens.io/0/driver/latest?password=$SUPERTOKENS_API_KEY&mode=DEV&version=$driverVersionXY&name=node" \
34 | -H 'api-version: 0'`
35 | if [[ `echo $driverInfo | jq .tag` == "null" ]]
36 | then
37 | echo "fetching latest X.Y.Z version for driver, X.Y version: $driverVersionXY gave response: $driverInfo"
38 | exit 1
39 | fi
40 | driverTag=$(echo $driverInfo | jq .tag | tr -d '"')
41 | driverVersion=$(echo $driverInfo | jq .version | tr -d '"')
42 |
43 | git clone git@github.com:supertokens/supertokens-node.git
44 | cd supertokens-node
45 | git checkout $driverTag
46 | coreDriverJson=`cat ./coreDriverInterfaceSupported.json`
47 | coreDriverLength=`echo $coreDriverJson | jq ".versions | length"`
48 | coreDriverArray=`echo $coreDriverJson | jq ".versions"`
49 | coreDriverVersion=`echo $coreDriverArray | jq ". | last"`
50 | coreDriverVersion=`echo $coreDriverVersion | tr -d '"'`
51 | cd ../
52 | rm -rf supertokens-node
53 |
54 | coreFree=`curl -s -X GET \
55 | "https://api.supertokens.io/0/core-driver-interface/dependency/core/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$coreDriverVersion" \
56 | -H 'api-version: 0'`
57 | if [[ `echo $coreFree | jq .core` == "null" ]]
58 | then
59 | echo "fetching latest X.Y version for core given core-driver-interface X.Y version: $coreDriverVersion, planType: FREE gave response: $coreFree. Please make sure all relevant cores have been pushed."
60 | exit 1
61 | fi
62 | coreFree=$(echo $coreFree | jq .core | tr -d '"')
63 |
64 | ./setupAndTestWithFreeCore.sh $coreFree $driverTag $version
65 | if [[ $? -ne 0 ]]
66 | then
67 | echo "test failed... exiting!"
68 | exit 1
69 | fi
70 | rm -rf ../../supertokens-root
71 | rm -rf ../TestingApp/test/server/node_modules/supertokens-node
72 | git checkout HEAD -- ../TestingApp/test/server/package.json
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/app/src/main/java/com/supertokens/supertokensexample/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.supertokens.supertokensexample;
2 |
3 | import android.app.Application;
4 | import android.content.res.Configuration;
5 | import androidx.annotation.NonNull;
6 |
7 | import com.facebook.react.PackageList;
8 | import com.facebook.react.ReactApplication;
9 | import com.facebook.react.ReactNativeHost;
10 | import com.facebook.react.ReactPackage;
11 | import com.facebook.react.config.ReactFeatureFlags;
12 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
13 | import com.facebook.react.defaults.DefaultReactNativeHost;
14 | import com.facebook.soloader.SoLoader;
15 |
16 | import expo.modules.ApplicationLifecycleDispatcher;
17 | import expo.modules.ReactNativeHostWrapper;
18 |
19 | import java.util.List;
20 |
21 | public class MainApplication extends Application implements ReactApplication {
22 |
23 | private final ReactNativeHost mReactNativeHost =
24 | new ReactNativeHostWrapper(this, new DefaultReactNativeHost(this) {
25 | @Override
26 | public boolean getUseDeveloperSupport() {
27 | return BuildConfig.DEBUG;
28 | }
29 |
30 | @Override
31 | protected List getPackages() {
32 | @SuppressWarnings("UnnecessaryLocalVariable")
33 | List packages = new PackageList(this).getPackages();
34 | // Packages that cannot be autolinked yet can be added manually here, for example:
35 | // packages.add(new MyReactNativePackage());
36 | return packages;
37 | }
38 |
39 | @Override
40 | protected String getJSMainModuleName() {
41 | return ".expo/.virtual-metro-entry";
42 | }
43 |
44 | @Override
45 | protected boolean isNewArchEnabled() {
46 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
47 | }
48 |
49 | @Override
50 | protected Boolean isHermesEnabled() {
51 | return BuildConfig.IS_HERMES_ENABLED;
52 | }
53 | });
54 |
55 | @Override
56 | public ReactNativeHost getReactNativeHost() {
57 | return mReactNativeHost;
58 | }
59 |
60 | @Override
61 | public void onCreate() {
62 | super.onCreate();
63 | SoLoader.init(this, /* native exopackage */ false);
64 | if (!BuildConfig.REACT_NATIVE_UNSTABLE_USE_RUNTIME_SCHEDULER_ALWAYS) {
65 | ReactFeatureFlags.unstable_useRuntimeSchedulerAlways = false;
66 | }
67 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
68 | // If you opted-in for the New Architecture, we load the native entry point for this app.
69 | DefaultNewArchitectureEntryPoint.load();
70 | }
71 | ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
72 | ApplicationLifecycleDispatcher.onApplicationCreate(this);
73 | }
74 |
75 | @Override
76 | public void onConfigurationChanged(@NonNull Configuration newConfig) {
77 | super.onConfigurationChanged(newConfig);
78 | ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/lib/build/normalisedURLDomain.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | import { logDebugMessage } from "./logger";
16 | import { isAnIpAddress } from "./utils";
17 | export default class NormalisedURLDomain {
18 | constructor(url) {
19 | this.getAsStringDangerous = () => {
20 | return this.value;
21 | };
22 | this.value = normaliseURLDomainOrThrowError(url);
23 | }
24 | }
25 | function normaliseURLDomainOrThrowError(input, ignoreProtocol = false) {
26 | input = input.trim();
27 | let error = null;
28 | try {
29 | if (!input.startsWith("http://") && !input.startsWith("https://")) {
30 | throw new Error("converting to proper URL");
31 | }
32 | const urlObj = new URL(input);
33 | if (ignoreProtocol) {
34 | if (urlObj.hostname.startsWith("localhost") || isAnIpAddress(urlObj.hostname)) {
35 | input = "http://" + urlObj.host;
36 | } else {
37 | input = "https://" + urlObj.host;
38 | }
39 | } else {
40 | input = urlObj.protocol + "//" + urlObj.host;
41 | }
42 | return input;
43 | // eslint-disable-next-line no-empty
44 | } catch (err) {
45 | error = err;
46 | logDebugMessage(err);
47 | }
48 | if (input.startsWith("/")) {
49 | throw new Error("Please provide a valid domain name");
50 | }
51 | // not a valid URL
52 | if (input.indexOf(".") === 0) {
53 | input = input.substr(1);
54 | }
55 | // If the input contains a . it means they have given a domain name.
56 | // So we try assuming that they have given a domain name
57 | if (
58 | (input.indexOf(".") !== -1 || input.startsWith("localhost")) &&
59 | !input.startsWith("http://") &&
60 | !input.startsWith("https://")
61 | ) {
62 | input = "https://" + input;
63 | // at this point, it should be a valid URL. So we test that before doing a recursive call
64 | try {
65 | new URL(input);
66 | return normaliseURLDomainOrThrowError(input, true);
67 | // eslint-disable-next-line no-empty
68 | } catch (err) {
69 | throw err;
70 | }
71 | }
72 | if (error === null) {
73 | error = new Error("Please provide a valid domain name");
74 | }
75 | throw error;
76 | }
77 |
--------------------------------------------------------------------------------
/TestingApp/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if %ERRORLEVEL% equ 0 goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if %ERRORLEVEL% equ 0 goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | set EXIT_CODE=%ERRORLEVEL%
84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
86 | exit /b %EXIT_CODE%
87 |
88 | :mainEnd
89 | if "%OS%"=="Windows_NT" endlocal
90 |
91 | :omega
92 |
--------------------------------------------------------------------------------
/addDevTag:
--------------------------------------------------------------------------------
1 | # check if we need to merge master into this branch------------
2 | if [[ $(git log master ^HEAD) ]]; then
3 | echo "You need to merge master into this branch. Exiting"
4 | exit 1
5 | fi
6 |
7 | # get version------------
8 | version=`cat package.json | grep -e '"version":'`
9 | while IFS='"' read -ra ADDR; do
10 | counter=0
11 | for i in "${ADDR[@]}"; do
12 | if [ $counter == 3 ]
13 | then
14 | version=$i
15 | fi
16 | counter=$(($counter+1))
17 | done
18 | done <<< "$version"
19 |
20 | versionLock=`head -n 3 package-lock.json | grep -e '"version":'`
21 |
22 | while IFS='"' read -ra ADDR; do
23 | counter=0
24 | for i in "${ADDR[@]}"; do
25 | if [ $counter == 3 ]
26 | then
27 | versionLock=$i
28 | fi
29 | counter=$(($counter+1))
30 | done
31 | done <<< "$versionLock"
32 |
33 | # check if package and package-lock versions are similar.-----------
34 | if ! [[ $version == $versionLock ]]
35 | then
36 | RED='\033[0;31m'
37 | NC='\033[0m' # No Color
38 | printf "${RED}Difference between package-lock and package version. Please run npm install. Stopping process${NC}\n"
39 | exit 1
40 | fi
41 |
42 | # get current branch name
43 | branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
44 | branch_name="(unnamed branch)" # detached HEAD
45 | branch_name=${branch_name##refs/heads/}
46 |
47 | # check if branch is correct based on the version-----------
48 | if ! [[ $version == $branch_name* ]]
49 | then
50 | RED='\033[0;31m'
51 | NC='\033[0m' # No Color
52 | printf "${RED}Adding tag to wrong branch. Stopping process${NC}\n"
53 | exit 1
54 | fi
55 |
56 | #Sync tags with remote
57 | git fetch --prune --prune-tags
58 |
59 | # GET Current Commit Hash -------
60 | if [ $# -eq 0 ]
61 | then
62 | commit_hash=`git log --pretty=format:'%H' -n 1`
63 | else
64 | commit_hash=$1
65 | fi
66 |
67 | # check if current commit already has a tag or not------------
68 | if [[ `git tag -l --points-at $commit_hash` == "" ]]
69 | then
70 | continue=1
71 | else
72 | RED='\033[0;31m'
73 | NC='\033[0m'
74 | printf "${RED}This commit already has a tag. Please remove that and re-run this script${NC}\n"
75 | echo "git tag --delete "
76 | echo "git push --delete origin "
77 | exit 1
78 | fi
79 |
80 | # check if release version of this tag exists------------
81 |
82 | if git rev-parse v$version >/dev/null 2>&1
83 | then
84 | RED='\033[0;31m'
85 | NC='\033[0m'
86 | printf "${RED}The released version of this tag already exists${NC}\n"
87 | exit 1
88 | fi
89 |
90 | # add an empty commit if the user has not given a commit hash so that we are sure it's built------------
91 | if [ $# -eq 0 ]
92 | then
93 | npm run build-pretty
94 | npm run build-docs
95 | git add --all
96 | git commit --allow-empty -m"adding dev-v$version tag to this commit to ensure building"
97 | git push
98 | commit_hash=`git log --pretty=format:'%H' -n 1`
99 | fi
100 |
101 |
102 | git tag dev-v$version $commit_hash
103 | git push --tags
--------------------------------------------------------------------------------
/lib/ts/normalisedURLDomain.ts:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 |
16 | import { logDebugMessage } from "./logger";
17 | import { isAnIpAddress } from "./utils";
18 |
19 | export default class NormalisedURLDomain {
20 | private value: string;
21 |
22 | constructor(url: string) {
23 | this.value = normaliseURLDomainOrThrowError(url);
24 | }
25 |
26 | getAsStringDangerous = (): string => {
27 | return this.value;
28 | };
29 | }
30 |
31 | function normaliseURLDomainOrThrowError(input: string, ignoreProtocol = false): string {
32 | input = input.trim();
33 | let error: Error | null = null;
34 | try {
35 | if (!input.startsWith("http://") && !input.startsWith("https://")) {
36 | throw new Error("converting to proper URL");
37 | }
38 |
39 | const urlObj = new URL(input);
40 | if (ignoreProtocol) {
41 | if (urlObj.hostname.startsWith("localhost") || isAnIpAddress(urlObj.hostname)) {
42 | input = "http://" + urlObj.host;
43 | } else {
44 | input = "https://" + urlObj.host;
45 | }
46 | } else {
47 | input = urlObj.protocol + "//" + urlObj.host;
48 | }
49 | return input;
50 | // eslint-disable-next-line no-empty
51 | } catch (err) {
52 | error = err;
53 | logDebugMessage(err);
54 | }
55 |
56 | if (input.startsWith("/")) {
57 | throw new Error("Please provide a valid domain name");
58 | }
59 |
60 | // not a valid URL
61 | if (input.indexOf(".") === 0) {
62 | input = input.substr(1);
63 | }
64 | // If the input contains a . it means they have given a domain name.
65 | // So we try assuming that they have given a domain name
66 | if (
67 | (input.indexOf(".") !== -1 || input.startsWith("localhost")) &&
68 | !input.startsWith("http://") &&
69 | !input.startsWith("https://")
70 | ) {
71 | input = "https://" + input;
72 | // at this point, it should be a valid URL. So we test that before doing a recursive call
73 | try {
74 | new URL(input);
75 | return normaliseURLDomainOrThrowError(input, true);
76 |
77 | // eslint-disable-next-line no-empty
78 | } catch (err) {
79 | throw err;
80 | }
81 | }
82 |
83 | if (error === null) {
84 | error = new Error("Please provide a valid domain name");
85 | }
86 |
87 | throw error;
88 | }
89 |
--------------------------------------------------------------------------------
/examples/with-thirdparty/ios/withthirdparty/AppDelegate.mm:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 | #import
5 | #import
6 |
7 | @implementation AppDelegate
8 |
9 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
10 | {
11 | self.moduleName = @"main";
12 |
13 | // You can add your custom initial props in the dictionary below.
14 | // They will be passed down to the ViewController used by React Native.
15 | self.initialProps = @{};
16 |
17 | return [super application:application didFinishLaunchingWithOptions:launchOptions];
18 | }
19 |
20 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
21 | {
22 | #if DEBUG
23 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@".expo/.virtual-metro-entry"];
24 | #else
25 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
26 | #endif
27 | }
28 |
29 | // Linking API
30 | - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options {
31 | BOOL handled;
32 |
33 | handled = [GIDSignIn.sharedInstance handleURL:url];
34 | if (handled) {
35 | return YES;
36 | }
37 |
38 | if ([self.authorizationFlowManagerDelegate resumeExternalUserAgentFlowWithURL:url]) {
39 | return YES;
40 | }
41 |
42 | return [super application:application openURL:url options:options] || [RCTLinkingManager application:application openURL:url options:options];
43 | }
44 |
45 | // Universal Links
46 | - (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray> * _Nullable))restorationHandler {
47 | BOOL result = [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
48 | return [super application:application continueUserActivity:userActivity restorationHandler:restorationHandler] || result;
49 | }
50 |
51 | // Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
52 | - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
53 | {
54 | return [super application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
55 | }
56 |
57 | // Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
58 | - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
59 | {
60 | return [super application:application didFailToRegisterForRemoteNotificationsWithError:error];
61 | }
62 |
63 | // Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
64 | - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
65 | {
66 | return [super application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
67 | }
68 |
69 | @end
70 |
--------------------------------------------------------------------------------
/lib/build/normalisedURLPath.js:
--------------------------------------------------------------------------------
1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
2 | *
3 | * This software is licensed under the Apache License, Version 2.0 (the
4 | * "License") as published by the Apache Software Foundation.
5 | *
6 | * You may not use this file except in compliance with the License. You may
7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 | * License for the specific language governing permissions and limitations
13 | * under the License.
14 | */
15 | export default class NormalisedURLPath {
16 | constructor(url) {
17 | this.startsWith = other => {
18 | return this.value.startsWith(other.value);
19 | };
20 | this.appendPath = other => {
21 | return new NormalisedURLPath(this.value + other.value);
22 | };
23 | this.getAsStringDangerous = () => {
24 | return this.value;
25 | };
26 | this.value = normaliseURLPathOrThrowError(url);
27 | }
28 | }
29 | function normaliseURLPathOrThrowError(input) {
30 | input = input.trim();
31 | try {
32 | if (!input.startsWith("http://") && !input.startsWith("https://")) {
33 | throw new Error("converting to proper URL");
34 | }
35 | const urlObj = new URL(input);
36 | input = urlObj.pathname;
37 | if (input.charAt(input.length - 1) === "/") {
38 | return input.substr(0, input.length - 1);
39 | }
40 | return input;
41 | // eslint-disable-next-line no-empty
42 | } catch (err) {}
43 | // not a valid URL
44 | // If the input contains a . it means they have given a domain name.
45 | // So we try assuming that they have given a domain name + path
46 | if (
47 | (domainGiven(input) || input.startsWith("localhost")) &&
48 | !input.startsWith("http://") &&
49 | !input.startsWith("https://")
50 | ) {
51 | input = "http://" + input;
52 | return normaliseURLPathOrThrowError(input);
53 | }
54 | if (input.charAt(0) !== "/") {
55 | input = "/" + input;
56 | }
57 | // at this point, we should be able to convert it into a fake URL and recursively call this function.
58 | try {
59 | // test that we can convert this to prevent an infinite loop
60 | new URL("http://example.com" + input);
61 | return normaliseURLPathOrThrowError("http://example.com" + input);
62 | } catch (err) {
63 | throw new Error("Please provide a valid URL path");
64 | }
65 | }
66 | function domainGiven(input) {
67 | // If no dot, return false.
68 | if (input.indexOf(".") === -1 || input.startsWith("/")) {
69 | return false;
70 | }
71 | try {
72 | const url = new URL(input);
73 | return url.hostname.indexOf(".") !== -1;
74 | } catch (e) {}
75 | try {
76 | const url = new URL("http://" + input);
77 | return url.hostname.indexOf(".") !== -1;
78 | } catch (e) {}
79 | return false;
80 | }
81 |
--------------------------------------------------------------------------------
/TestingApp/test/tough-cookie/lib/store.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Copyright (c) 2015, Salesforce.com, Inc.
3 | * All rights reserved.
4 | *
5 | * Redistribution and use in source and binary forms, with or without
6 | * modification, are permitted provided that the following conditions are met:
7 | *
8 | * 1. Redistributions of source code must retain the above copyright notice,
9 | * this list of conditions and the following disclaimer.
10 | *
11 | * 2. Redistributions in binary form must reproduce the above copyright notice,
12 | * this list of conditions and the following disclaimer in the documentation
13 | * and/or other materials provided with the distribution.
14 | *
15 | * 3. Neither the name of Salesforce.com nor the names of its contributors may
16 | * be used to endorse or promote products derived from this software without
17 | * specific prior written permission.
18 | *
19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 | * POSSIBILITY OF SUCH DAMAGE.
30 | */
31 | "use strict";
32 | /*jshint unused:false */
33 |
34 | function Store() {}
35 | exports.Store = Store;
36 |
37 | // Stores may be synchronous, but are still required to use a
38 | // Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
39 | // API that converts from synchronous-callbacks to imperative style.
40 | Store.prototype.synchronous = false;
41 |
42 | Store.prototype.findCookie = function(domain, path, key, cb) {
43 | throw new Error("findCookie is not implemented");
44 | };
45 |
46 | Store.prototype.findCookies = function(domain, path, cb) {
47 | throw new Error("findCookies is not implemented");
48 | };
49 |
50 | Store.prototype.putCookie = function(cookie, cb) {
51 | throw new Error("putCookie is not implemented");
52 | };
53 |
54 | Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
55 | // recommended default implementation:
56 | // return this.putCookie(newCookie, cb);
57 | throw new Error("updateCookie is not implemented");
58 | };
59 |
60 | Store.prototype.removeCookie = function(domain, path, key, cb) {
61 | throw new Error("removeCookie is not implemented");
62 | };
63 |
64 | Store.prototype.removeCookies = function(domain, path, cb) {
65 | throw new Error("removeCookies is not implemented");
66 | };
67 |
68 | Store.prototype.removeAllCookies = function(cb) {
69 | throw new Error("removeAllCookies is not implemented");
70 | };
71 |
72 | Store.prototype.getAllCookies = function(cb) {
73 | throw new Error("getAllCookies is not implemented (therefore jar cannot be serialized)");
74 | };
75 |
--------------------------------------------------------------------------------
/lib/build/types.d.ts:
--------------------------------------------------------------------------------
1 | import OverrideableBuilder from "supertokens-js-override";
2 | export type Event = {
3 | action: "SIGN_OUT" | "REFRESH_SESSION" | "SESSION_CREATED";
4 | } | {
5 | action: "UNAUTHORISED";
6 | sessionExpiredOrRevoked: boolean;
7 | };
8 | export type EventHandler = (event: Event) => void;
9 | export type InputType = {
10 | enableDebugLogs?: boolean;
11 | apiDomain: string;
12 | apiBasePath?: string;
13 | sessionExpiredStatusCode?: number;
14 | autoAddCredentials?: boolean;
15 | tokenTransferMethod?: "cookie" | "header";
16 | /**
17 | * This specifies the maximum number of times the interceptor will attempt to refresh
18 | * the session when a 401 Unauthorized response is received. If the number of retries
19 | * exceeds this limit, no further attempts will be made to refresh the session, and
20 | * and an error will be thrown.
21 | */
22 | maxRetryAttemptsForSessionRefresh?: number;
23 | sessionTokenBackendDomain?: string;
24 | preAPIHook?: (context: {
25 | action: "SIGN_OUT" | "REFRESH_SESSION";
26 | requestInit: RequestInit;
27 | url: string;
28 | }) => Promise<{
29 | url: string;
30 | requestInit: RequestInit;
31 | }>;
32 | onHandleEvent?: EventHandler;
33 | override?: {
34 | functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface;
35 | };
36 | };
37 | export type NormalisedInputType = {
38 | apiDomain: string;
39 | apiBasePath: string;
40 | sessionExpiredStatusCode: number;
41 | autoAddCredentials: boolean;
42 | tokenTransferMethod: string;
43 | maxRetryAttemptsForSessionRefresh: number;
44 | sessionTokenBackendDomain: string | undefined;
45 | preAPIHook: (context: {
46 | action: "SIGN_OUT" | "REFRESH_SESSION";
47 | requestInit: RequestInit;
48 | url: string;
49 | }) => Promise<{
50 | url: string;
51 | requestInit: RequestInit;
52 | }>;
53 | onHandleEvent: EventHandler;
54 | override: {
55 | functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface;
56 | };
57 | };
58 | export type PreAPIHookFunction = (context: {
59 | requestInit: RequestInit;
60 | url: string;
61 | }) => Promise<{
62 | url: string;
63 | requestInit: RequestInit;
64 | }>;
65 | export type RecipeInterface = {
66 | addFetchInterceptorsAndReturnModifiedFetch: (originalFetch: any, config: NormalisedInputType) => typeof fetch;
67 | addAxiosInterceptors: (axiosInstance: any, config: NormalisedInputType) => void;
68 | getUserId: (config: NormalisedInputType) => Promise;
69 | getAccessTokenPayloadSecurely: (config: NormalisedInputType) => Promise;
70 | doesSessionExist: (config: NormalisedInputType) => Promise;
71 | signOut: (config: NormalisedInputType) => Promise;
72 | shouldDoInterceptionBasedOnUrl(toCheckUrl: string, apiDomain: string, sessionTokenBackendDomain: string | undefined): boolean;
73 | };
74 | export type IdRefreshTokenType = {
75 | status: "NOT_EXISTS" | "MAY_EXIST";
76 | } | {
77 | status: "EXISTS";
78 | token: string;
79 | };
80 | export type TokenType = "access" | "refresh";
81 |
--------------------------------------------------------------------------------