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

feat: add hanko api passkey integration #606

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 9 additions & 1 deletion apps/api/api-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,12 @@ export type {
GetPresetByIdApi,
UpdatePresetApi,
GetAllPresetApi,
} from '../dist/schemas/index.js';
PasskeyStartRegistrationApi,
PasskeyFinalizeRegistrationApi,
PasskeyStartLoginApi,
PasskeyFinalizeLoginApi,
UserInfoApi,
DeleteCredentialApi,
PasskeyListCredentialsApi,
PasskeyUpdateCredentialsApi,
} from '../dist/schemas/index.d.ts';
35 changes: 20 additions & 15 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,33 +40,38 @@
"license": "ISC",
"dependencies": {
"@codeimage/prisma-models": "workspace:*",
"@fastify/autoload": "^5.7.1",
"@fastify/cors": "^8.3.0",
"@fastify/env": "^4.2.0",
"@fastify/jwt": "^6.7.1",
"@fastify/sensible": "^5.2.0",
"@fastify/swagger": "^8.5.1",
"@fastify/swagger-ui": "^1.8.1",
"@fastify/type-provider-typebox": "^3.2.0",
"@fastify/auth": "^4.4.0",
"@fastify/autoload": "^5.8.0",
"@fastify/cors": "^8.4.2",
"@fastify/env": "^4.3.0",
"@fastify/jwt": "^7.2.4",
"@fastify/sensible": "^5.5.0",
"@fastify/swagger": "^8.12.1",
"@fastify/swagger-ui": "^2.0.1",
"@fastify/type-provider-typebox": "^3.5.0",
"@prisma/client": "^4.15.0",
"@sinclair/typebox": "^0.28.15",
"@sinclair/typebox": "^0.31.28",
"@teamhanko/passkeys-sdk": "^0.1.8",
"auth0": "4.3.1",
"close-with-grace": "^1.2.0",
"dotenv": "^16.1.4",
"dotenv-cli": "^6.0.0",
"fastify": "^4.18.0",
"fastify-auth0-verify": "^1.2.0",
"fastify-cli": "^5.7.1",
"fastify": "^4.25.1",
"fastify-auth0-verify": "^1.2.1",
"fastify-cli": "^5.9.0",
"fastify-healthcheck": "^4.4.0",
"fastify-plugin": "^4.5.0",
"fluent-json-schema": "^4.1.0",
"fastify-jwt-jwks": "^1.1.4",
"fastify-overview": "^3.6.0",
"fastify-plugin": "^4.5.1",
"fluent-json-schema": "^4.2.1",
"prisma": "^4.15.0"
},
"devDependencies": {
"@types/node": "^18.16.17",
"@types/sinon": "^10.0.15",
"@vitest/ui": "^0.31.4",
"concurrently": "^7.6.0",
"fastify-tsconfig": "^1.0.1",
"fastify-tsconfig": "^2.0.0",
"sinon": "^15.1.2",
"tsup": "6.7.0",
"tsx": "3.12.7",
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ declare module 'fastify' {
GRANT_TYPE_AUTH0?: string;
ALLOWED_ORIGINS?: string;
PRESETS_LIMIT?: number;
HANKO_PASSKEYS_LOGIN_BASE_URL: string;
HANKO_PASSKEYS_TENANT_ID: string;
HANKO_PASSKEYS_API_KEY: string;
};
}
}
Expand Down Expand Up @@ -51,6 +54,9 @@ const app: FastifyPluginAsync<AppOptions> = async (
GRANT_TYPE_AUTH0: Type.String(),
ALLOWED_ORIGINS: Type.String(),
PRESETS_LIMIT: Type.Number({default: Number.MAX_SAFE_INTEGER}),
HANKO_PASSKEYS_LOGIN_BASE_URL: Type.String(),
HANKO_PASSKEYS_TENANT_ID: Type.String(),
HANKO_PASSKEYS_API_KEY: Type.String(),
}),
});

Expand All @@ -61,6 +67,7 @@ const app: FastifyPluginAsync<AppOptions> = async (
dir: join(__dirname, 'plugins'),
options: opts,
forceESM: true,
encapsulate: false,
});

// This loads all plugins defined in routes
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import {User} from '@codeimage/prisma-models';
import '@fastify/jwt';
import {
FastifyInstance,
FastifyPluginAsync,
FastifyReply,
FastifyRequest,
preHandlerHookHandler,
} from 'fastify';
import fastifyAuth0Verify, {Authenticate} from 'fastify-auth0-verify';
import fp from 'fastify-plugin';
import {AuthorizeOptions} from './authorize.js';

