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

Web2 auth #2442

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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 demos/web2-auth/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Internet Identity</title>
<link rel="shortcut icon" href="/favicon.ico" />
<script type="module" src="src/index.ts"></script>
</head>
<body>
<main id="pageContent" aria-live="polite">
<aside style="max-width: 40rem; margin: 0 auto; text-align: center">
<output style="display: block" data-output-id="is-authed" disabled
>You are not authed</output
>
<button data-button-id="authenticate" disabled>Authenticate</button>
</aside>
</main>
</body>
</html>
18 changes: 18 additions & 0 deletions demos/web2-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "web2-auth",
"version": "1.0.0",
"description": "",
"type": "module",
"dependencies": {
"@dfinity/sig-verifier-js": "*"
},
"devDependencies": {
"vite": "*"
},
"scripts": {
"check": "tsc --noEmit",
"vite": "NODE_OPTIONS='--experimental-wasm-modules' vite --config ./vite.config.ts"
},
"author": "",
"license": "ISC"
}
127 changes: 127 additions & 0 deletions demos/web2-auth/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// TODO: deduplicate

import type { SignIdentity, Signature } from "@dfinity/agent";
import {
Delegation,
DelegationChain,
DelegationIdentity,
SignedDelegation,
} from "@dfinity/identity";
import { Principal } from "@dfinity/principal";

// The type of response from II as per the spec
interface AuthResponseSuccess {
kind: "authorize-client-success";
delegations: {
delegation: {
pubkey: Uint8Array;
expiration: bigint;
targets?: Principal[];
};
signature: Uint8Array;
}[];
userPublicKey: Uint8Array;
}

// Perform a sign in to II using parameters set in this app
export const authWithII = async ({
url: url_,
maxTimeToLive,
derivationOrigin,
sessionPublicKey,
}: {
url: string;
maxTimeToLive?: bigint;
derivationOrigin?: string;
sessionPublicKey: Uint8Array;
}): Promise<DelegationIdentity> => {
// Figure out the II URL to use
const iiUrl = new URL(url_);
iiUrl.hash = "#authorize";

// Open an II window and kickstart the flow
const win = window.open(iiUrl, "ii-window");
if (win === null) {
throw new Error(`Could not open window for '${iiUrl}'`);
}

// Wait for II to say it's ready
const evnt = await new Promise<MessageEvent>((resolve) => {
const readyHandler = (e: MessageEvent) => {

Check warning

Code scanning / CodeQL

Missing origin verification in `postMessage` handler Medium

Postmessage handler has no origin check.
window.removeEventListener("message", readyHandler);
resolve(e);
};
window.addEventListener("message", readyHandler);
});

if (evnt.data.kind !== "authorize-ready") {
throw new Error("Bad message from II window: " + JSON.stringify(evnt));
}

// Send the request to II
const request = {
kind: "authorize-client",
sessionPublicKey,
maxTimeToLive,
derivationOrigin,
};

win.postMessage(request, iiUrl.origin);

// Wait for the II response and update the local state
const response = await new Promise<MessageEvent>((resolve) => {
const responseHandler = (e: MessageEvent) => {

Check warning

Code scanning / CodeQL

Missing origin verification in `postMessage` handler Medium

Postmessage handler has no origin check.
window.removeEventListener("message", responseHandler);
win.close();
resolve(e);
};
window.addEventListener("message", responseHandler);
});

const message = response.data;
if (message.kind !== "authorize-client-success") {
throw new Error("Bad reply: " + JSON.stringify(message));
}

return message;
};

// Read delegations the delegations from the response
const identityFromResponse = ({
sessionIdentity,
response,
}: {
sessionIdentity: SignIdentity;
response: AuthResponseSuccess;
}): DelegationIdentity => {
const delegations = response.delegations.map(extractDelegation);

const delegationChain = DelegationChain.fromDelegations(
delegations,
response.userPublicKey.buffer
);

const identity = DelegationIdentity.fromDelegation(
sessionIdentity,
delegationChain
);

return identity;
};

// Infer the type of an array's elements
type ElementOf<Arr> = Arr extends readonly (infer ElementOf)[]
? ElementOf
: "argument is not an array";

export const extractDelegation = (
signedDelegation: ElementOf<AuthResponseSuccess["delegations"]>
): SignedDelegation => ({
delegation: new Delegation(
signedDelegation.delegation.pubkey,
signedDelegation.delegation.expiration,
signedDelegation.delegation.targets
),
signature: signedDelegation.signature
.buffer as Signature /* brand type for agent-js */,
});
50 changes: 50 additions & 0 deletions demos/web2-auth/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { authWithII } from "./auth";

const button = document.querySelector(
"[data-button-id=authenticate]"
)! as HTMLButtonElement;
const isAuthed = document.querySelector(
"[data-output-id=is-authed]"
)! as HTMLOutputElement;

export const uint8ArrayToHexString = (bytes: Uint8Array | number[]) => {
if (!(bytes instanceof Uint8Array)) {
bytes = Uint8Array.from(bytes);
}
return bytes.reduce(
(str, byte) => str + byte.toString(16).padStart(2, "0"),
""
);
};

