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

fix(etag): change where to check for crypto #3916

Open
wants to merge 5 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
2 changes: 1 addition & 1 deletion src/middleware/etag/digest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const generateDigest = async (
stream: ReadableStream<Uint8Array> | null,
generator: (body: Uint8Array) => ArrayBuffer | Promise<ArrayBuffer>
): Promise<string | null> => {
if (!stream || !crypto || !crypto.subtle) {
if (!stream) {
return null
}

Expand Down
31 changes: 22 additions & 9 deletions src/middleware/etag/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ function etagMatches(etag: string, ifNoneMatch: string | null) {
return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).indexOf(etag) > -1
}

function initializeGenerator(
generator?: ETagOptions['generateDigest']
): ETagOptions['generateDigest'] | undefined {
if (!generator) {
if (crypto && crypto.subtle) {
generator = (body: Uint8Array) =>
crypto.subtle.digest(
{
name: 'SHA-1',
},
body
)
}
}

return generator
}

/**
* ETag Middleware for Hono.
*
Expand All @@ -57,15 +75,7 @@ function etagMatches(etag: string, ifNoneMatch: string | null) {
export const etag = (options?: ETagOptions): MiddlewareHandler => {
const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS
const weak = options?.weak ?? false
const generator =
options?.generateDigest ??
((body: Uint8Array) =>
crypto.subtle.digest(
{
name: 'SHA-1',
},
body
))
const generator = initializeGenerator(options?.generateDigest)

return async function etag(c, next) {
const ifNoneMatch = c.req.header('If-None-Match') ?? null
Expand All @@ -76,6 +86,9 @@ export const etag = (options?: ETagOptions): MiddlewareHandler => {
let etag = res.headers.get('ETag')

if (!etag) {
if (!generator) {
return
}
const hash = await generateDigest(res.clone().body, generator)
if (hash === null) {
return
Expand Down
Loading