Compare commits

...

88 Commits

Author SHA1 Message Date
Tim Barley c6a52adabc
Merge 05e09f6a4b into 6c36f525f9 2025-04-11 10:57:05 -04:00
github-actions[bot] 6c36f525f9
Version Packages (#1123)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-11 16:23:32 +09:00
Yusuke Wada 944f1989f5
fix(react-renderer): tweak dynamic importing `renderToReadableStream` (#1122)
* fix(react-renderer): tweak dynamic importing `renderToReadableStream`

* changeset
2025-04-11 16:19:43 +09:00
github-actions[bot] a1fcb554ef
Version Packages (#1121)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-11 07:46:10 +09:00
Yusuke Wada 684ae9a21d
feat(react-renderer): use React v19 and specify `react-dom/server.edge` for `renderToReadableStream` (#1119)
* feat(react-renderer): use React v19 and specify `react-dom/server.edge` for `renderToReadableStream`

* changeset
2025-04-11 07:43:03 +09:00
Tim Barley 05e09f6a4b
Merge branch 'main' into main 2025-04-09 10:31:04 -04:00
Jonathan Haines 595fa28485 ci(release): yarn config set npmAuthToken (#1117) 2025-04-09 09:28:14 -04:00
chimame 3e13eefc67 chore(conform-validator): Change conform valibot adapter to official library (#1114) 2025-04-09 09:28:14 -04:00
Jonathan Haines 95b87e5b5a ci(release): restore build during release (#1116) 2025-04-09 09:28:14 -04:00
github-actions[bot] b4ceb3a82c Version Packages (#1115)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Jonathan Haines e4c5c3d07f fix(zod-openapi): republish without workspace reference (#1111)
fixes #1109
2025-04-09 09:28:14 -04:00
github-actions[bot] 95f746f964 Version Packages (#1108)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Jonathan Haines 17df8a47c8 feat(eslint-config): enable linting with type information (#1098) 2025-04-09 09:28:14 -04:00
github-actions[bot] dc917efec0 Version Packages (#1107)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Yusuke Wada 59559961bb fix(zod-openapi): infer Env correctly if the middleware is `[]` (#1106)
* fix(zod-openapi): infer Env correctly if the middleware is `[]`

* add changeset
2025-04-09 09:28:14 -04:00
github-actions[bot] b09d7bbc2c Version Packages (#1101)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
liquidleif 509ead8934 fix(oauth-providers): Update twitter authorization url (#1099)
Closes #1100

* Update twitter authorization url

The twitter authorization URL is outdated.

* add a changeset
2025-04-09 09:28:14 -04:00
Jonathan Haines 741e9d49ff build: typescript project references (#1077)
* build: typescript project references

* chore: remove duplicate keys
2025-04-09 09:28:14 -04:00
github-actions[bot] 7e2652d297 Version Packages (#1095)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Shotaro Nakamura d61e8a66ea fix(node-ws): adapter shouldn't send buffer as a event (#1094)
* fix(node-ws): adapter shouldn't send buffer as a event

* chore: changeset
2025-04-09 09:28:14 -04:00
Jonathan Haines 3b5eb36b4f chore(dev-deps): upgrade to hono v4 (#1092)
* chore(dev-deps): upgrade to hono v4

* chore(zod-openapi): build workspace dependencies

* chore(trpc-server): ignore null body type
2025-04-09 09:28:14 -04:00
Jonathan Haines 6edd7bc1ce ci: run eslint in each workflow (#1083) 2025-04-09 09:28:14 -04:00
Yann Normand 226f4e7b9b docs:(zod-openapi): add note about app.route (#1088) 2025-04-09 09:28:14 -04:00
github-actions[bot] 77fce3c040 Version Packages (#1087)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Yusuke Wada 8810eccff2 chore(eslint-config): add missing changeset (#1085) 2025-04-09 09:28:14 -04:00
Yusuke Wada db5207c509 fix(eslint-config): add spread to `tseslint.configs.recommended` (#1084) 2025-04-09 09:28:14 -04:00
github-actions[bot] c9dfd2b5a3 Version Packages (#1082)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:28:14 -04:00
Yusuke Wada e2e4f6aa52 fix(sentry): fix the type error (#1081) 2025-04-09 09:28:14 -04:00
Yusuke Wada 5f3a3fa29c fix(typebox-validator): export modules correctly (#1080) 2025-04-09 09:28:14 -04:00
Yusuke Wada 76f00959c6 refactor(typebox-validator): fix the type error (#1079) 2025-04-09 09:28:14 -04:00
Yusuke Wada 70834f9f70 refactor(zod-openapi): fix type errors (#1078)
* refactor(zod-openapi): fix type errors

* fix types
2025-04-09 09:28:14 -04:00
Aditya Mathur 7cba581041 feat: updated @hono/eslint-config package (#1031)
* chore(eslint-config): update dependencies and improve configuration

* chore(eslint-config): replace @typescript-eslint packages with typescript-eslint

* chore: completed changes suggested by @BarryThePenguin

* chore: updated the repo eslint config

* chore: updated the lockfile

* feat: added ci and minor changes

* chore: updated the eslint version in package.json

* chore: updated the lockfile

* add changeset

* `@ryoppippi/unplugin-typia` as devDependencies

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
2025-04-09 09:28:14 -04:00
Jonathan Haines 21afe41dec ci: use node v20 (#1076) 2025-04-09 09:28:14 -04:00
Jonathan Haines 5b1e8ae2e5 test: move tests to src directory (#1075)
* test(react-renderer): move tests to src directory

* test: move tests to src directory

* test: ensure vitest-pool-workers is installed at the root
2025-04-09 09:28:14 -04:00
Jonathan Haines e31cd008aa build(react-renderer): lint published package (#1058)
Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
2025-04-09 09:26:27 -04:00
Jonathan Haines 7498fbcff1 build(sentry): lint published package (#1059)
Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
2025-04-09 09:26:27 -04:00
Jonathan Haines 4db6cce55d build(react-compat): lint published package (#1060) 2025-04-09 09:26:27 -04:00
Jonathan Haines 1924c630a8 build(standard-validator): lint published package (#1061)
Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
2025-04-09 09:26:27 -04:00
Yusuke Wada 2e6c051b11 chore: update the lockfile (#1074) 2025-04-09 09:26:27 -04:00
Jonathan Haines 369680c298 build(swagger-ui): lint published package (#1063) 2025-04-09 09:26:27 -04:00
Jonathan Haines ddba7cf343 build(valibot-validator): lint published package (#1068) 2025-04-09 09:26:27 -04:00
Jonathan Haines 8557f3bc0b build(typia-validator): lint published package (#1067) 2025-04-09 09:26:27 -04:00
Yusuke Wada 008ce5eb83 chore: update the lockfile (#1073) 2025-04-09 09:26:27 -04:00
Jonathan Haines b1d32f5783 build(zod-validator): lint published package (#1070) 2025-04-09 09:26:27 -04:00
Jonathan Haines 5a65ef92b0 build(zod-openapi): lint published package (#1069) 2025-04-09 09:26:27 -04:00
Jonathan Haines a2c278515f build(typebox-validator): lint published package (#1066) 2025-04-09 09:26:27 -04:00
Jonathan Haines 72b20df1c8 build(tsyringe): lint published package (#1065) 2025-04-09 09:26:27 -04:00
Jonathan Haines 34c71fead3 build(trpc-server): lint published package (#1064) 2025-04-09 09:26:27 -04:00
Jonathan Haines b73045462e build(swagger-editor): lint published package (#1062) 2025-04-09 09:26:27 -04:00
Jonathan Haines cb6c76fef7 build(oidc-auth): lint published package (#1054)
* build(oidc-auth): lint published package

* build(oidc-auth): include require condition in subpath exports
2025-04-09 09:26:26 -04:00
Jonathan Haines 3529d32b17 build(qwik-city): lint published package (#1057)
* build(qwik-city): lint published package

* ci(qwik-city): add workflow to run build and publint
2025-04-09 09:26:26 -04:00
Jonathan Haines 5f4572f5b8 build(prometheus): lint published package (#1056) 2025-04-09 09:26:26 -04:00
Jonathan Haines 978da3e14b build(otel): lint published package (#1055) 2025-04-09 09:26:26 -04:00
Yusuke Wada 2d91b60742 chore: update the lockfile (#1072) 2025-04-09 09:26:26 -04:00
Jonathan Haines fcce865c87 build(oauth-providers): lint published package (#1053) 2025-04-09 09:26:26 -04:00
Jonathan Haines 9e77615d91 build(node-ws): lint published package (#1052) 2025-04-09 09:26:26 -04:00
Jonathan Haines abd52ce669 build(medley-router): lint published package (#1051) 2025-04-09 09:26:26 -04:00
Jonathan Haines 6a7e42d4ee build(hello): lint published package (#1050) 2025-04-09 09:26:26 -04:00
Jonathan Haines c1adb69a5c build(graphql-server): lint published package (#1049) 2025-04-09 09:26:26 -04:00
Jonathan Haines a5b900e503 build(firebase-auth): lint published package (#1048) 2025-04-09 09:26:26 -04:00
Jonathan Haines 66c265f7ea build(esbuild-transpiler): lint published package (#1046)
* build(esbuild-transpiler): lint published package

* chore: fix repository directory reference
2025-04-09 09:26:26 -04:00
Yusuke Wada 7a8b23d8c8 chore: update the lockfile (#1071) 2025-04-09 09:26:26 -04:00
Jonathan Haines 3b9448b870 build(event-emitter): lint published package (#1047) 2025-04-09 09:26:26 -04:00
Jonathan Haines 23b4cdd414 build(effect-validator): lint published package (#1045) 2025-04-09 09:26:26 -04:00
Jonathan Haines 4f2744b181 build(conform-validator): lint published package (#1044) 2025-04-09 09:26:26 -04:00
Jonathan Haines 8f97fdf83e build(cloudflare-access): lint published package (#1043) 2025-04-09 09:26:26 -04:00
Jonathan Haines 15971bde72 build(clerk-auth): lint published package (#1042) 2025-04-09 09:26:26 -04:00
Jonathan Haines 9e23349777 build(class-validator): lint published package (#1041) 2025-04-09 09:26:26 -04:00
Jonathan Haines d65cc146f9 build(auth-js): lint published package (#1034)
* build(auth-js): lint published package

* ci(auth-js): run publint

* build(auth-js): remove no splitting flag
2025-04-09 09:26:26 -04:00
github-actions[bot] 4b66525ad3 Version Packages (#1037)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:26:26 -04:00
wayofthepie 650cd0409b feat(oidc-auth): allow setting audience for oidc-auth (#1010) 2025-04-09 09:26:26 -04:00
Jonathan Haines 43794beaf5 ci(bun-transpiler): run publint (#1035) 2025-04-09 09:26:26 -04:00
Jonathan Haines 1b29fd1c35 build(casbin): lint published package (#1036) 2025-04-09 09:26:26 -04:00
Jonathan Haines 9da50dcc8c build(arktype-validator): lint published package (#1033)
* build(arktype-validator): lint published package

* ci(arktype-validator): run publint
2025-04-09 09:26:26 -04:00
Jonathan Haines 59a9a2747e chore: add tsup to monorepo root (#1032) 2025-04-09 09:26:26 -04:00
Jonathan Haines 95dd8e74ad build(ajv-validator): lint published package (#1030) 2025-04-09 09:26:26 -04:00
github-actions[bot] 64154467f0 Version Packages (#1028)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:26:26 -04:00
Musa Asukhanov 35031cb9f1 fix: Move "default" entrypoint down in "typia-validator" (#1027)
* Move "default" entrypoint down in "typia-validator"

* Add changeset

* Fix changeset
2025-04-09 09:26:26 -04:00
github-actions[bot] fc20f9c6f4 Version Packages (#1025)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:26:26 -04:00
Sungyu Kang 23fa14c596 chore(typia): bump 8.0.3 (#1024)
* chore(typia): bump 8.0.3

* chore: changeset

* fix: review

* fix: patch

* Update packages/typia-validator/package.json

Co-authored-by: Jonathan Haines <jonno.haines@gmail.com>

---------

Co-authored-by: Jonathan Haines <jonno.haines@gmail.com>
2025-04-09 09:26:26 -04:00
Jonathan Haines 4a1038ee66 chore: add coverage badges (#1023)
* chore: add coverage badges

* ci(casbin): fix spelling
2025-04-09 09:26:26 -04:00
Jonathan Haines 9d7a29d178 ci: initial coverage (#1022) 2025-04-09 09:26:26 -04:00
Jonathan Haines 86cb7db506 ci(coverage): upload initial coverage to codecov (#1021)
* ci(coverage): upload initial coverage to codecov

* ci(coverage): add flags

* ci(bun-transpiler): add coverage
2025-04-09 09:26:26 -04:00
Yusuke Wada e2726fd622 chore: update the lock file (#1019) 2025-04-09 09:26:26 -04:00
Jonathan Haines 990c8a5047 ci: run workspace scripts (#1015)
* ci: run workspace scripts

* ci: remove run option

* ci: remvoe default working directory

* test(firebase-auth): start emulator in vitest
2025-04-09 09:26:26 -04:00
github-actions[bot] 5ffb59fb53 Version Packages (#1018)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-04-09 09:26:26 -04:00
Milan Raj 2c16357028 feat(oidc-auth) Add initOidcAuthMiddleware and avoid mutating environment variables (#980)
* Add setOidcAuthEnv

* Avoid test relying on mutated global

* Test and docs

* Changeset

* style

* Update type import

* Switch to setOidcAuthEnvMiddleware

* Update changeset description

* nit remove unneeded optional param on getOidcAuthEnv

* Rename to initOidcAuthMiddleware
2025-04-09 09:26:26 -04:00
Tim Barley 76665d716e feat(oauth-providers): Add MSEntra OAuth Provider 2025-03-14 15:45:18 -04:00
17 changed files with 682 additions and 42 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/oauth-providers': minor
---
The PR adds Microsoft Entra (AzureAD) to the list of supported 3rd-party OAuth providers.

View File

@ -45,4 +45,4 @@
"vitest": "^3.0.8"
},
"packageManager": "yarn@4.0.2"
}
}

View File

@ -57,4 +57,4 @@
"engines": {
"node": ">=18.14.1"
}
}
}

View File

@ -1087,6 +1087,128 @@ The validation endpoint helps your application detect when tokens become invalid
> For security and compliance, make sure to implement regular token validation in your application. If a token becomes invalid, promptly sign out the user and terminate their OAuth session.
### MSEntra
```ts
import { Hono } from 'hono'
import { msentraAuth } from '@hono/oauth-providers/msentra'
const app = new Hono()
app.use(
'/msentra',
msentraAuth({
client_id: process.env.MSENTRA_ID,
client_secret: process.env.MSENTRA_SECRET,
tenant_id: process.env.MSENTRA_TENANT_ID
scope: [
'openid',
'profile',
'email',
'https;//graph.microsoft.com/.default',
]
})
)
export default app
```
### Parameters
- `client_id`:
- Type: `string`.
- `Required`.
- Your app client Id. You can find this in your Azure Portal.
- `client_secret`:
- Type: `string`.
- `Required`.
- Your app client secret. You can find this in your Azure Portal.
> ⚠️ Do **not** share your **client secret** to ensure the security of your app.
- `tenant_id`:
- Type: `string`
- `Required`.
- Your Microsoft Tenant's Id. You can find this in your Azure Portal.
- `scope`:
- Type: `string[]`.
- `Required`.
- Set of **permissions** to request the user's authorization to access your app for retrieving
user information and performing actions on their behalf.
#### Authentication Flow
After the completion of the MSEntra OAuth flow, essential data has been prepared for use in the
subsequent steps that your app needs to take.
`msentraAuth` method provides 4 set key data:
- `token`:
- Access token to make requests to the MSEntra API for retrieving user information and
performing actions on their behalf.
- Type:
```
{
token: string
expires_in: number
refresh_token: string
}
```
- `granted-scopes`:
- Scopes for which the user has granted permissions.
- Type: `string[]`.
- `user-msentra`:
- User basic info retrieved from MSEntra
- Type:
```
{
businessPhones: string[],
displayName: string
givenName: string
jobTitle: string
mail: string
mobilePhone: string
officeLocation: string
surname: string
userPrincipalName: string
id: string
}
```
> [!NOTE]
> To access this data, utilize the `c.get` method within the callback of the upcoming HTTP request
> handler.
```ts
app.get('/msentra', (c) => {
const token = c.get('token')
const grantedScopes = c.get('granted-scopes')
const user = c.get('user-msentra')
return c.json({
token,
grantedScopes,
user,
})
})
```
#### Refresh Token
Once the user token expires you can refresh their token without the need to prompt the user again
for access. In such scenario, you can utilize the `refreshToken` method, which accepts the
`client_id`, `client_secret`, `tenant_id`, and `refresh_token` as parameters.
> [!NOTE]
> The `refresh_token` can be used once. Once the token is refreshed MSEntra gives you a new
> `refresh_token` along with the new token.
```ts
import { msentraAuth, refreshToken } from '@hono/oauth-providers/msentra'
app.get('/msentra/refresh', (c, next) => {
const newTokens = await refreshToken({ client_id, client_secret, tenant_id, refresh_token })
})
```
## Advance Usage
### Customize `redirect_uri`

View File

@ -10,6 +10,11 @@ import type {
import type { GitHubErrorResponse, GitHubTokenResponse } from './src/providers/github'
import type { GoogleErrorResponse, GoogleTokenResponse, GoogleUser } from './src/providers/google'
import type { LinkedInErrorResponse, LinkedInTokenResponse } from './src/providers/linkedin'
import type {
MSEntraErrorResponse,
MSEntraTokenResponse,
MSEntraUser,
} from './src/providers/msentra'
import type {
TwitchErrorResponse,
TwitchTokenResponse,
@ -206,6 +211,31 @@ export const handlers = [
return HttpResponse.json(twitchValidateError, { status: 401 })
}
),
// MSEntra
http.post(
'https://login.microsoft.com/fake-tenant-id/oauth2/v2.0/token',
async ({
request,
}): Promise<StrictResponse<Partial<MSEntraTokenResponse> | MSEntraErrorResponse>> => {
const body = new URLSearchParams(await request.text())
if (body.get('code') === dummyCode || body.get('refresh_token') === msentraRefreshToken) {
return HttpResponse.json(msentraToken)
}
return HttpResponse.json(msentraCodeError)
}
),
http.get(
'https://graph.microsoft.com/v1.0/me',
async ({ request }): Promise<StrictResponse<Partial<MSEntraUser> | MSEntraErrorResponse>> => {
const authorization = request.headers.get('authorization')
if (authorization === `Bearer ${msentraToken.access_token}`) {
return HttpResponse.json(msentraUser)
}
return HttpResponse.json(msentraCodeError)
}
),
]
export const dummyCode = '4/0AfJohXl9tS46EmTA6u9x3pJQiyCNyahx4DLJaeJelzJ0E5KkT4qJmCtjq9n3FxBvO40ofg'
@ -558,3 +588,28 @@ export const twitchValidateError = {
status: 401,
message: 'invalid access token',
}
export const msentraRefreshToken = 'paofniueawnbfisdjkaierlufjkdnsj'
export const msentraToken = {
...dummyToken,
refresh_token: msentraRefreshToken,
}
export const msentraUser = {
'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',
businessPhones: ['111-111-1111'],
displayName: 'Test User',
givenName: 'Test',
jobTitle: 'Developer',
mail: 'example@email.com',
mobilePhone: '111-111-1111',
officeLocation: 'es-419',
preferredLanguage: null,
surname: 'User',
userPrincipalName: 'example@email.com',
id: '11111111-1111-1111-1111-111111111111',
}
export const msentraCodeError = {
error: 'invalid_grant',
error_description: 'AADSTS1234567: Invalid request.',
error_codes: [1234567],
}

View File

@ -27,6 +27,30 @@
"default": "./dist/index.cjs"
}
},
"./*": {
"import": {
"types": "./dist/providers/*/index.d.ts",
"default": "./dist/providers/*/index.js"
},
"require": {
"types": "./dist/providers/*/index.d.cts",
"default": "./dist/providers/*/index.cjs"
}
},
"./msentra": {
"import": {
"types": "./dist/providers/msentra/index.d.mts",
"default": "./dist/providers/msentra/index.mjs"
},
"require": {
"types": "./dist/providers/msentra/index.d.ts",
"default": "./dist/providers/msentra/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./*": {
"import": {
"types": "./dist/providers/*/index.d.ts",
@ -60,6 +84,9 @@
],
"twitch": [
"./dist/providers/twitch/index.d.ts"
],
"msentra": [
"./dist/providers/msentra/index.d.ts"
]
}
},

View File

@ -19,6 +19,10 @@ import {
linkedInCodeError,
linkedInToken,
linkedInUser,
msentraCodeError,
msentraRefreshToken,
msentraToken,
msentraUser,
xCodeError,
xRefreshToken,
xRefreshTokenError,
@ -48,6 +52,8 @@ import { googleAuth } from './providers/google'
import type { GoogleUser } from './providers/google'
import { linkedinAuth } from './providers/linkedin'
import type { LinkedInUser } from './providers/linkedin'
import type { MSEntraUser } from './providers/msentra'
import { msentraAuth, refreshToken as msentraRefresh } from './providers/msentra'
import type { TwitchUser } from './providers/twitch'
import {
twitchAuth,
@ -421,6 +427,55 @@ describe('OAuth Middleware', () => {
return c.json(response)
})
// MSEntra
app.use(
'/msentra',
msentraAuth({
client_id,
client_secret,
tenant_id: 'fake-tenant-id',
scope: ['openid', 'email', 'profile'],
})
)
app.use('/msentra-custom-redirect', (c, next) => {
return msentraAuth({
client_id,
client_secret,
tenant_id: 'fake-tenant-id',
scope: ['openid', 'email', 'profile'],
redirect_uri: 'http://localhost:3000/msentra',
})(c, next)
})
app.get('/msentra', (c) => {
const user = c.get('user-msentra')
const token = c.get('token')
const grantedScopes = c.get('granted-scopes')
return c.json({
user,
token,
grantedScopes,
})
})
app.get('/msentra/refresh', async (c) => {
const response = await msentraRefresh({
client_id,
client_secret,
tenant_id: 'fake-tenant-id',
refresh_token: msentraRefreshToken,
})
return c.json(response)
})
app.get('/msentra/refresh/error', async (c) => {
const response = await msentraRefresh({
client_id,
client_secret,
tenant_id: 'fake-tenant-id',
refresh_token: 'wrong-refresh-token',
})
return c.json(response)
})
beforeAll(() => {
server.listen()
})
@ -973,4 +1028,77 @@ describe('OAuth Middleware', () => {
})
})
})
describe('msentraAuth middleware', () => {
describe('middleware', () => {
it('Should redirect', async () => {
const res = await app.request('/msentra')
expect(res).not.toBeNull()
expect(res.status).toBe(302)
expect(res.headers)
})
it('Should redirect to custom redirect_uri', async () => {
const res = await app.request('/msentra-custom-redirect')
expect(res).not.toBeNull()
expect(res.status).toBe(302)
const redirectLocation = res.headers.get('location')!
const redirectUrl = new URL(redirectLocation)
expect(redirectUrl.searchParams.get('redirect_uri')).toBe('http://localhost:3000/msentra')
})
it('Prevent CSRF attack', async () => {
const res = await app.request(`/msentra?code=${dummyCode}&state=malware-state`)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
})
it('Should throw error for invalid code', async () => {
const res = await app.request('/msentra?code=9348ffdsd-sdsdbad-code')
const text = await res.text()
expect(res).not.toBeNull()
expect(res.status).toBe(400)
expect(text).toBe(msentraCodeError.error)
})
it('Should work with received code', async () => {
const res = await app.request(`/msentra?code=${dummyCode}`)
const response = (await res.json()) as {
token: Token
user: MSEntraUser
grantedScopes: string[]
}
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(response.user).toEqual(msentraUser)
expect(response.grantedScopes).toEqual(msentraToken.scope.split(' '))
expect(response.token).toEqual({
token: msentraToken.access_token,
expires_in: msentraToken.expires_in,
refresh_token: msentraToken.refresh_token,
})
})
})
describe('Refresh Token', () => {
it('Should refresh token', async () => {
const res = await app.request('/msentra/refresh')
expect(res).not.toBeNull()
expect(await res.json()).toEqual(msentraToken)
})
it('Should return error for refresh', async () => {
const res = await app.request('/msentra/refresh/error')
expect(res).not.toBeNull()
expect(res.status).toBe(400)
expect(await res.text()).toBe(msentraCodeError.error)
})
})
})
})

View File

@ -0,0 +1,124 @@
import { HTTPException } from 'hono/http-exception'
import { toQueryParams } from '../../utils/objectToQuery'
import type { MSEntraErrorResponse, MSEntraToken, MSEntraTokenResponse, MSEntraUser } from './types'
type MSEntraAuthFlow = {
client_id: string
client_secret: string
tenant_id: string
redirect_uri: string
code: string | undefined
token: MSEntraToken | undefined
scope: string[]
state?: string
}
export class AuthFlow {
client_id: string
client_secret: string
tenant_id: string
redirect_uri: string
code: string | undefined
token: MSEntraToken | undefined
scope: string[]
state: string | undefined
user: Partial<MSEntraUser> | undefined
granted_scopes: string[] | undefined
constructor({
client_id,
client_secret,
tenant_id,
redirect_uri,
code,
token,
scope,
state,
}: MSEntraAuthFlow) {
this.client_id = client_id
this.client_secret = client_secret
this.tenant_id = tenant_id
this.redirect_uri = redirect_uri
this.code = code
this.token = token
this.scope = scope
this.state = state
this.user = undefined
if (
this.client_id === undefined ||
this.client_secret === undefined ||
this.tenant_id === undefined ||
this.scope.length <= 0
) {
throw new HTTPException(400, {
message: 'Required parameters were not found. Please provide them to proceed.',
})
}
}
redirect() {
const parsedOptions = toQueryParams({
response_type: 'code',
redirect_uri: this.redirect_uri,
client_id: this.client_id,
include_granted_scopes: true,
scope: this.scope.join(' '),
state: this.state,
})
return `https://login.microsoft.com/${this.tenant_id}/oauth2/v2.0/authorize?${parsedOptions}`
}
async getTokenFromCode() {
const parsedOptions = toQueryParams({
client_id: this.client_id,
client_secret: this.client_secret,
redirect_uri: this.redirect_uri,
code: this.code,
grant_type: 'authorization_code',
})
const response = (await fetch(
`https://login.microsoft.com/${this.tenant_id}/oauth2/v2.0/token`,
{
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body: parsedOptions,
}
).then((res) => res.json())) as MSEntraTokenResponse | MSEntraErrorResponse
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}
if ('access_token' in response) {
this.token = {
token: response.access_token,
expires_in: response.expires_in,
refresh_token: response.refresh_token,
}
this.granted_scopes = response.scope.split(' ')
}
}
async getUserData() {
await this.getTokenFromCode()
//TODO: add support for extra fields
const response = (await fetch('https://graph.microsoft.com/v1.0/me', {
headers: {
authorization: `Bearer ${this.token?.token}`,
},
}).then(async (res) => res.json())) as MSEntraUser | MSEntraErrorResponse
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}
if ('id' in response) {
this.user = response
}
}
}

View File

@ -0,0 +1,11 @@
export { msentraAuth } from './msentraAuth'
export { refreshToken } from './refreshToken'
export * from './types'
import type { OAuthVariables } from '../../types'
import type { MSEntraUser } from './types'
declare module 'hono' {
interface ContextVariableMap extends OAuthVariables {
'user-msentra': Partial<MSEntraUser> | undefined
}
}

View File

@ -0,0 +1,63 @@
import type { MiddlewareHandler } from 'hono'
import { env } from 'hono/adapter'
import { getCookie, setCookie } from 'hono/cookie'
import { HTTPException } from 'hono/http-exception'
import { getRandomState } from '../../utils/getRandomState'
import { AuthFlow } from './authFlow'
export function msentraAuth(options: {
client_id?: string
client_secret?: string
tenant_id?: string
redirect_uri?: string
code?: string | undefined
scope: string[]
state?: string
}): MiddlewareHandler {
return async (c, next) => {
// Generate encoded "keys" if not provided
const newState = options.state || getRandomState()
// Create new Auth instance
const auth = new AuthFlow({
client_id: options.client_id || (env(c).MSENTRA_ID as string),
client_secret: options.client_secret || (env(c).MSENTRA_SECRET as string),
tenant_id: options.tenant_id || (env(c).MSENTRA_TENANT_ID as string),
redirect_uri: options.redirect_uri || c.req.url.split('?')[0],
code: c.req.query('code'),
token: {
token: c.req.query('access_token') as string,
expires_in: Number(c.req.query('expires_in')) as number,
},
scope: options.scope,
})
// Redirect to login dialog
if (!auth.code) {
setCookie(c, 'state', newState, {
maxAge: 60 * 10,
httpOnly: true,
path: '/',
})
return c.redirect(auth.redirect())
}
// Avoid CSRF attack by checking state
if (c.req.url.includes('?')) {
const storedState = getCookie(c, 'state')
if (c.req.query('state') !== storedState) {
throw new HTTPException(401)
}
}
// Retrieve user data from Microsoft Entra
await auth.getUserData()
// Set return info
c.set('token', auth.token)
c.set('user-msentra', auth.user)
c.set('granted-scopes', auth.granted_scopes)
await next()
}
}

View File

@ -0,0 +1,40 @@
import { HTTPException } from 'hono/http-exception'
import { toQueryParams } from '../../utils/objectToQuery'
import type { MSEntraErrorResponse, MSEntraTokenResponse } from './types'
export async function refreshToken({
client_id,
client_secret,
tenant_id,
refresh_token,
}: {
client_id: string
client_secret: string
tenant_id: string
refresh_token: string
}) {
if (!refresh_token) {
throw new HTTPException(400, { message: 'missing refresh token' })
}
const params = toQueryParams({
client_id,
client_secret,
refresh_token,
grant_type: 'refresh_token',
})
const response = (await fetch(`https://login.microsoft.com/${tenant_id}/oauth2/v2.0/token`, {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body: params,
}).then((res) => res.json())) as MSEntraTokenResponse | MSEntraErrorResponse
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}
return response
}

View File

@ -0,0 +1,32 @@
import type { Token } from '../../types'
export type MSEntraErrorResponse = {
error: string
error_description: string
error_codes: number[]
}
export type MSEntraTokenResponse = {
access_token: string
expires_in: number
scope: string
token_type: string
id_token: string
refresh_token: string
}
export type MSEntraUser = {
id: string
upn: string
verified_email: boolean
name: string
given_name: string
family_name: string
picture: string
local: string
employeeId: string
}
export type MSEntraToken = Token & {
refresh_token?: string
}

View File

@ -1,5 +1,17 @@
# @hono/react-renderer
## 1.0.1
### Patch Changes
- [#1122](https://github.com/honojs/middleware/pull/1122) [`944f1989f5fc14f62348427b8f26989bd17fd61c`](https://github.com/honojs/middleware/commit/944f1989f5fc14f62348427b8f26989bd17fd61c) Thanks [@yusukebe](https://github.com/yusukebe)! - fix: tweak dynamic importing `renderToReadableStream`
## 1.0.0
### Major Changes
- [#1119](https://github.com/honojs/middleware/pull/1119) [`684ae9a21d2976ad0a42853fd30dc1494494da46`](https://github.com/honojs/middleware/commit/684ae9a21d2976ad0a42853fd30dc1494494da46) Thanks [@yusukebe](https://github.com/yusukebe)! - feat: use React v19 and specify `react-dom/server.edge` for `renderToReadableStream`
## 0.3.0
### Minor Changes

View File

@ -1,6 +1,6 @@
{
"name": "@hono/react-renderer",
"version": "0.3.0",
"version": "1.0.1",
"description": "React Renderer Middleware for Hono",
"type": "module",
"module": "dist/index.js",
@ -40,17 +40,17 @@
"homepage": "https://github.com/honojs/middleware",
"peerDependencies": {
"hono": "*",
"react": "*",
"react-dom": "*"
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.17.4",
"@cloudflare/vitest-pool-workers": "^0.7.8",
"@types/react": "^18",
"@types/react-dom": "^18.2.17",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.2",
"publint": "^0.3.9",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"tsup": "^8.4.0",
"typescript": "^5.8.2",
"vitest": "^3.0.8"

View File

@ -128,6 +128,7 @@ describe('Basic', () => {
({ children }) => {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
@ -139,7 +140,9 @@ describe('Basic', () => {
const res = await app.request('/')
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('<!DOCTYPE html><html><body><h1>Hello</h1></body></html>')
expect(await res.text()).toBe(
'<!DOCTYPE html><html><head></head><body><h1>Hello</h1></body></html>'
)
})
it('Should return a content without a doctype', async () => {
@ -161,7 +164,7 @@ describe('Basic', () => {
const res = await app.request('/')
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('<html><body><h1>Hello</h1></body></html>')
expect(await res.text()).toBe('<html><head></head><body><h1>Hello</h1></body></html>')
})
it('Should return a custom doctype', async () => {
@ -187,7 +190,7 @@ describe('Basic', () => {
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe(
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><body><h1>Hello</h1></body></html>'
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head></head><body><h1>Hello</h1></body></html>'
)
})
@ -231,6 +234,8 @@ describe('Streaming', () => {
expect(res.status).toBe(200)
expect(res.headers.get('Transfer-Encoding')).toBe('chunked')
expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')
expect(await res.text()).toBe('<!DOCTYPE html><html><body><h1>Hello</h1></body></html>')
expect(await res.text()).toBe(
'<!DOCTYPE html><html><head></head><body><h1>Hello</h1></body></html>'
)
})
})

View File

@ -30,10 +30,13 @@ const createRenderer =
options?: RendererOptions
) =>
async (children: React.ReactElement, props?: Props) => {
const node = component ? component({ children, Layout, c, ...props }) : children
const node = component ? await component({ children, Layout, c, ...props }) : children
if (options?.stream) {
const { renderToReadableStream } = await import('react-dom/server')
// @ts-expect-error `react-dom/server.edge` is not typed well
const module = await import('react-dom/server.edge')
const renderToReadableStream =
module.renderToReadableStream ?? module.default.renderToReadableStream
const stream = await renderToReadableStream(
React.createElement(RequestContext.Provider, { value: c }, node),
options.readableStreamOptions
@ -52,8 +55,8 @@ const createRenderer =
typeof options?.docType === 'string'
? options.docType
: options?.docType === false
? ''
: '<!DOCTYPE html>'
? ''
: '<!DOCTYPE html>'
const body =
docType + renderToString(React.createElement(RequestContext.Provider, { value: c }, node))
return c.html(body)
@ -71,7 +74,7 @@ export const reactRenderer = (
if (component) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
c.setLayout((props: any) => {
return component({ ...props, Layout, c }, c)
return component({ ...props, Layout, c })
})
}
c.setRenderer(createRenderer(c, Layout, component, options))

View File

@ -2197,18 +2197,18 @@ __metadata:
dependencies:
"@arethetypeswrong/cli": "npm:^0.17.4"
"@cloudflare/vitest-pool-workers": "npm:^0.7.8"
"@types/react": "npm:^18"
"@types/react-dom": "npm:^18.2.17"
"@types/react": "npm:^19.1.0"
"@types/react-dom": "npm:^19.1.2"
publint: "npm:^0.3.9"
react: "npm:^18.2.0"
react-dom: "npm:^18.2.0"
react: "npm:^19.1.0"
react-dom: "npm:^19.1.0"
tsup: "npm:^8.4.0"
typescript: "npm:^5.8.2"
vitest: "npm:^3.0.8"
peerDependencies:
hono: "*"
react: "*"
react-dom: "*"
react: ^19.0.0
react-dom: ^19.0.0
languageName: unknown
linkType: soft
@ -3924,12 +3924,12 @@ __metadata:
languageName: node
linkType: hard
"@types/react-dom@npm:^18.2.17":
version: 18.3.5
resolution: "@types/react-dom@npm:18.3.5"
"@types/react-dom@npm:^19.1.2":
version: 19.1.2
resolution: "@types/react-dom@npm:19.1.2"
peerDependencies:
"@types/react": ^18.0.0
checksum: b163d35a6b32a79f5782574a7aeb12a31a647e248792bf437e6d596e2676961c394c5e3c6e91d1ce44ae90441dbaf93158efb4f051c0d61e2612f1cb04ce4faa
"@types/react": ^19.0.0
checksum: 100c341cacba9ec8ae1d47ee051072a3450e9573bf8eeb7262490e341cb246ea0f95a07a1f2077e61cf92648f812a0324c602fcd811bd87b7ce41db2811510cd
languageName: node
linkType: hard
@ -3943,6 +3943,15 @@ __metadata:
languageName: node
linkType: hard
"@types/react@npm:^19.1.0":
version: 19.1.0
resolution: "@types/react@npm:19.1.0"
dependencies:
csstype: "npm:^3.0.2"
checksum: 632fd20ee176e55801a61c5f854141b043571a3e363ef106b047b766a813a12735cbb37abb3d61d126346979f530f2ed269a60c8ef3cdee54e5e9fe4174e5dad
languageName: node
linkType: hard
"@types/request@npm:^2.48.8":
version: 2.48.12
resolution: "@types/request@npm:2.48.12"
@ -11882,15 +11891,14 @@ __metadata:
languageName: node
linkType: hard
"react-dom@npm:^18.2.0":
version: 18.3.1
resolution: "react-dom@npm:18.3.1"
"react-dom@npm:^19.1.0":
version: 19.1.0
resolution: "react-dom@npm:19.1.0"
dependencies:
loose-envify: "npm:^1.1.0"
scheduler: "npm:^0.23.2"
scheduler: "npm:^0.26.0"
peerDependencies:
react: ^18.3.1
checksum: a752496c1941f958f2e8ac56239172296fcddce1365ce45222d04a1947e0cc5547df3e8447f855a81d6d39f008d7c32eab43db3712077f09e3f67c4874973e85
react: ^19.1.0
checksum: 3e26e89bb6c67c9a6aa86cb888c7a7f8258f2e347a6d2a15299c17eb16e04c19194e3452bc3255bd34000a61e45e2cb51e46292392340432f133e5a5d2dfb5fc
languageName: node
linkType: hard
@ -11903,6 +11911,13 @@ __metadata:
languageName: node
linkType: hard
"react@npm:^19.1.0":
version: 19.1.0
resolution: "react@npm:19.1.0"
checksum: 530fb9a62237d54137a13d2cfb67a7db6a2156faed43eecc423f4713d9b20c6f2728b026b45e28fcd72e8eadb9e9ed4b089e99f5e295d2f0ad3134251bdd3698
languageName: node
linkType: hard
"read-yaml-file@npm:^1.1.0":
version: 1.1.0
resolution: "read-yaml-file@npm:1.1.0"
@ -12610,12 +12625,10 @@ __metadata:
languageName: node
linkType: hard
"scheduler@npm:^0.23.2":
version: 0.23.2
resolution: "scheduler@npm:0.23.2"
dependencies:
loose-envify: "npm:^1.1.0"
checksum: 26383305e249651d4c58e6705d5f8425f153211aef95f15161c151f7b8de885f24751b377e4a0b3dd42cce09aad3f87a61dab7636859c0d89b7daf1a1e2a5c78
"scheduler@npm:^0.26.0":
version: 0.26.0
resolution: "scheduler@npm:0.26.0"
checksum: 5b8d5bfddaae3513410eda54f2268e98a376a429931921a81b5c3a2873aab7ca4d775a8caac5498f8cbc7d0daeab947cf923dbd8e215d61671f9f4e392d34356
languageName: node
linkType: hard