button.addEventListener("click", async () => {
const resp = await fetch("/challenge");
const obj: { challenge: string } = await resp.json();
const challenge = obj.challenge;
const delegationIdentity = await authWithII({
// The url needs to be aligned with the root key in the backend
// url: "http://internet_identity.localhost:5173",
url: "https://jqajs-xiaaa-aaaad-aab5q-cai.ic0.app/",
sessionPublicKey: new Uint8Array(Buffer.from(challenge, "base64")),
});
const data = { challenge, delegationIdentity };
await fetch("/verify", {
method: "POST",
body: JSON.stringify(data, (_, v) => {
if (typeof v === "bigint") {
// We need to expiration date to be hex string.
return v.toString(16);
}
if (v instanceof Uint8Array) {
// We need the keys to be hex strings.
return uint8ArrayToHexString(v);
}
return v;
}),
headers: new Headers({
"Content-Type": "application/json",
}),
});
});

button.disabled = false;
7 changes: 7 additions & 0 deletions demos/web2-auth/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"include": ["vite.config.ts", "./src"],
"compilerOptions": {
"composite": true
}
}
131 changes: 131 additions & 0 deletions demos/web2-auth/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { validateDelegationAndGetPrincipal } from "@dfinity/sig-verifier-js/sig_verifier_js";
import { IncomingMessage, ServerResponse } from "http";
import type { Plugin, ViteDevServer } from "vite";
import { defineConfig } from "vite";

export async function createChallenge(): Promise<string> {
// TODO: generate random challenge, store & add expiry
return "YSBjaGFsbGVuZ2UsIGkuZS4gYSBzdHJpbmcgb2YgYXQgbGVhc3QgMzIgYnl0ZXM=";
}

type Delegation = {
delegation: {
pubkey: string;
expiration: string;
};
signature: string;
};

type VerifyData = {
challenge: string;
authMethod: string;
delegationIdentity: {
kind: string;
delegations: Delegation[];
userPublicKey: string;
};
};

const ROOT_PUBLIC_KEY_RAW = new Uint8Array([
0x81, 0x4c, 0x0e, 0x6e, 0xc7, 0x1f, 0xab, 0x58, 0x3b, 0x08, 0xbd, 0x81, 0x37,
0x3c, 0x25, 0x5c, 0x3c, 0x37, 0x1b, 0x2e, 0x84, 0x86, 0x3c, 0x98, 0xa4, 0xf1,
0xe0, 0x8b, 0x74, 0x23, 0x5d, 0x14, 0xfb, 0x5d, 0x9c, 0x0c, 0xd5, 0x46, 0xd9,
0x68, 0x5f, 0x91, 0x3a, 0x0c, 0x0b, 0x2c, 0xc5, 0x34, 0x15, 0x83, 0xbf, 0x4b,
0x43, 0x92, 0xe4, 0x67, 0xdb, 0x96, 0xd6, 0x5b, 0x9b, 0xb4, 0xcb, 0x71, 0x71,
0x12, 0xf8, 0x47, 0x2e, 0x0d, 0x5a, 0x4d, 0x14, 0x50, 0x5f, 0xfd, 0x74, 0x84,
0xb0, 0x12, 0x91, 0x09, 0x1c, 0x5f, 0x87, 0xb9, 0x88, 0x83, 0x46, 0x3f, 0x98,
0x09, 0x1a, 0x0b, 0xaa, 0xae,
]);

export function verifyChallenge(data: VerifyData): string | undefined {
try {
const delegationChain = {
delegations: data.delegationIdentity.delegations,
publicKey: data.delegationIdentity.userPublicKey,
};
const currentTimeNanoSeconds = process.hrtime.bigint();
const res = validateDelegationAndGetPrincipal(
Uint8Array.from(Buffer.from(data.challenge, "base64")),
JSON.stringify(delegationChain),
currentTimeNanoSeconds,
"jqajs-xiaaa-aaaad-aab5q-cai",
ROOT_PUBLIC_KEY_RAW
);

return res;
} catch (e) {
console.error(e);
return undefined;
}
}

const handleChallenge = async (req: IncomingMessage, res: ServerResponse) => {
const challenge = await createChallenge();
res.statusCode = 200;
res.end(JSON.stringify({ challenge }));
};

const handleVerify = async (req: RequestWithBody, res: ServerResponse) => {
res.statusCode = 200;
const principal = verifyChallenge(req.body);
console.log("principal", principal);
// TODO: add cookie here on success
res.end(JSON.stringify({ status: "ok" }));
};

// Extend IncomingMessage to include body
interface RequestWithBody extends IncomingMessage {
body?: any;
}

const bodyParserPlugin = (): Plugin => ({
name: "body-parser",
configureServer(server) {
server.middlewares.use(
async (req: RequestWithBody, res: ServerResponse, next) => {
// Only parse JSON bodies and only for POST requests
if (
req.method === "POST" &&
req.headers["content-type"] === "application/json"
) {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString(); // convert Buffer to string
});
req.on("end", () => {
try {
req.body = JSON.parse(body);
} catch (e: unknown) {
res.statusCode = 400;
return res.end("Error parsing JSON body");
}
next();
});
} else {
next();
}
}
);
},
});

const backendPlugin = (): Plugin => ({
name: "backend-plugin",
configureServer(server: ViteDevServer) {
server.middlewares.use(async (req, res, next) => {
if (req.url === "/challenge") {
return handleChallenge(req, res);
}
if (req.url === "/verify") {
return handleVerify(req, res);
}

return next();
});
},
});

export default defineConfig({
plugins: [bodyParserPlugin(), backendPlugin()],
server: { port: 5178 },
});
Loading
Loading