Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New @turnkey/iframe-stamper package and email recovery example #129

Merged
merged 13 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .codesandbox/ci.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"packages/http",
"packages/viem",
"packages/webauthn-stamper",
"packages/api-key-stamper"
"packages/api-key-stamper",
"packages/iframe-stamper"
],
"sandboxes": [],
"node": "18"
Expand Down
7 changes: 7 additions & 0 deletions examples/email-recovery/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
API_PUBLIC_KEY="<Turnkey API Public Key (that starts with 02 or 03)>"
API_PRIVATE_KEY="<Turnkey API Private Key>"
NEXT_PUBLIC_ORGANIZATION_ID="<Turnkey organization ID>"
NEXT_PUBLIC_BASE_URL="https://api.turnkey.com"
# Can be changed to a localhost iframe if you're modifying the recovery flow
# For production, the URL should not be changed and point to the primary Turnkey domain.
NEXT_PUBLIC_RECOVERY_IFRAME_URL="https://recovery.turnkey.com"
3 changes: 3 additions & 0 deletions examples/email-recovery/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
35 changes: 35 additions & 0 deletions examples/email-recovery/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
55 changes: 55 additions & 0 deletions examples/email-recovery/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Example: `email-recovery`

This example shows a complete email recovery flow. It contains a NextJS app with:

- a frontend application
- a backend application

The overall flow for email recovery is outlined below:
![Email recovery flow diagram](./email_recovery_steps.png)

This example contains an example recovery page as well as a stub API endpoint for "your business" (where the email is resolved into an organization ID). The creation of the hidden iframe is abstracted by our `@turnkey/iframe-stamper` package.

## Getting started

### 1/ Cloning the example

Make sure you have `node` installed locally; we recommend using Node v16+.

```bash
$ git clone https://github.com/tkhq/sdk
$ cd sdk/
$ corepack enable # Install `pnpm`
$ pnpm install -r # Install dependencies
$ pnpm run build-all # Compile source code
$ cd examples/email-recovery/
```

### 2/ Setting up Turnkey

The first step is to set up your Turnkey organization and account. By following the [Quickstart](https://docs.turnkey.com/getting-started/quickstart) guide, you should have:

- A public/private API key pair for Turnkey
- An organization ID

Once you've gathered these values, add them to a new `.env.local` file. Notice that your API private key should be securely managed and **_never_** be committed to git.

```bash
$ cp .env.local.example .env.local
```

Now open `.env.local` and add the missing environment variables:

- `API_PUBLIC_KEY`
- `API_PRIVATE_KEY`
- `NEXT_PUBLIC_ORGANIZATION_ID`
- `NEXT_PUBLIC_BASE_URL` (the `NEXT_PUBLIC` prefix makes the env variable accessible to the frontend app)
- `NEXT_PUBLIC_RECOVERY_IFRAME_URL`

### 3/ Running the app

```bash
$ pnpm run dev
```

This command will run a NextJS app on port 3000. If you navigate to http://localhost:3000 in your browser, you can follow the prompts to start an email recovery.
Binary file added examples/email-recovery/email_recovery_steps.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions examples/email-recovery/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

module.exports = nextConfig;
32 changes: 32 additions & 0 deletions examples/email-recovery/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@turnkey/example-email-recovery",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@turnkey/http": "workspace:*",
"@turnkey/api-key-stamper": "workspace:*",
"@turnkey/iframe-stamper": "workspace:*",
"@types/node": "20.3.1",
"@types/react": "18.2.14",
"@types/react-dom": "18.2.6",
"axios": "^1.4.0",
"encoding": "^0.1.13",
"eslint": "8.43.0",
"eslint-config-next": "13.4.7",
"esm": "^3.2.25",
"install": "^0.13.0",
"next": "13.4.7",
"npm": "^9.7.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.45.1",
"typescript": "5.1.3"
}
emostov marked this conversation as resolved.
Show resolved Hide resolved
}
25 changes: 25 additions & 0 deletions examples/email-recovery/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.
Binary file not shown.
29 changes: 29 additions & 0 deletions examples/email-recovery/public/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions examples/email-recovery/src/components/Recovery.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"use client";

