Skip to content

Commit

Permalink
Fix/OIDC incompatible (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
rustin01 authored Aug 1, 2024
1 parent 14505f5 commit 14d03bc
Show file tree
Hide file tree
Showing 42 changed files with 5,657 additions and 32 deletions.
1 change: 1 addition & 0 deletions apps/wallet/.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ VITE_RELEASE_VERSION=v1.0
VITE_HIBIT_ID_API=https://api.hibit.app/
VITE_TELEGRAM_BOT_ID=6944468360
VITE_SYSTEM_MAX_DECIMALS=8
VITE_OIDC_REFRESH_TOKEN_TIMEOUT=3600000
1 change: 1 addition & 0 deletions apps/wallet/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ VITE_HIBIT_AUTH_SERVER=https://testnetauth.hibit.app/
VITE_HIBIT_AUTH_CLIENT_ID=hibit_id_local
VITE_TELEGRAM_BOT_ID=6944468360
VITE_SYSTEM_MAX_DECIMALS=8
VITE_OIDC_REFRESH_TOKEN_TIMEOUT=3600000
8 changes: 6 additions & 2 deletions apps/wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"dayjs": "^1.11.11",
"ethers": "^6.13.1",
"i18next": "^23.12.2",
"oidc-spa": "^4.11.1",
"jwt-decode": "^4.0.0",
"oidc-client-ts": "^3.0.1",
"qrcode": "^1.5.3",
"react-hook-form": "^7.52.1",
"react-i18next": "^15.0.0",
Expand All @@ -41,8 +42,11 @@
"tailwind-merge": "^2.3.0",
"tonweb": "^0.0.66",
"tonweb-mnemonic": "^1.0.1",
"tsafe": "^1.7.2",
"tweetnacl": "^1.0.3",
"yup": "^1.4.0"
"worker-timers": "^8.0.3",
"yup": "^1.4.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@rollup/plugin-typescript": "^11.1.6",
Expand Down
18 changes: 16 additions & 2 deletions apps/wallet/src/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { QueryClient } from "@tanstack/react-query";
import hibitIdSession from "../stores/session";
import axios, { AxiosRequestConfig } from 'axios';
import { AuthServerErrorResponse } from "./models";
import toaster from "../components/Toaster";
import { prOidc } from "../utils/oidc";

export const queryClient = new QueryClient()

Expand All @@ -26,6 +28,17 @@ const authApiRequest = axios.create({
},
});

authApiRequest.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
hibitIdSession.disconnect();
toaster.error('User unauthorized, please login again');
}
return Promise.reject(error);
}
)

