Skip to content

Commit

Permalink
Update changes with main
Browse files Browse the repository at this point in the history
  • Loading branch information
benmalcom committed Feb 29, 2024
1 parent 19f6d81 commit aa48352
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 49 deletions.
12 changes: 8 additions & 4 deletions packages/near-fast-auth-signer/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import debug from 'debug';
import React from 'react';
import {
Route, BrowserRouter as Router, Routes
Route, BrowserRouter as Router, Routes,
} from 'react-router-dom';

import AddDevice from './components/AddDevice/AddDevice';
import AuthCallbackPage from './components/AuthCallback/AuthCallback';
import AuthIndicator from './components/AuthIndicator/AuthIndicator';
import CreateAccount from './components/CreateAccount/CreateAccount';
import Devices from './components/Devices/Devices';
import InitializeGlobals from './components/InitializeGlobals/InitializeGlobals';
import Login from './components/Login/Login';
import RemoveTrailingSlash from './components/RemoveTrailingSlash/RemoveTrailingSlash';
import RpcRoute from './components/RpcRoute/RpcRoute';
import Sign from './components/Sign/Sign';
import VerifyEmailPage from './components/VerifyEmail/verify-email';
import FastAuthController from './lib/controller';
import './styles/theme.css';
import './styles/globals.css';
import GlobalStyle from './styles/index';
import { basePath } from './utils/config';
import { basePath, networkId } from './utils/config';

(window as any).fastAuthController = new FastAuthController({
accountId: 'harisvalj.testnet',
networkId
});