import { IframeStamper } from "@turnkey/iframe-stamper";
import { Dispatch, SetStateAction, useEffect, useState } from "react";

interface RecoveryProps {
iframeUrl: string;
turnkeyBaseUrl: string;
setIframeStamper: Dispatch<SetStateAction<IframeStamper | null>>;
}

const TurnkeyIframeContainerId = "turnkey-iframe-container-id";
const TurnkeyIframeElementId = "turnkey-iframe-element-id";

export function Recovery(props: RecoveryProps) {
const [iframeStamper, setIframeStamper] = useState<IframeStamper | null>(
null
);

useEffect(() => {
if (!iframeStamper) {
const iframeStamper = new IframeStamper({
iframeUrl: props.iframeUrl,
iframeContainerId: TurnkeyIframeContainerId,
iframeElementId: TurnkeyIframeElementId,
});
iframeStamper.init().then(() => {
setIframeStamper(iframeStamper);
props.setIframeStamper(iframeStamper);
});
}

return () => {
if (iframeStamper) {
iframeStamper.clear();
setIframeStamper(null);
}
};
}, [props, iframeStamper, setIframeStamper]);

return <div style={{ display: "none" }} id={TurnkeyIframeContainerId}></div>;
}
19 changes: 19 additions & 0 deletions examples/email-recovery/src/pages/_document.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Document, { Html, Head, Main, NextScript } from "next/document";

class Example extends Document {
render() {
return (
<Html>
<Head>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

export default Example;
73 changes: 73 additions & 0 deletions examples/email-recovery/src/pages/api/initRecovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { TurnkeyClient, createActivityPoller } from "@turnkey/http";
import { ApiKeyStamper } from "@turnkey/api-key-stamper";

type InitRecoveryRequest = {
email: string;
targetPublicKey: string;
};

/**
* Returns the userId starting recovery (available in `INIT_USER_EMAIL_RECOVERY` activity result)
* as well as the organization ID. These two pieces of information are useful because they are used
* inside of the `RECOVER_USER` activity params.
*/
type InitRecoveryResponse = {
userId: string;
organizationId: string;
};

type ErrorMessage = {
message: string;
};

export default async function initRecovery(
req: NextApiRequest,
res: NextApiResponse<InitRecoveryResponse | ErrorMessage>
) {
try {
const request = req.body as InitRecoveryRequest;
const turnkeyClient = new TurnkeyClient(
{ baseUrl: process.env.NEXT_PUBLIC_BASE_URL! },
new ApiKeyStamper({
apiPublicKey: process.env.API_PUBLIC_KEY!,
apiPrivateKey: process.env.API_PRIVATE_KEY!,
})
);

const activityPoller = createActivityPoller({
client: turnkeyClient,
requestFn: turnkeyClient.initUserEmailRecovery,
});

const completedActivity = await activityPoller({
type: "ACTIVITY_TYPE_INIT_USER_EMAIL_RECOVERY",
timestampMs: String(Date.now()),
// This is simple in the case of a single organization.
// If you use sub-organizations for each user, this needs to be replaced by the user's specific sub-organization.
organizationId: process.env.NEXT_PUBLIC_ORGANIZATION_ID!,
parameters: {
email: request.email,
targetPublicKey: request.targetPublicKey,
},
});

const userId = completedActivity.result.initUserEmailRecoveryResult?.userId;
if (!userId) {
throw new Error("Expected a non-null user ID!");
}

res.status(200).json({
userId: userId,
// This is simple in the case of a single organization
// If you use sub-organizations for each user, this needs to be replaced by the user's specific sub-organization.
organizationId: process.env.NEXT_PUBLIC_ORGANIZATION_ID!,
});
} catch (e) {
console.error(e);

res.status(500).json({
message: "Something went wrong.",
});
}
}
Loading