Skip to content

Commit

Permalink
made minor corrections
Browse files Browse the repository at this point in the history
  • Loading branch information
timonson committed Sep 14, 2019
1 parent ac098c4 commit 3309873
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 28 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { encode, decode } from "https://deno.land/std/strings/mod.ts"
import { makeJwt } from "../create.ts"
import { validateJwt } from "../validate.ts"

const key: string = "abc"
const key = "abc"
const claims = {
iss: "joe",
exp: 1300819380,
Expand All @@ -27,14 +27,15 @@ const headerObject = {
typ: "JWT",
}
const s = serve("0.0.0.0:8000")

;(async function main() {
for await (const req of s) {
if (req.method === "GET") {
const jwt = makeJwt(headerObject, claims, key)
req.respond({ body: encode(jwt) })
} else {
const requestBody = decode(await req.body())
validateJwt(requestBody, key)
validateJwt(requestBody, key, false)
? req.respond({ body: encode("Valid JWT\n") })
: req.respond({ status: 401, body: encode("Invalid JWT\n") })
}
Expand Down
17 changes: 8 additions & 9 deletions create.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import * as base64 from "https://denopkg.com/chiefbiiko/base64/mod.ts"
import { hmac } from "https://denopkg.com/chiefbiiko/hmac/mod.ts"

interface Claims {
iss?: string
sub?: string
Expand All @@ -15,10 +18,6 @@ interface Jose {
[key: string]: any
}

// §5.1 (JWS) Compute the encoded payload value BASE64URL(JWS Payload)
import * as base64 from "https://denopkg.com/chiefbiiko/base64/mod.ts"
import { hmac } from "https://denopkg.com/chiefbiiko/hmac/mod.ts"

function convertBase64urlFromBase64(base64: string): string {
return base64
.replace(/=/g, "")
Expand All @@ -33,17 +32,17 @@ function makeB64urlEncodedString(
if (typeof input === "object")
return convertBase64urlFromBase64(base64.fromUint8Array(input))
const makeTypedArray =
inputEncoding === "hex" ? convertHexToTypedArray : convertUtf8ToTypedArray
inputEncoding === "hex" ? convertHexToUint8Array : convertUtf8ToTypedArray
return convertBase64urlFromBase64(base64.fromUint8Array(makeTypedArray(input)))
}

function convertHexToTypedArray(hex: string): Uint8Array {
function convertHexToUint8Array(hex: string): Uint8Array {
if (typeof hex !== "string") throw new TypeError("Expected input to be a string")
if (hex.length % 2 !== 0) throw new RangeError("String is not an even number long")
if (hex.length % 2 !== 0)
throw new RangeError("String length is not an even number")
var view = new Uint8Array(hex.length / 2)
for (var i = 0; i < hex.length; i += 2)
view[i / 2] = parseInt(hex.substring(i, i + 2), 16)

return view
}

Expand All @@ -70,7 +69,7 @@ function makeSignature(
): string | Uint8Array {
if (alg === "HS256") return makeHmacSignature("sha256", key, msg)
if (alg === "HS512") return makeHmacSignature("sha512", key, msg)
throw new Error("no matching algorithm")
throw new RangeError("no matching algorithm")
}

function makeJwt(headerObject: Jose, claims: Claims, key: string): string {
Expand Down
8 changes: 2 additions & 6 deletions examples/mini_example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@ const s = serve("0.0.0.0:8000")
for await (const req of s) {
if (req.method === "GET")
req.respond({
status: 200,
body: encode(makeJwt({ typ: "JWT", alg: "HS512" }, { iss: "joe" }, "abc")),
})
else
validateJwt(decode(await req.body()), "abc")
? req.respond({
status: 200,
body: encode("Valid JWT\n"),
})
validateJwt(decode(await req.body()), "abc", false)
? req.respond({ body: encode("Valid JWT\n") })
: req.respond({ status: 401, body: encode("Invalid JWT\n") })
}
})()
4 changes: 2 additions & 2 deletions examples/readme_example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { encode, decode } from "https://deno.land/std/strings/mod.ts"
import { makeJwt } from "../create.ts"
import { validateJwt } from "../validate.ts"

const key: string = "abc"
const key = "abc"
const claims = {
iss: "joe",
exp: 1300819380,
Expand All @@ -20,7 +20,7 @@ const s = serve("0.0.0.0:8000")
req.respond({ body: encode(jwt) })
} else {
const requestBody = decode(await req.body())
validateJwt(requestBody, key)
validateJwt(requestBody, key, false)
? req.respond({ body: encode("Valid JWT\n") })
: req.respond({ status: 401, body: encode("Invalid JWT\n") })
}
Expand Down
14 changes: 5 additions & 9 deletions validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ interface CritHandlers {
*/
function checkAlgHeaderParameter(joseHeader: Jose, algorithms: string[]): string {
const algorithm = algorithms.find(el => el === joseHeader.alg)
if (!algorithm) throw new Error("no or no matching algorithm in the header")

if (!algorithm) throw new RangeError("no or no matching algorithm in the header")
return algorithm
}

Expand Down Expand Up @@ -51,7 +50,6 @@ function checkCritHeaderParameter(
.map(str => critHandlers[str])
if (activatedHandlers.length == 0)
throw new Error("critical header extensions are not understood or supported")

return Promise.all(activatedHandlers.map(handler => handler(joseHeader)))
}

Expand All @@ -60,13 +58,12 @@ function handleJoseHeader(
algorithms: string[],
critHandlers: CritHandlers
): [string, Promise<any[]>] {
if (typeof joseHeader !== "object") throw new Error("the json header is no object")
if (typeof joseHeader !== "object") throw new TypeError("the json header is no object")
const algorithm: string = checkAlgHeaderParameter(joseHeader, algorithms)
const criticalResults: Promise<any[]> =
"crit" in joseHeader
? checkCritHeaderParameter(joseHeader, critHandlers)
: Promise.resolve([])

return [algorithm, criticalResults]
}

Expand All @@ -77,7 +74,7 @@ function addPaddingCharactersToBase64url(base64url: string): string {
return base64url
}

function uint8ArrayToHex(uint8Array: Uint8Array): string {
function convertUint8ArrayToHex(uint8Array: Uint8Array): string {
return Array.from(uint8Array)
.map(x => ("00" + x.toString(16)).slice(-2))
.join("")
Expand All @@ -89,15 +86,15 @@ function parseAndDecodeJwt(jwt: string): any[] {
.map(str => addPaddingCharactersToBase64url(str))
.map((str, index) =>
index === 2
? uint8ArrayToHex(base64.toUint8Array(str))
? convertUint8ArrayToHex(base64.toUint8Array(str))
: JSON.parse(new TextDecoder().decode(base64.toUint8Array(str)))
)
}

function validateJwt(
jwt: string,
key: string,
throwErrors: boolean = false,
throwErrors: boolean = true,
criticalHandlers: CritHandlers = {}
) {
try {
Expand All @@ -114,7 +111,6 @@ function validateJwt(
} catch (err) {
err.message = `Invalid JWT: ${err.message}`
if (throwErrors) throw err
else console.log(err)
}
}

Expand Down

0 comments on commit 3309873

Please sign in to comment.