declare module '@fastify/jwt' {
interface FastifyJWT {
Expand All @@ -16,10 +15,6 @@ declare module '@fastify/jwt' {
}
}

interface AuthorizeOptions {
mustBeAuthenticated: boolean;
}

export function mockAuthProvider(context: {email: string}) {
return fp(async (fastify: FastifyInstance) => {
const auth0Authenticate: Authenticate = async req => {
Expand All @@ -36,31 +31,28 @@ export function mockAuthProvider(context: {email: string}) {
});
}

export default fp<{authProvider?: FastifyPluginAsync}>(
async (fastify, options) => {
if (fastify.config.MOCK_AUTH) {
await fastify.register(
mockAuthProvider({
email: fastify.config.MOCK_AUTH_EMAIL as string,
}),
);
} else if (options.authProvider) {
await fastify.register(options.authProvider);
} else {
await fastify.register(fastifyAuth0Verify.default, {
domain: fastify.config.DOMAIN_AUTH0,
secret: fastify.config.CLIENT_SECRET_AUTH,
audience: fastify.config.AUDIENCE_AUTH0,
});
}
export const auth0Plugin: FastifyPluginAsync<{
authProvider?: FastifyPluginAsync;
}> = async (fastify, options) => {
if (fastify.config.MOCK_AUTH) {
await fastify.register(
mockAuthProvider({
email: fastify.config.MOCK_AUTH_EMAIL as string,
}),
);
} else if (options.authProvider) {
await fastify.register(options.authProvider);
} else {
await fastify.register(fastifyAuth0Verify.default, {
domain: fastify.config.DOMAIN_AUTH0,
secret: fastify.config.CLIENT_SECRET_AUTH,
audience: fastify.config.AUDIENCE_AUTH0,
});
}

async function authorize(
req: FastifyRequest,
reply: FastifyReply,
options: AuthorizeOptions = {
mustBeAuthenticated: true,
},
) {
const authorize: (options?: AuthorizeOptions) => preHandlerHookHandler =
(options = {mustBeAuthenticated: true}) =>
async (req, reply) => {
try {
await fastify.authenticate(req, reply);
} catch (e) {
Expand All @@ -71,9 +63,8 @@ export default fp<{authProvider?: FastifyPluginAsync}>(

const emailClaim = `${fastify.config.AUTH0_CLIENT_CLAIMS}/email`;

if (!req.user) {
req.appUserOptional = null;
return;
if (!req.user && options.mustBeAuthenticated) {
throw fastify.httpErrors.unauthorized();
}

const email = req.user[emailClaim] as string;
Expand All @@ -97,26 +88,13 @@ export default fp<{authProvider?: FastifyPluginAsync}>(
} else {
req.appUser = user;
}
};

req.appUserOptional = req.appUser;
}

fastify.decorateRequest('appUser', null);
fastify.decorate('authorize', authorize);
},
);
fastify.decorate('verifyAuth0', authorize);
};

declare module 'fastify' {
interface FastifyInstance {
authorize: (
req: FastifyRequest,
reply: FastifyReply,
options?: AuthorizeOptions,
) => void;
}

interface FastifyRequest {
appUser: User;
appUserOptional: User | null;
verifyAuth0: (options?: AuthorizeOptions) => preHandlerHookHandler;
}
}
3 changes: 3 additions & 0 deletions apps/api/src/common/auth/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface AuthorizeOptions {
mustBeAuthenticated: boolean;
}
27 changes: 27 additions & 0 deletions apps/api/src/common/auth/multiAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import fastifyAuth from '@fastify/auth';
import {FastifyPluginAsync, preHandlerHookHandler} from 'fastify';
import {AuthorizeOptions} from './authorize.js';

export const multiAuthProviderPlugin: FastifyPluginAsync = async fastify => {
fastify.register(fastifyAuth);

const preHookHandler: (
options?: AuthorizeOptions,
) => preHandlerHookHandler = (options = {mustBeAuthenticated: true}) =>
function (request, reply, done) {
return fastify
.auth([
fastify.verifyAuth0(options),
fastify.verifyHankoPasskey(options),
])
.apply(this, [request, reply, done]);
};

fastify.decorate('authorize', preHookHandler);
};

declare module 'fastify' {
interface FastifyInstance {
authorize: (options?: AuthorizeOptions) => preHandlerHookHandler;
}
}
50 changes: 50 additions & 0 deletions apps/api/src/common/auth/passkeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {tenant} from '@teamhanko/passkeys-sdk';
import {FastifyPluginAsync, preHandlerHookHandler} from 'fastify';

interface AuthorizeOptions {
mustBeAuthenticated: boolean;
}

export const passkeysPlugin: FastifyPluginAsync = async fastify => {
const passkeysApi = tenant({
tenantId: fastify.config.HANKO_PASSKEYS_TENANT_ID,
apiKey: fastify.config.HANKO_PASSKEYS_API_KEY,
baseUrl: fastify.config.HANKO_PASSKEYS_LOGIN_BASE_URL,
});

fastify.decorate('passkeysApi', passkeysApi);

const verify: (options?: AuthorizeOptions) => preHandlerHookHandler =
(options = {mustBeAuthenticated: true}) =>
async req => {
const token = req.headers.authorization
?.split('Bearer ')[1]
.split('.')[1] as string;
const claims = JSON.parse(atob(token));
const userId = claims.sub;

const user = await fastify.prisma.user.findFirst({
where: {
id: userId,
},
});

if (user) {
req.appUser = user;
} else if (options.mustBeAuthenticated) {
throw fastify.httpErrors.unauthorized();
}
};

fastify.decorate('verifyHankoPasskey', verify);
};

export default passkeysPlugin;

declare module 'fastify' {
interface FastifyInstance {
passkeysApi: ReturnType<typeof tenant>;

verifyHankoPasskey: (options?: AuthorizeOptions) => preHandlerHookHandler;
}
}
12 changes: 12 additions & 0 deletions apps/api/src/common/auth/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {FastifyPluginAsync} from 'fastify';
import {User} from '@codeimage/prisma-models';

export const appUserPlugin: FastifyPluginAsync = async fastify => {
fastify.decorateRequest('appUser', null);
};

declare module 'fastify' {
interface FastifyRequest {
appUser: User;
}
}
26 changes: 22 additions & 4 deletions apps/api/src/common/typebox/nullable.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
import {SchemaOptions, TSchema, Type} from '@sinclair/typebox';
import {
SchemaOptions,
TNull,
TOptional,
TSchema,
TUnion,
Type,
} from '@sinclair/typebox';

export const Nullable = <T extends TSchema>(tType: T, optional = true) => {
export function Nullable<T extends TSchema>(
tType: T,
optional?: true,
): TOptional<TUnion<[T, TNull]>>;
export function Nullable<T extends TSchema>(
tType: T,
optional?: false,
): TUnion<[T, TNull]>;
export function Nullable<T extends TSchema>(
tType: T,
optional?: boolean,
): TOptional<TUnion<[T, TNull]>> | TUnion<[T, TNull]> {
const options: SchemaOptions | undefined = Reflect.has(tType, 'default')
? {default: tType.default}
: undefined;

const resolvedType = Type.Union([tType, Type.Null()], options);

if (optional) {
if (optional === undefined || optional) {
return Type.Optional(resolvedType);
}
return resolvedType;
};
}
6 changes: 3 additions & 3 deletions apps/api/src/modules/project/handlers/project.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Project, User} from '@codeimage/prisma-models';
import {HttpError, HttpErrors} from '@fastify/sensible/lib/httpError.js';
import {HttpErrors} from '@fastify/sensible/lib/httpError.js';
import {createProjectRequestMapper} from '../mapper/create-project-mapper.js';
import {createCompleteProjectGetByIdResponseMapper} from '../mapper/get-project-by-id-mapper.js';
import {ProjectRepository} from '../repository/index.js';
Expand Down Expand Up @@ -89,7 +89,7 @@ export function makeProjectService(
try {
const project = await repository.findById(projectId);
if (!project) {
throw {name: 'NotFoundError'} as HttpError;
throw {name: 'NotFoundError'} as HttpErrors['HttpError'];
}
return this.createNewProject(user.id, {
name: newName ?? project.name,
Expand All @@ -99,7 +99,7 @@ export function makeProjectService(
terminal: project.terminal,
});
} catch (e) {
const error = e as HttpError;
const error = e as HttpErrors['HttpError'];
if (error && error.name === 'NotFoundError') {
throw httpErrors.notFound(
`Cannot clone project with id ${projectId} since it does not exists`,
Expand Down
20 changes: 20 additions & 0 deletions apps/api/src/plugins/auth0Management.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {ManagementClient} from 'auth0';
import fp from 'fastify-plugin';

export default fp(async fastify => {
fastify.decorate(
'auth0Management',
new ManagementClient({
domain: fastify.config.DOMAIN_AUTH0!,
audience: fastify.config.AUDIENCE_AUTH0!,
clientId: fastify.config.CLIENT_ID_AUTH0!,
clientSecret: fastify.config.CLIENT_SECRET_AUTH0!,
}),
);
});

declare module 'fastify' {
interface FastifyInstance {
auth0Management: ManagementClient;
}
}
Loading
Loading