export const ex3ServiceClient = async <D>(config: ServiceRequestConfig<D>) => {
const { method = 'GET' } = config;
if (method === 'GET') config.params = config.data;
Expand Down Expand Up @@ -85,15 +98,16 @@ export const sendAuthRequest = async <TInput, TOutput>(
url: string,
method: 'GET' | 'POST' = 'POST'
): Promise<TOutput> => {
if (!hibitIdSession.auth?.idToken) {
const oidc = await prOidc
if (!oidc.isUserLoggedIn) {
throw new Error('No auth session');
}
const res = await authServiceClient<TInput>({
url: url,
method,
data: input,
headers: {
'Authorization': `Bearer ${hibitIdSession.auth.idToken}`
'Authorization': `Bearer ${oidc.getTokens().idToken}`
},
});
try {
Expand Down
2 changes: 1 addition & 1 deletion apps/wallet/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import rpcManager from './stores/rpc.ts'
import './i18n'
import HibitToastContainer from './components/Toaster/Container.tsx'
import BigNumber from 'bignumber.js'
import { OidcProvider } from './utils/oidc.ts'
import { OidcProvider } from './utils/oidc/index.ts'

BigNumber.config({ EXPONENTIAL_AT: 1e+9 });

Expand Down
2 changes: 1 addition & 1 deletion apps/wallet/src/stores/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { RuntimeEnv } from "../utils/basicEnums";
import rpcManager from "./rpc";
import { WalletAccount } from "@deland-labs/hibit-id-sdk";
import { TonChainWallet } from "../utils/chain/chain-wallets/ton";
import { Oidc } from "oidc-spa/oidc";
import { Oidc } from "../utils/oidc/lib/oidc-spa-4.11.1/src/oidc";
import { GetMnemonicAsync, UpdateMnemonicAsync } from "../apis/services/auth";
import { HibitIDError, HibitIDErrorCode } from "../utils/error-code";
import { GetMnemonicInput, GetMnemonicResult, UpdateMnemonicInput } from "../apis/models";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {createReactOidc} from "oidc-spa/react";
import {createReactOidc} from "./lib/oidc-spa-4.11.1/src/react";

export const {OidcProvider, useOidc, prOidc} = createReactOidc({
issuerUri: import.meta.env.VITE_HIBIT_AUTH_SERVER,
Expand Down
2 changes: 2 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# For GitHub language statistics: https://user-images.githubusercontent.com/6702424/127756647-5ebe6dde-0903-4a02-b1e8-529046dd06f2.png
.eslintrc.js -linguist-detectable
44 changes: 44 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

.vscode

.DS_Store

/.yarn_home
/dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/node_modules/
/dist/
/.eslintrc.js
/docs/
/CHANGELOG.md
/.yarn_home
11 changes: 11 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"printWidth": 105,
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": false,
"quoteProps": "preserve",
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "avoid"
}
38 changes: 38 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Contributing

PR and issues are welcomed!

### Testing your changes in an external app

You have made some changes to the code and you want to test them
in your app before submitting a pull request?

Assuming `you/my-app` have `oidc-spa` as a dependency.

```bash
cd ~/github
git clone https://github.com/you/my-app
cd my-app
yarn

cd ~/github
git clone https://github.com/garronej/oidc-spa
cd oidc-spa
yarn
yarn build
yarn link-in-app my-app
npx tsc -w

# Open another terminal

cd ~/github/my-app
rm -rf node_modules/.cache
yarn start # Or whatever my-app is using for starting the project
```

You don't have to use `~/github` as reference path. Just make sure `my-app` and `oidc-spa`
are in the same directory.

> Note for the maintainer: You might run into issues if you do not list all your singleton dependencies in
> `src/link-in-app.js -> singletonDependencies`. A singleton dependency is a dependency that can
> only be present once in an App. Singleton dependencies are usually listed as peerDependencies example `react`, `@emotion/*`.
21 changes: 21 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 GitHub user u/garronej

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
122 changes: 122 additions & 0 deletions apps/wallet/src/utils/oidc/lib/oidc-spa-4.11.1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
![oidc-spa](https://github.com/keycloakify/oidc-spa/assets/6702424/3375294c-cc31-4fc1-9fb5-1fcfa00423ba)

<p align="center">
<br>
<a href="https://github.com/keycloakify/oidc-spa/actions">
<img src="https://github.com/keycloakify/oidc-spa/actions/workflows/ci.yaml/badge.svg?branch=main">
</a>
<a href="https://bundlephobia.com/package/oidc-spa">
<img src="https://img.shields.io/bundlephobia/minzip/oidc-spa">
</a>
<a href="https://www.npmjs.com/package/oidc-spa">
<img src="https://img.shields.io/npm/dw/oidc-spa">
</a>
<a href="https://github.com/garronej/oidc-spa/blob/main/LICENSE">
<img src="https://img.shields.io/npm/l/oidc-spa">
</a>
</p>
<p align="center">
We're here to help!<br/>
<a href="https://discord.gg/mJdYJSdcm4">
<img src="https://dcbadge.limes.pink/api/server/kYFZG7fQmn"/>
</a>
</p>
<p align="center">
<a href="https://www.oidc-spa.dev">Home</a>
-
<a href="https://docs.oidc-spa.dev">Documentation</a>
</p>

An Open ID Connect client tailored for Single Page Applications, particularly suitable for [Vite](https://vitejs.dev/) projects.\
This library is intended for scenarios such as integrating your application with [Keycloak](https://www.keycloak.org/). &#x20;

In straightforward terms, this library is ideal for those seeking to enable user login/registration in their web application. When used in conjunction with Keycloak (for example), it enables you to offer a modern and secure authentication experience with minimal coding effort. This includes options for signing in via Google, X, GitHub, or other social media platforms. We provide comprehensive guidance from beginning to end.

- 🎓 Accessible to all skill levels; no need to be an OIDC expert. And we are here to help [on Discord](https://discord.gg/mJdYJSdcm4).
- 🛠️ Easy to set up; eliminates the need for creating special `/login` `/logout` routes.
- 💬 Helpful debug message telling you what's wrong in your configuration and how to fix it.
- 🎛️ Minimal API surface for ease of use.
- 🕣 Easy implementation of auto logout. _Are you still there? You will be logged out in 10...9..._
- ✨ Robust yet optional React integration.
- 📖 Comprehensive documentation and project examples: End-to-end solutions for authenticating your app.
- ✅ Best in class type safety: Enhanced API response types based on usage context.

## Comparison with Existing Libraries

### [oidc-client-ts](https://github.com/authts/oidc-client-ts)

While `oidc-client-ts` serves as a comprehensive toolkit, our library aims to provide a simplified, ready-to-use adapter that will pass
any security audit and that will just work out of the box on any browser.
We utilize `oidc-client-ts` internally but abstract away most of its intricacies.

### [react-oidc-context](https://github.com/authts/react-oidc-context)

`react-oidc-context` is a React wrapper around `oidc-client-ts`.
`oidc-spa` also feature a carefully crafted React API that comes with example
integration with:

- [`@tanstack/react-router`](https://docs.oidc-spa.dev/example-setups/tanstack-router)
- [`react-router-dom`](https://docs.oidc-spa.dev/example-setups/react-router)

### [keycloak-js](https://www.npmjs.com/package/keycloak-js)

The official OIDC Client for Keycloak. It only works with Keycloak and [will eventually be deprecated](https://www.keycloak.org/2023/03/adapter-deprecation-update).

### [NextAuth.js](https://next-auth.js.org/)

NextAuth.js is a authentication solution for Next.js and features a [Keycloak adapter](https://next-auth.js.org/providers/keycloak).
`oidc-spa` is specifically designed for Single Page Applications, Next.js projects do not call in this category, so NextAuth.js is what you should use if you're using Next.js.

> _NOTE: We might create in the future a `oidc-mpa` library for Multi Page Applications that would aim at supporting Next.js projects._
## 🚀 Quick start

Heads over to [the documentation website](https://docs.oidc-spa.dev) 📘!

## Sponsor

<br/>

<div align="center">

![Logo Dark](https://github.com/user-attachments/assets/935c0f10-6f7b-41f4-94cc-4540d0985569#gh-dark-mode-only)

</div>

<div align="center">

![Logo Light](https://github.com/user-attachments/assets/2e5bce29-4149-44fc-9d17-789e17e9642b#gh-light-mode-only)

</div>

<br/>

<p align="center">
<a href="https://www.zone2.tech/services/keycloak-consulting">
<i><strong>Keycloak Consulting Services</strong> - Your partner in Keycloak deployment, configuration, and extension development for optimized identity management solutions.</i>
</a>
</p>

Thank you, [Zone2](https://www.zone2.tech/), backing the project!

## Showcases

This library powers the authentication of the following platforms:

### Onyxia

- [Source code](https://github.com/InseeFrLab/onyxia)
- [Public instance](https://datalab.sspcloud.fr)

<a href="https://youtu.be/FvpNfVrxBFM">
<img width="1712" alt="image" src="https://user-images.githubusercontent.com/6702424/231314534-2eeb1ab5-5460-4caa-b78d-55afd400c9fc.png">
</a>

### The French Interministerial Base of Free Software

- [Source code](https://github.com/codegouvfr/sill-web/)
- [Deployment of the website](https://sill-preprod.lab.sspcloud.fr/)

<a href="https://youtu.be/AT3CvmY_Y7M?si=Edkf0vRNjosGLA3R">
<img width="1712" alt="image" src="https://github.com/garronej/i18nifty/assets/6702424/aa06cc30-b2bd-4c8b-b435-2f875f53175b">
</a>
Loading

0 comments on commit 14d03bc

Please sign in to comment.