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

Add MyGovId Mock service to Logto #55

Merged
merged 5 commits into from
Jul 3, 2024
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
21 changes: 21 additions & 0 deletions mygovid-mock-service/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"rules": {
"no-redeclare": "off",
"no-unused-vars": "off"
},
"env": {
"browser": true,
"node": true
},
"ignorePatterns": ["dist"]
}
2 changes: 2 additions & 0 deletions mygovid-mock-service/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.tap
44 changes: 44 additions & 0 deletions mygovid-mock-service/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "mygovid-mock-service",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "TAP_RCFILE=tap.yml tap",
"start": "node dist/index.js",
peschina marked this conversation as resolved.
Show resolved Hide resolved
"dev": "nodemon | pino-pretty",
"lint": "eslint . --ext .ts",
"build": "echo Build script for the MyGovId mock service not needed so far"
},
"nodemonConfig": {
"ext": "ts,json",
"exec": "node --import tsx src/index.ts"
},
"type": "module",
"author": "",
"license": "ISC",
"dependencies": {
"@fastify/cookie": "^9.3.1",
"@fastify/formbody": "^7.4.0",
"@fastify/sensible": "^5.5.0",
"@fastify/type-provider-typebox": "^4.0.0",
"@sinclair/typebox": "^0.32.16",
"fastify": "^4.26.2",
"fastify-plugin": "^4.5.1",
"jose": "^5.2.4"
},
"devDependencies": {
"@types/node": "^20.11.28",
"@typescript-eslint/eslint-plugin": "^7.5.0",
"@typescript-eslint/parser": "^7.5.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"pino-pretty": "^11.0.0",
"prettier": "^3.2.5",
"tap": "^18.8.0",
"ts-node": "^10.9.2",
"tsx": "^4.7.1",
"typescript": "^5.4.2"
}
}
21 changes: 21 additions & 0 deletions mygovid-mock-service/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import fastify, { FastifyServerOptions } from "fastify";
import routes from "./routes/index.js";
import { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import sensible from "@fastify/sensible";

export async function build(opts?: FastifyServerOptions) {
const app = fastify(opts).withTypeProvider<TypeBoxTypeProvider>();

app.register(import("@fastify/cookie"), {
hook: "onRequest", // set to false to disable cookie autoparsing or set autoparsing on any of the following hooks: 'onRequest', 'preParsing', 'preHandler', 'preValidation'. default: 'onRequest'
parseOptions: {}, // options for parsing cookies
});

app.register(import("@fastify/formbody"));

app.register(routes);

app.register(sensible);

return app;
}
13 changes: 13 additions & 0 deletions mygovid-mock-service/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { build } from "./app.js";

const app = await build();

app.listen({ host: "0.0.0.0", port: 4005 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`MyGovId Mock Service listening at ${address}`);
});

await app.ready();
6 changes: 6 additions & 0 deletions mygovid-mock-service/src/routes/healthcheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { FastifyInstance } from "fastify";
export default async function healthCheck(app: FastifyInstance) {
app.get("/health", async () => {
return { status: "ok" };
});
}
8 changes: 8 additions & 0 deletions mygovid-mock-service/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FastifyInstance } from "fastify";
import healthCheck from "./healthcheck.js";
import logto from "./logto/index.js";

export default async function routes(app: FastifyInstance) {
app.register(healthCheck);
app.register(logto, { prefix: "/logto/mock" });
}
186 changes: 186 additions & 0 deletions mygovid-mock-service/src/routes/logto/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { FastifyInstance } from "fastify";
import fs from "fs";
import path, { dirname } from "path";
import { exportJWK } from "jose";
import { fileURLToPath } from "url";
import { Type } from "@sinclair/typebox";
import {
createMockSignedJwt,
getPublicKey,
streamToString,
} from "./utils/index.js";
import { HttpError } from "../../types/httpErrors.js";

const __dirname = dirname(fileURLToPath(import.meta.url));