const faLog = debug('fastAuth');
const log = faLog.extend('App');
Expand All @@ -43,7 +48,6 @@ export default function App() {
<GlobalStyle />
<Router basename={basePath || ''}>
<RemoveTrailingSlash />
<InitializeGlobals />
<Routes>
<Route path="/">
<Route index element={<AuthIndicator />} />
Expand Down
86 changes: 46 additions & 40 deletions packages/near-fast-auth-signer/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { captureException } from '@sentry/react';
import { KeyPair } from 'near-api-js';

import { network } from '../utils/config';
Expand All @@ -10,26 +9,33 @@ import {
* Fetches the account IDs associated with a given public key.
*
* @param publicKey - The public key to fetch the account IDs for.
* @param options - An object containing the following properties:
* - returnEmpty: A boolean indicating whether to return an empty array if no account IDs are found.
* @returns A promise that resolves to an array of account IDs.
* @throws Will throw an error if the fetch request fails.
*/
export const fetchAccountIds = async (publicKey: string): Promise<string[]> => {
const res = await fetch(`${network.fastAuth.authHelperUrl}/publicKey/${publicKey}/accounts`);
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}

let accountIds: string[] = await res.json();

if (accountIds.length === 0) {
type Option= {
returnEmpty?: boolean;
}
export const fetchAccountIds = async (publicKey: string, options?: Option): Promise<string[]> => {
// retrieve from firebase
let accountIds = [];
if (publicKey) {
const accountId = await window.firestoreController.getAccountIdByPublicKey(publicKey);
accountIds = accountId ? [accountId] : [];
if (accountId) {
return [accountId];
}
// retrieve from kitwallet
const res = await fetch(`${network.fastAuth.authHelperUrl}/publicKey/${publicKey}/accounts`);
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
accountIds = await res.json();
}

if (accountIds.length === 0) {
const noAccountIdError = new Error('Unable to retrieve account id');
captureException(noAccountIdError);
throw noAccountIdError;
if (accountIds.length === 0 && !options?.returnEmpty) {
throw new Error('Unable to retrieve account id');
}

return accountIds;
Expand All @@ -44,35 +50,35 @@ type LimitedAccessKey = {

type NewAccountResponse =
| {
type: 'ok',
create_account_options: {
full_access_keys: string[] | null,
limited_access_keys: LimitedAccessKey[] | null,
contract_bytes: string[] | null
},
user_recovery_public_key: string,
near_account_id: string
}
type: 'ok',
create_account_options: {
full_access_keys: string[] | null,
limited_access_keys: LimitedAccessKey[] | null,
contract_bytes: string[] | null
},
user_recovery_public_key: string,
near_account_id: string
}
| {
type: 'err',
msg: string
};
type: 'err',
msg: string
};

/**
* This function creates a new account on the NEAR blockchain by sending a request to the /new_account endpoint of the MPC recovery service.
*
* @param accountId - The ID of the new account to be created on the NEAR blockchain.
* @param fullAccessKeys - An array of full access keys to be added to the account.
* @param limitedAccessKeys - An array of objects, each representing a limited access key to be associated with the account. Each object has the following properties:
* - public_key: The public key of the limited access key.
* - receiver_id: The contract_ID that the limited access key is authorized to call.
* - allowance: The maximum amount of NEAR tokens that the limited access key is allowed to spend on gas fees.
* - method_names: A string of comma-separated method names that the limited access key is allowed to call.
* @param accessToken - The OIDC access token.
* @param oidcKeypair - The public and private key pair of the FRP.
* @returns A promise that resolves to an object of type NewAccountResponse. This object contains the result of the account creation process. It can either be of type 'ok' with the account details or of type 'err' with an error message.
* @throws An error if the fetch request fails.
*/
* This function creates a new account on the NEAR blockchain by sending a request to the /new_account endpoint of the MPC recovery service.
*
* @param accountId - The ID of the new account to be created on the NEAR blockchain.
* @param fullAccessKeys - An array of full access keys to be added to the account.
* @param limitedAccessKeys - An array of objects, each representing a limited access key to be associated with the account. Each object has the following properties:
* - public_key: The public key of the limited access key.
* - receiver_id: The contract_ID that the limited access key is authorized to call.
* - allowance: The maximum amount of NEAR tokens that the limited access key is allowed to spend on gas fees.
* - method_names: A string of comma-separated method names that the limited access key is allowed to call.
* @param accessToken - The OIDC access token.
* @param oidcKeypair - The public and private key pair of the FRP.
* @returns A promise that resolves to an object of type NewAccountResponse. This object contains the result of the account creation process. It can either be of type 'ok' with the account details or of type 'err' with an error message.
* @throws An error if the fetch request fails.
*/
export const createNEARAccount = async ({
accountId,
fullAccessKeys = [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const onCreateAccount = async ({
setStatusMessage('Account created successfully!');

// TODO: Check if account ID matches the one from email

console.log('publicKeyFak ', publicKeyFak);
if (publicKeyFak) {
window.localStorage.setItem('webauthn_username', email);
}
Expand Down Expand Up @@ -102,9 +102,7 @@ export const onSignIn = async ({
gateway,
}) => {
const recoveryPK = await window.fastAuthController.getUserCredential(accessToken);
const accountIds = await fetchAccountIds(recoveryPK).catch(() => {
throw new Error('Account not found, please create an account and try again');
});
const accountIds = await fetchAccountIds(recoveryPK, { returnEmpty: true });

// TODO: If we want to remove old LAK automatically, use below code and add deleteKeyActions to signAndSendActionsWithRecoveryKey
// const existingDevice = await window.firestoreController.getDeviceCollection(publicKeyFak);
Expand Down
2 changes: 1 addition & 1 deletion packages/near-fast-auth-signer/src/hooks/useAuthState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const getAuthState = async (email?: string | null): Promise<AuthState> =>
const keypairs = await getKeys(webauthnUsername);
const accounts = await Promise.allSettled(
keypairs.map(async (k) => {
const accIds = await fetchAccountIds(k.getPublicKey().toString());
const accIds = await fetchAccountIds(k.getPublicKey().toString(), { returnEmpty: true });
return accIds.map((accId) => { return { accId, keyPair: k }; });
})
);
Expand Down
5 changes: 5 additions & 0 deletions packages/near-fast-auth-signer/src/lib/firestoreController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ class FirestoreController {
async getAccountIdFromOidcToken() {
const recoveryPK = await window.fastAuthController.getUserCredential(this.oidcToken);
const accountIds = await fetchAccountIds(recoveryPK);
if (!accountIds.length) {
const noAccountIdError = new Error('Unable to retrieve account Id');
captureException(noAccountIdError);
throw noAccountIdError;
}
return accountIds[0];
}

Expand Down

0 comments on commit aa48352

Please sign in to comment.