export default async function login(app: FastifyInstance) {
app.get<{
Querystring: {
response_type: string;
client_id: string;
redirect_uri: string;
state: string;
nonce: string;
scope: string;
};
}>(
"/auth",
{
schema: {
tags: ["Mock"],
querystring: {
response_type: Type.String(),
client_id: Type.String(),
redirect_uri: Type.String(),
state: Type.String(),
nonce: Type.String(),
scope: Type.String(),
},
response: { 200: Type.String(), 500: HttpError },
},
},
async (request, reply) => {
const { redirect_uri, state } = request.query;

const stream = fs.createReadStream(
path.join(__dirname, "..", "static", "mock-login.html")
);

const result = (await streamToString(stream))
.replace("%REDIRECT_URL%", redirect_uri)
.replace("%STATE%", state);
return reply.type("text/html").send(result);
}
);

app.post<{
Body: {
password: string;
firstName: string;
lastName: string;
email: string;
redirect_url: string;
state: string;
};
}>("/login", async (request, reply) => {
const { password, firstName, lastName, email, redirect_url, state } =
request.body;

if (password !== "123")
reply.redirect(
`/logto/mock/auth?redirect_uri=${redirect_url}&state=${state}`
);

const id_token = await createMockSignedJwt(
{ firstName, lastName, email },
request.headers.origin as unknown as string
);

return reply.redirect(`${redirect_url}?code=${id_token}&state=${state}`);
});

app.post<{
Body: {
code: string;
grant_type: string;
redirect_uri: string;
client_id: string;
client_secret: string;
};
Reply: {
id_token: string;
access_token: string;
token_type: string;
not_before: number;
expires_in: number;
expires_on: number;
id_token_expires_in: number;
profile_info: string;
scope: string;
};
}>(
"/token",
{
schema: {
tags: ["Mock"],
body: Type.Object({
code: Type.String(),
grant_type: Type.String(),
redirect_uri: Type.String(),
client_id: Type.String(),
client_secret: Type.String(),
}),
response: {
200: Type.Object({
id_token: Type.String(),
access_token: Type.String(),
token_type: Type.String(),
not_before: Type.Number(),
expires_in: Type.Number(),
expires_on: Type.Number(),
id_token_expires_in: Type.Number(),
profile_info: Type.String(),
scope: Type.String(),
}),
500: HttpError,
},
},
},
async (request, _) => {
const id_token = request.body.code;
return {
id_token,
access_token: id_token,
token_type: "Bearer",
not_before: Date.now() - 5000,
expires_in: 1800,
expires_on: Date.now() - 5000 + 1800,
id_token_expires_in: 1800,
profile_info:
"eyJ2ZXIiOiIxLjAiLCJ0aWQiOiI4OTc5MmE2ZC0xZWE0LTQxMjYtOTRkZi1hNzFkMjkyZGViYzciLCJzdWIiOm51bGwsIm5hbWUiOm51bGwsInByZWZlcnJlZF91c2VybmFtZSI6bnVsbCwiaWRwIjpudWxsfQ",
scope: "openid",
};
}
);

app.get<{
Reply: {
keys: {
kid: string;
use: string;
kty?: string;
n?: string;
e?: string;
}[];
};
}>(
"/keys",
{
schema: {
tags: ["Mock"],
response: {
200: Type.Object({
keys: Type.Array(
Type.Object({
kid: Type.String(),
use: Type.String(),
kty: Type.Optional(Type.String()),
n: Type.Optional(Type.String()),
e: Type.Optional(Type.String()),
})
),
}),
500: HttpError,
},
},
},
async (request, reply) => {
const publicKey = await getPublicKey();
const { kty, n, e } = await exportJWK(publicKey);

return {
keys: [{ kid: "signingkey.mygovid.v1", use: "sig", kty, n, e }],
};
}
);
}
81 changes: 81 additions & 0 deletions mygovid-mock-service/src/routes/logto/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import fs from "fs";
import crypto from "crypto";
import { importPKCS8, importSPKI, SignJWT } from "jose";

const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});

export const streamToString = (stream: fs.ReadStream): Promise<string> => {
const chunks: Buffer[] = [];
return new Promise((resolve, reject) => {
stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
stream.on("error", (err) => reject(err));
stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
};

const getRandomPhoneNumber = () =>
`+353${Math.floor(Math.random() * 9000000000) + 1000000000}`;

const getRandomString = () => crypto.randomBytes(20).toString("hex");

export const createMockSignedJwt = async (
user: {
firstName: string;
lastName: string;
email: string;
},
origin: string,
) => {
const body = {
ver: "1.0",
sub: getRandomString(),
auth_time: Date.now(),
email: user.email,
oid: getRandomString(),
AlternateIds: "",
BirthDate: "13/06/1941",
PublicServiceNumber: "0111019P",
LastJourney: "Login",
mobile: getRandomPhoneNumber(),
DSPOnlineLevel: "0",
DSPOnlineLevelStatic: "0",
givenName: user.firstName,
surname: user.lastName,
CustomerId: "532",
AcceptedPrivacyTerms: true,
AcceptedPrivacyTermsVersionNumber: "7",
SMS2FAEnabled: false,
AcceptedPrivacyTermsDateTime: 1715582120,
firstName: user.firstName,
lastName: user.lastName,
currentCulture: "en",
trustFrameworkPolicy: "B2C_1A_MyGovID_signin-v5-PARTIAL2",
CorrelationId: getRandomString(),
nbf: 1716804749,
};

const alg = "RS256";
const key = await importPKCS8(privateKey, alg);

const jwt = await new SignJWT(body)
.setProtectedHeader({ alg })
.setAudience("mock_client_id")
.setIssuedAt()
.setIssuer(origin)
.setExpirationTime("2h")
.sign(key);

return jwt;
};

export const getPublicKey = async () => await importSPKI(publicKey, "RS256");
Loading