Compare commits

...

23 Commits

Author SHA1 Message Date
Balázs Orbán
d5dd901b03 chore(release): bump package version(s) [skip ci] 2022-12-11 14:52:30 +00:00
Balázs Orbán
62f672ae30 fix(core): host detection/NEXTAUTH_URL (#6007)
* rename `host` to `origin` internally

* rename `userOptions` to `authOptions` internally

* use object for `headers` internally

* default `method` to GET

* simplify `unstable_getServerSession`

* allow optional headers

* revert middleware

* wip getURL

* revert host detection

* use old `detectHost`

* fix/add some tests wip

* move more to core, refactor getURL

* better type auth actions

* fix custom path support (w/ api/auth)

* add `getURL` tests

* fix email tests

* fix assert tests

* custom base without api/auth, with trailing slash

* remove parseUrl from assert.ts

* return 400 when wrong url

* fix tests

* refactor

* fix protocol in dev

* fix tests

* fix custom url handling

* add todo comments
2022-12-11 14:48:28 +00:00
Balázs Orbán
2c669b32fc fix(core): correct status code when returning redirects (#6004)
* fix(core): correctly set status when returning redirect

* update tests

* forward other headers

* update test

* remove default 200 status
2022-12-11 12:55:16 +00:00
Cyril Perraud
2dea8919e5 fix(sequelize): increase sequelize id_token column length (#5929)
Co-authored-by: Nico Domino <yo@ndo.dev>
2022-12-10 12:34:45 +01:00
Balázs Orbán
6fdb0da6eb chore(release): bump package version(s) [skip ci] 2022-12-09 00:34:31 +01:00
Balázs Orbán
5c4a9a697d fix(core): handle Request -> Response regressions (#5991)
* fix(next): don't override `Content-Type` by `unstable_getServerSession`

* fix(core): handle `,` while setting `set-cookie`
2022-12-08 23:29:25 +00:00
Thomas Desmond
eddd8fd7f9 chore(docs): add new tutorial (#5604)
Co-authored-by: Nico Domino <yo@ndo.dev>
2022-12-08 18:24:58 +01:00
Balázs Orbán
b74bfc68e8 chore(release): bump package version(s) [skip ci] 2022-12-08 05:16:10 +01:00
Balázs Orbán
0a140cdf87 test(core): fix test 2022-12-08 05:11:37 +01:00
Balázs Orbán
157269e0fb fix(core): throw error if no action can be determined 2022-12-08 05:10:26 +01:00
Balázs Orbán
221bc8e99c fix(core): add protocol if missing 2022-12-08 04:54:42 +01:00
Balázs Orbán
f856363ac8 chore(release): bump package version(s) [skip ci] 2022-12-08 04:38:03 +01:00
Balázs Orbán
f3291025e6 fix(core): properly construct url (#5984) 2022-12-08 04:33:20 +01:00
Balázs Orbán
bc0912cc71 chore(release): bump package version(s) [skip ci] 2022-12-08 00:08:09 +01:00
Branden Cash
b19b2bcb3f fix(core): don't mutate authOptions in unstable_getServerSession (#5973) 2022-12-07 22:04:53 +01:00
Balázs Orbán
63c2a15717 Update nextjs.md 2022-12-07 14:39:57 +01:00
Balázs Orbán
9209b48dbe chore: add issue validator 2022-12-06 12:21:42 +01:00
Balázs Orbán
0fcc6a0d04 refactor: more renames 2022-12-05 13:38:29 +01:00
Balázs Orbán
cbf8c7a59f refactor: rename 2022-12-03 15:51:38 +01:00
Balázs Orbán
0e6c51adec refactor: rename 2022-12-03 15:41:39 +01:00
Balázs Orbán
c4352a7d56 chore(dev): upgrade dev app and deps
Conflicts:
	apps/dev/pages/api/auth/[...nextauth].ts
2022-12-03 15:33:49 +01:00
Balázs Orbán
7e91d7df54 refactor(core): use standard Request and Response (#4769)
* WIP use `Request` and `Response` for core

* bump Next.js

* rename ts types

* refactor

* simplify

* upgrade Next.js

* implement body reader

* use `Request`/`Response` in `next-auth/next`

* make linter happy

* revert

* fix tests

* remove workaround for middleware return type

* return session in protected api route example

* don't export internal handler

* fall back host to localhost

* refactor `getBody`

* refactor `next-auth/next`

* chore: add `@edge-runtime/jest-environment`

* fix tests, using Node 18 as runtime

* fix test

* remove patch

* fix neo4j build

* remove new-line

* reduce file changes in the PR

* fix tests

* fix tests

* refactor

* refactor

* add host tests

* refactor tests

* fix body reading

* fix tests

* use 302

* fix test

* fix again

* fix tests

* handle when body is `Buffer`

* move comment
2022-12-03 13:39:08 +00:00
Balázs Orbán
c1424136db chore(dev): don't load all adapters in dev app 2022-12-03 13:45:06 +01:00
56 changed files with 2499 additions and 657 deletions

View File

@@ -0,0 +1,2 @@
!dist
!package-lock.json

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,652 @@
@actions/core
MIT
The MIT License (MIT)
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@actions/github
MIT
The MIT License (MIT)
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@actions/http-client
MIT
Actions Http Client for Node.js
Copyright (c) GitHub, Inc.
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@octokit/auth-token
MIT
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@octokit/core
MIT
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@octokit/endpoint
MIT
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@octokit/graphql
MIT
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@octokit/plugin-paginate-rest
MIT
MIT License Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@octokit/plugin-rest-endpoint-methods
MIT
MIT License Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@octokit/request
MIT
The MIT License
Copyright (c) 2018 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@octokit/request-error
MIT
The MIT License
Copyright (c) 2019 Octokit contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@vercel/ncc
MIT
Copyright 2018 ZEIT, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
before-after-hook
Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Gregor Martynus and other contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
deprecation
ISC
The ISC License
Copyright (c) Gregor Martynus and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
is-plain-object
MIT
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
node-fetch
MIT
The MIT License (MIT)
Copyright (c) 2016 David Frank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
once
ISC
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
root
ISC License
Copyright (c) 2018-2021, Iain Collins
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
tr46
MIT
tunnel
MIT
The MIT License (MIT)
Copyright (c) 2012 Koichi Kobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
universal-user-agent
ISC
# [ISC License](https://spdx.org/licenses/ISC)
Copyright (c) 2018, Gregor Martynus (https://github.com/gr2m)
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
uuid
MIT
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
webidl-conversions
BSD-2-Clause
# The BSD 2-Clause License
Copyright (c) 2014, Domenic Denicola
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
whatwg-url
MIT
The MIT License (MIT)
Copyright (c) 20152016 Sebastian Mayr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
wrappy
ISC
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

445
.github/actions/issue-validator/package-lock.json generated vendored Normal file
View File

@@ -0,0 +1,445 @@
{
"name": "issue-validator",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"dependencies": {
"@actions/core": "1.10.0",
"@actions/github": "5.1.1"
},
"devDependencies": {
"@vercel/ncc": "0.34.0"
}
},
"node_modules/@actions/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz",
"integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==",
"dependencies": {
"@actions/http-client": "^2.0.1",
"uuid": "^8.3.2"
}
},
"node_modules/@actions/github": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@actions/github/-/github-5.1.1.tgz",
"integrity": "sha512-Nk59rMDoJaV+mHCOJPXuvB1zIbomlKS0dmSIqPGxd0enAXBnOfn4VWF+CGtRCwXZG9Epa54tZA7VIRlJDS8A6g==",
"dependencies": {
"@actions/http-client": "^2.0.1",
"@octokit/core": "^3.6.0",
"@octokit/plugin-paginate-rest": "^2.17.0",
"@octokit/plugin-rest-endpoint-methods": "^5.13.0"
}
},
"node_modules/@actions/http-client": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz",
"integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==",
"dependencies": {
"tunnel": "^0.0.6"
}
},
"node_modules/@octokit/auth-token": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz",
"integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==",
"dependencies": {
"@octokit/types": "^6.0.3"
}
},
"node_modules/@octokit/core": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.6.0.tgz",
"integrity": "sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==",
"dependencies": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.6.3",
"@octokit/request-error": "^2.0.5",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/endpoint": {
"version": "6.0.12",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.12.tgz",
"integrity": "sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==",
"dependencies": {
"@octokit/types": "^6.0.3",
"is-plain-object": "^5.0.0",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/graphql": {
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.8.0.tgz",
"integrity": "sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==",
"dependencies": {
"@octokit/request": "^5.6.0",
"@octokit/types": "^6.0.3",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/openapi-types": {
"version": "12.10.1",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.10.1.tgz",
"integrity": "sha512-P+SukKanjFY0ZhsK6wSVnQmxTP2eVPPE8OPSNuxaMYtgVzwJZgfGdwlYjf4RlRU4vLEw4ts2fsE2icG4nZ5ddQ=="
},
"node_modules/@octokit/plugin-paginate-rest": {
"version": "2.21.3",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz",
"integrity": "sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw==",
"dependencies": {
"@octokit/types": "^6.40.0"
},
"peerDependencies": {
"@octokit/core": ">=2"
}
},
"node_modules/@octokit/plugin-rest-endpoint-methods": {
"version": "5.16.2",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz",
"integrity": "sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw==",
"dependencies": {
"@octokit/types": "^6.39.0",
"deprecation": "^2.3.1"
},
"peerDependencies": {
"@octokit/core": ">=3"
}
},
"node_modules/@octokit/request": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz",
"integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==",
"dependencies": {
"@octokit/endpoint": "^6.0.1",
"@octokit/request-error": "^2.1.0",
"@octokit/types": "^6.16.1",
"is-plain-object": "^5.0.0",
"node-fetch": "^2.6.7",
"universal-user-agent": "^6.0.0"
}
},
"node_modules/@octokit/request-error": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz",
"integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==",
"dependencies": {
"@octokit/types": "^6.0.3",
"deprecation": "^2.0.0",
"once": "^1.4.0"
}
},
"node_modules/@octokit/types": {
"version": "6.40.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.40.0.tgz",
"integrity": "sha512-MFZOU5r8SwgJWDMhrLUSvyJPtVsqA6VnbVI3TNbsmw+Jnvrktzvq2fYES/6RiJA/5Ykdwq4mJmtlYUfW7CGjmw==",
"dependencies": {
"@octokit/openapi-types": "^12.10.0"
}
},
"node_modules/@vercel/ncc": {
"version": "0.34.0",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.34.0.tgz",
"integrity": "sha512-G9h5ZLBJ/V57Ou9vz5hI8pda/YQX5HQszCs3AmIus3XzsmRn/0Ptic5otD3xVST8QLKk7AMk7AqpsyQGN7MZ9A==",
"dev": true,
"bin": {
"ncc": "dist/ncc/cli.js"
}
},
"node_modules/before-after-hook": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.2.tgz",
"integrity": "sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ=="
},
"node_modules/deprecation": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
"integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
},
"node_modules/is-plain-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/node-fetch": {
"version": "2.6.7",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/tunnel": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz",
"integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==",
"engines": {
"node": ">=0.6.11 <=0.7.0 || >=0.7.3"
}
},
"node_modules/universal-user-agent": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz",
"integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w=="
},
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}
},
"dependencies": {
"@actions/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz",
"integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==",
"requires": {
"@actions/http-client": "^2.0.1",
"uuid": "^8.3.2"
}
},
"@actions/github": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@actions/github/-/github-5.1.1.tgz",
"integrity": "sha512-Nk59rMDoJaV+mHCOJPXuvB1zIbomlKS0dmSIqPGxd0enAXBnOfn4VWF+CGtRCwXZG9Epa54tZA7VIRlJDS8A6g==",
"requires": {
"@actions/http-client": "^2.0.1",
"@octokit/core": "^3.6.0",
"@octokit/plugin-paginate-rest": "^2.17.0",
"@octokit/plugin-rest-endpoint-methods": "^5.13.0"
}
},
"@actions/http-client": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz",
"integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==",
"requires": {
"tunnel": "^0.0.6"
}
},
"@octokit/auth-token": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz",
"integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==",
"requires": {
"@octokit/types": "^6.0.3"
}
},
"@octokit/core": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.6.0.tgz",
"integrity": "sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==",
"requires": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.6.3",
"@octokit/request-error": "^2.0.5",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/endpoint": {
"version": "6.0.12",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.12.tgz",
"integrity": "sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==",
"requires": {
"@octokit/types": "^6.0.3",
"is-plain-object": "^5.0.0",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/graphql": {
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.8.0.tgz",
"integrity": "sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==",
"requires": {
"@octokit/request": "^5.6.0",
"@octokit/types": "^6.0.3",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/openapi-types": {
"version": "12.10.1",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.10.1.tgz",
"integrity": "sha512-P+SukKanjFY0ZhsK6wSVnQmxTP2eVPPE8OPSNuxaMYtgVzwJZgfGdwlYjf4RlRU4vLEw4ts2fsE2icG4nZ5ddQ=="
},
"@octokit/plugin-paginate-rest": {
"version": "2.21.3",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz",
"integrity": "sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw==",
"requires": {
"@octokit/types": "^6.40.0"
}
},
"@octokit/plugin-rest-endpoint-methods": {
"version": "5.16.2",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz",
"integrity": "sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw==",
"requires": {
"@octokit/types": "^6.39.0",
"deprecation": "^2.3.1"
}
},
"@octokit/request": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz",
"integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==",
"requires": {
"@octokit/endpoint": "^6.0.1",
"@octokit/request-error": "^2.1.0",
"@octokit/types": "^6.16.1",
"is-plain-object": "^5.0.0",
"node-fetch": "^2.6.7",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/request-error": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz",
"integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==",
"requires": {
"@octokit/types": "^6.0.3",
"deprecation": "^2.0.0",
"once": "^1.4.0"
}
},
"@octokit/types": {
"version": "6.40.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.40.0.tgz",
"integrity": "sha512-MFZOU5r8SwgJWDMhrLUSvyJPtVsqA6VnbVI3TNbsmw+Jnvrktzvq2fYES/6RiJA/5Ykdwq4mJmtlYUfW7CGjmw==",
"requires": {
"@octokit/openapi-types": "^12.10.0"
}
},
"@vercel/ncc": {
"version": "0.34.0",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.34.0.tgz",
"integrity": "sha512-G9h5ZLBJ/V57Ou9vz5hI8pda/YQX5HQszCs3AmIus3XzsmRn/0Ptic5otD3xVST8QLKk7AMk7AqpsyQGN7MZ9A==",
"dev": true
},
"before-after-hook": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.2.tgz",
"integrity": "sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ=="
},
"deprecation": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
"integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
},
"is-plain-object": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q=="
},
"node-fetch": {
"version": "2.6.7",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
"requires": {
"whatwg-url": "^5.0.0"
}
},
"once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"requires": {
"wrappy": "1"
}
},
"tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"tunnel": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz",
"integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg=="
},
"universal-user-agent": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz",
"integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w=="
},
"uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
},
"webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"requires": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}
}
}

View File

@@ -0,0 +1,14 @@
{
"private": true,
"exports": "./index.mjs",
"scripts": {
"build": "ncc -m -o . build src/index.mjs --license licenses.txt"
},
"devDependencies": {
"@vercel/ncc": "0.34.0"
},
"dependencies": {
"@actions/core": "1.10.0",
"@actions/github": "5.1.1"
}
}

View File

@@ -0,0 +1,38 @@
We cannot recreate the issue with the provided information. **Please add a reproduction in order for us to be able to investigate.**
### **Why was this issue marked with the `incomplete` label?**
To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository ([template](https://github.com/nextauthjs/next-auth-example)), but you can also use a tool like [CodeSandbox](https://codesandbox.io/s/github/nextauthjs/next-auth-example/tree/main) or [StackBlitz](https://stackblitz.com/fork/github/nextauthjs/next-auth-example).
To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as **minimal** as possible. This means that you should **remove unnecessary code, files, and dependencies** that do not contribute to the issue.
Please test your reproduction against the latest version of NextAuth.js (`next-auth@latest`) to make sure your issue has not already been fixed.
### **I added a link, why was it still marked?**
Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "[example.com](http://example.com/)", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.
### **What happens if I don't provide a sufficient minimal reproduction?**
Issues with the `incomplete` label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.
If your issue has _not_ been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.
### **I did not open this issue, but it is relevant to me, what can I do to help?**
Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the :+1: reaction on the topmost comment (please **do not** comment "I have the same issue" without repro steps). Then, we can sort issues by votes to prioritize.
### **I think my reproduction is good enough, why aren't you looking into it quicker?**
We look into every NextAuth.js issue and constantly monitor open issues for new comments.
However, sometimes we might miss one or two. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.
Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.
### **Useful Resources**
- [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
- [Reporting a NextAuth.js bug](https://github.com/nextauthjs/next-auth/blob/main/.github/ISSUE_TEMPLATE/1_bug_framework.yml)
- [How to Contribute to Open Source (Next.js)](https://www.youtube.com/watch?v=cuoNzXFLitc)

View File

@@ -0,0 +1,88 @@
// @ts-check
// @ts-expect-error
import * as github from "@actions/github"
// @ts-expect-error
import * as core from "@actions/core"
import { readFileSync } from "node:fs"
import { join } from "node:path"
const addReproductionLabel = "incomplete"
const __dirname =
"/home/runner/work/nextauthjs/next-auth/.github/actions/issue-validator"
/**
* @typedef {{
* id :number
* node_id :string
* url :string
* name :string
* description :string
* color :string
* default :boolean
* }} Label
*
* @typedef {{
* pull_request: any
* issue?: {body: string, number: number, labels: Label[]}
* label: Label
* }} Payload
*
* @typedef {{
* payload: Payload
* repo: any
* }} Context
*/
async function run() {
try {
/** @type {Context} */
const { payload, repo } = github.context
const {
issue,
pull_request,
label: { name: newLabel },
} = payload
if (pull_request || !issue?.body || !process.env.GITHUB_TOKEN) return
const labels = issue.labels.map((l) => l.name)
// const isBugReport =
// labels.includes(bugLabel) || newLabel === bugLabel || !labels.length
if (
// !(isBugReport && issue.number > 43554) &&
![addReproductionLabel].includes(newLabel) &&
!labels.includes(addReproductionLabel)
) {
return core.info(
"Not a bug report or not manually labeled or already labeled."
)
}
const client = github.getOctokit(process.env.GITHUB_TOKEN).rest
const issueCommon = { ...repo, issue_number: issue.number }
if (
newLabel === addReproductionLabel
// || !hasValidRepro
) {
await Promise.all([
client.issues.addLabels({
...issueCommon,
labels: [addReproductionLabel],
}),
client.issues.createComment({
...issueCommon,
body: readFileSync(join(__dirname, "repro.md"), "utf8"),
}),
])
return core.info(
"Commented on issue, because it did not have a sufficient reproduction."
)
}
} catch (error) {
core.setFailed(error.message)
}
}
run()

17
.github/workflows/issue-validator.yml vendored Normal file
View File

@@ -0,0 +1,17 @@
name: Validate issue
on:
issues:
types: [labeled]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- name: 'Run issue validator'
run: node ./.github/actions/issue-validator/index.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -21,8 +21,7 @@
"@prisma/client": "^3", "@prisma/client": "^3",
"@supabase/supabase-js": "^2.0.5", "@supabase/supabase-js": "^2.0.5",
"faunadb": "^4", "faunadb": "^4",
"jsonwebtoken": "^8.5.1", "next": "13.0.6",
"next": "13.0.2",
"next-auth": "workspace:*", "next-auth": "workspace:*",
"nodemailer": "^6", "nodemailer": "^6",
"react": "^18", "react": "^18",

View File

@@ -1,6 +1,4 @@
import NextAuth from "next-auth" import NextAuth, { type NextAuthOptions } from "next-auth"
import type { NextAuthOptions } from "next-auth"
import jwt from "jsonwebtoken"
// Providers // Providers
import Apple from "next-auth/providers/apple" import Apple from "next-auth/providers/apple"
@@ -37,69 +35,39 @@ import Vk from "next-auth/providers/vk"
import Wikimedia from "next-auth/providers/wikimedia" import Wikimedia from "next-auth/providers/wikimedia"
import WorkOS from "next-auth/providers/workos" import WorkOS from "next-auth/providers/workos"
// Adapters // // Prisma
import { PrismaClient } from "@prisma/client" // import { PrismaClient } from "@prisma/client"
import { PrismaAdapter } from "@next-auth/prisma-adapter" // import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { Client as FaunaClient } from "faunadb" // const client = globalThis.prisma || new PrismaClient()
import { FaunaAdapter } from "@next-auth/fauna-adapter" // if (process.env.NODE_ENV !== "production") globalThis.prisma = client
import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter" // const adapter = PrismaAdapter(client)
import { SupabaseAdapter } from "@next-auth/supabase-adapter"
// Add an adapter you want to test here. // // Fauna
const adapters = { // import { Client as FaunaClient } from "faunadb"
prisma() { // import { FaunaAdapter } from "@next-auth/fauna-adapter"
const client = globalThis.prisma || new PrismaClient() // const opts = { secret: process.env.FAUNA_SECRET, domain: process.env.FAUNA_DOMAIN }
if (process.env.NODE_ENV !== "production") globalThis.prisma = client // const client = globalThis.fauna || new FaunaClient(opts)
return PrismaAdapter(client) // if (process.env.NODE_ENV !== "production") globalThis.fauna = client
}, // const adapter = FaunaAdapter(client)
typeorm() {
return TypeORMLegacyAdapter({ // // TypeORM
type: "sqlite", // import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter"
name: "next-auth-test-memory", // const adapter = TypeORMLegacyAdapter({
database: "./typeorm/dev.db", // type: "sqlite",
synchronize: true, // name: "next-auth-test-memory",
}) // database: "./typeorm/dev.db",
}, // synchronize: true,
fauna() { // })
const client =
globalThis.fauna || // // Supabase
new FaunaClient({ // import { SupabaseAdapter } from "@next-auth/supabase-adapter"
secret: process.env.FAUNA_SECRET, // const adapter = SupabaseAdapter({
domain: process.env.FAUNA_DOMAIN, // url: process.env.NEXT_PUBLIC_SUPABASE_URL,
}) // secret: process.env.SUPABASE_SERVICE_ROLE_KEY,
if (process.env.NODE_ENV !== "production") global.fauna = client // })
return FaunaAdapter(client)
},
supabase() {
return SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY,
})
},
noop() {
return undefined
},
}
export const authOptions: NextAuthOptions = { export const authOptions: NextAuthOptions = {
adapter: adapters.noop(), // adapter,
callbacks: {
async session({ session, user }) {
// NOTE: this is needed when using Supabase with RLS. Otherwise this callback can be removed.
const signingSecret = process.env.SUPABASE_JWT_SECRET
if (signingSecret) {
const payload = {
aud: "authenticated",
exp: Math.floor(new Date(session.expires).getTime() / 1000),
sub: user.id,
email: user.email,
role: "authenticated",
}
session.supabaseAccessToken = jwt.sign(payload, signingSecret)
}
return session
},
},
debug: process.env.NODE_ENV !== "production", debug: process.env.NODE_ENV !== "production",
theme: { theme: {
logo: "https://next-auth.js.org/img/logo/logo-sm.png", logo: "https://next-auth.js.org/img/logo/logo-sm.png",

View File

@@ -75,9 +75,10 @@ You can also use `unstable_getServerSession` in Next.js' server components:
```tsx ```tsx
import { unstable_getServerSession } from "next-auth/next" import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
export default async function Page() { export default async function Page() {
const session = await unstable_getServerSession() const session = await unstable_getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre> return <pre>{JSON.stringify(session, null, 2)}</pre>
} }
``` ```

View File

@@ -46,6 +46,10 @@ title: Tutorials and Explainers
- Learn how to use Sign-In With Ethereum to authenticate your users with their existing Ethereum wallets - identifiers they personally control. - Learn how to use Sign-In With Ethereum to authenticate your users with their existing Ethereum wallets - identifiers they personally control.
- Example application: [spruceid/siwe-next-auth-example](https://github.com/spruceid/siwe-next-auth-example) - Example application: [spruceid/siwe-next-auth-example](https://github.com/spruceid/siwe-next-auth-example)
#### [Next.js Authentication with Okta and NextAuth.js 4.0](https://thetombomb.com/posts/nextjs-nextauth-okta) <svg xmlns="http://www.w3.org/2000/svg" style={{ marginLeft: '5px', marginBottom:'-6px'}} height="20" width="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><title>External</title> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /> </svg>
- Learn how to perform authentication with an OIDC Application in Okta and NextAuth.js.
## Fullstack ## Fullstack
#### [Build a FullStack App with Next.js, NextAuth.js, Supabase & Prisma](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-322389284337222224) <svg xmlns="http://www.w3.org/2000/svg" style={{ marginLeft: '5px', marginBottom:'-6px'}} height="20" width="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><title>External</title> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /> </svg> #### [Build a FullStack App with Next.js, NextAuth.js, Supabase & Prisma](https://themodern.dev/courses/build-a-fullstack-app-with-nextjs-supabase-and-prisma-322389284337222224) <svg xmlns="http://www.w3.org/2000/svg" style={{ marginLeft: '5px', marginBottom:'-6px'}} height="20" width="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><title>External</title> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /> </svg>

View File

@@ -14,6 +14,10 @@ If you did not find a guide or tutorial covering your use case, please [open an
- How to restrict access to pages and API routes. - How to restrict access to pages and API routes.
- [Usage with class components](/tutorials/usage-with-class-components) - [Usage with class components](/tutorials/usage-with-class-components)
- How to use `useSession()` hook with class components. - How to use `useSession()` hook with class components.
- [Next.js Authentication with Okta and NextAuth.js 4.0](https://thetombomb.com/posts/nextjs-nextauth-okta)
- Learn how to perform authentication with an OIDC Application in Okta and NextAuth.js.
### Advanced ### Advanced

View File

@@ -1,6 +1,6 @@
{ {
"name": "@next-auth/sequelize-adapter", "name": "@next-auth/sequelize-adapter",
"version": "1.0.6", "version": "1.0.7",
"description": "Sequelize adapter for next-auth.", "description": "Sequelize adapter for next-auth.",
"homepage": "https://next-auth.js.org", "homepage": "https://next-auth.js.org",
"repository": "https://github.com/nextauthjs/next-auth", "repository": "https://github.com/nextauthjs/next-auth",

View File

@@ -14,7 +14,7 @@ export const Account = {
expires_at: { type: DataTypes.INTEGER }, expires_at: { type: DataTypes.INTEGER },
token_type: { type: DataTypes.STRING }, token_type: { type: DataTypes.STRING },
scope: { type: DataTypes.STRING }, scope: { type: DataTypes.STRING },
id_token: { type: DataTypes.STRING }, id_token: { type: DataTypes.TEXT },
session_state: { type: DataTypes.STRING }, session_state: { type: DataTypes.STRING },
userId: { type: DataTypes.UUID }, userId: { type: DataTypes.UUID },
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "next-auth", "name": "next-auth",
"version": "4.18.0", "version": "4.18.5",
"description": "Authentication for Next.js", "description": "Authentication for Next.js",
"homepage": "https://next-auth.js.org", "homepage": "https://next-auth.js.org",
"repository": "https://github.com/nextauthjs/next-auth.git", "repository": "https://github.com/nextauthjs/next-auth.git",
@@ -120,7 +120,7 @@
"jest-environment-jsdom": "^28.1.1", "jest-environment-jsdom": "^28.1.1",
"jest-watch-typeahead": "^1.1.0", "jest-watch-typeahead": "^1.1.0",
"msw": "^0.42.3", "msw": "^0.42.3",
"next": "13.0.2", "next": "13.0.6",
"postcss": "^8.4.14", "postcss": "^8.4.14",
"postcss-cli": "^9.1.0", "postcss-cli": "^9.1.0",
"postcss-nested": "^5.0.6", "postcss-nested": "^5.0.6",

View File

@@ -1,7 +1,7 @@
import type { IncomingMessage } from "http" import type { IncomingMessage } from "http"
import type { LoggerInstance, Session } from ".." import type { LoggerInstance, Session } from ".."
export interface NextAuthClientConfig { export interface AuthClientConfig {
baseUrl: string baseUrl: string
basePath: string basePath: string
baseUrlServer: string baseUrlServer: string
@@ -31,7 +31,7 @@ export interface CtxOrReq {
*/ */
export async function fetchData<T = any>( export async function fetchData<T = any>(
path: string, path: string,
__NEXTAUTH: NextAuthClientConfig, __NEXTAUTH: AuthClientConfig,
logger: LoggerInstance, logger: LoggerInstance,
{ ctx, req = ctx?.req }: CtxOrReq = {} { ctx, req = ctx?.req }: CtxOrReq = {}
): Promise<T | null> { ): Promise<T | null> {
@@ -50,7 +50,7 @@ export async function fetchData<T = any>(
} }
} }
export function apiBaseUrl(__NEXTAUTH: NextAuthClientConfig) { export function apiBaseUrl(__NEXTAUTH: AuthClientConfig) {
if (typeof window === "undefined") { if (typeof window === "undefined") {
// Return absolute path when called server side // Return absolute path when called server side
return `${__NEXTAUTH.baseUrlServer}${__NEXTAUTH.basePathServer}` return `${__NEXTAUTH.baseUrlServer}${__NEXTAUTH.basePathServer}`

View File

@@ -72,6 +72,16 @@ export class InvalidCallbackUrl extends UnknownError {
code = "INVALID_CALLBACK_URL_ERROR" code = "INVALID_CALLBACK_URL_ERROR"
} }
export class UnknownAction extends UnknownError {
name = "UnknownAction"
code = "UNKNOWN_ACTION_ERROR"
}
export class UntrustedHost extends UnknownError {
name = "UntrustedHost"
code = "UNTRUST_HOST_ERROR"
}
type Method = (...args: any[]) => Promise<any> type Method = (...args: any[]) => Promise<any>
export function upperSnake(s: string) { export function upperSnake(s: string) {

View File

@@ -1,97 +1,55 @@
import logger, { setLogger } from "../utils/logger" import logger, { setLogger } from "../utils/logger"
import { detectHost } from "../utils/detect-host" import { toInternalRequest, toResponse } from "../utils/web"
import * as routes from "./routes"
import renderPage from "./pages"
import { init } from "./init" import { init } from "./init"
import { assertConfig } from "./lib/assert" import { assertConfig } from "./lib/assert"
import { SessionStore } from "./lib/cookie" import { SessionStore } from "./lib/cookie"
import renderPage from "./pages"
import * as routes from "./routes"
import type { NextAuthAction, NextAuthOptions } from "./types" import { UntrustedHost } from "./errors"
import type { Cookie } from "./lib/cookie" import type { Cookie } from "./lib/cookie"
import type { ErrorType } from "./pages/error" import type { ErrorType } from "./pages/error"
import { parse as parseCookie } from "cookie" import type { AuthAction, AuthOptions } from "./types"
/** @internal */
export interface RequestInternal { export interface RequestInternal {
/** @default "http://localhost:3000" */ url: URL
host?: string /** @default "GET" */
method?: string method: string
cookies?: Partial<Record<string, string>> cookies?: Partial<Record<string, string>>
headers?: Record<string, any> headers?: Record<string, any>
query?: Record<string, any> query?: Record<string, any>
body?: Record<string, any> body?: Record<string, any>
action: NextAuthAction action: AuthAction
providerId?: string providerId?: string
error?: string error?: string
} }
export interface NextAuthHeader { /** @internal */
key: string export interface ResponseInternal<
value: string
}
export interface OutgoingResponse<
Body extends string | Record<string, any> | any[] = any Body extends string | Record<string, any> | any[] = any
> { > {
status?: number status?: number
headers?: NextAuthHeader[] headers?: Record<string, string>
body?: Body body?: Body
redirect?: string redirect?: string
cookies?: Cookie[] cookies?: Cookie[]
} }
export interface NextAuthHandlerParams { const configErrorMessage =
req: Request | RequestInternal "There is a problem with the server configuration. Check the server logs for more information."
options: NextAuthOptions
}
async function getBody(req: Request): Promise<Record<string, any> | undefined> { async function AuthHandlerInternal<
try {
return await req.json()
} catch {}
}
// TODO:
async function toInternalRequest(
req: RequestInternal | Request,
trustHost: boolean = false
): Promise<RequestInternal> {
if (req instanceof Request) {
const url = new URL(req.url)
// TODO: handle custom paths?
const nextauth = url.pathname.split("/").slice(3)
const headers = Object.fromEntries(req.headers)
const query: Record<string, any> = Object.fromEntries(url.searchParams)
query.nextauth = nextauth
return {
action: nextauth[0] as NextAuthAction,
method: req.method,
headers,
body: await getBody(req),
cookies: parseCookie(req.headers.get("cookie") ?? ""),
providerId: nextauth[1],
error: url.searchParams.get("error") ?? nextauth[1],
host: detectHost(
trustHost,
headers["x-forwarded-host"] ?? headers.host,
"http://localhost:3000"
),
query,
}
}
return req
}
export async function NextAuthHandler<
Body extends string | Record<string, any> | any[] Body extends string | Record<string, any> | any[]
>(params: NextAuthHandlerParams): Promise<OutgoingResponse<Body>> { >(params: {
const { options: userOptions, req: incomingRequest } = params req: RequestInternal
options: AuthOptions
/** REVIEW: Is this the best way to skip parsing the body in Node.js? */
parsedBody?: any
}): Promise<ResponseInternal<Body>> {
const { options: authOptions, req } = params
const req = await toInternalRequest(incomingRequest, userOptions.trustHost) const assertionResult = assertConfig({ options: authOptions, req })
setLogger(userOptions.logger, userOptions.debug)
const assertionResult = assertConfig({ options: userOptions, req })
if (Array.isArray(assertionResult)) { if (Array.isArray(assertionResult)) {
assertionResult.forEach(logger.warn) assertionResult.forEach(logger.warn)
@@ -101,14 +59,13 @@ export async function NextAuthHandler<
const htmlPages = ["signin", "signout", "error", "verify-request"] const htmlPages = ["signin", "signout", "error", "verify-request"]
if (!htmlPages.includes(req.action) || req.method !== "GET") { if (!htmlPages.includes(req.action) || req.method !== "GET") {
const message = `There is a problem with the server configuration. Check the server logs for more information.`
return { return {
status: 500, status: 500,
headers: [{ key: "Content-Type", value: "application/json" }], headers: { "Content-Type": "application/json" },
body: { message } as any, body: { message: configErrorMessage } as any,
} }
} }
const { pages, theme } = userOptions const { pages, theme } = authOptions
const authOnErrorPage = const authOnErrorPage =
pages?.error && req.query?.callbackUrl?.startsWith(pages.error) pages?.error && req.query?.callbackUrl?.startsWith(pages.error)
@@ -131,13 +88,13 @@ export async function NextAuthHandler<
} }
} }
const { action, providerId, error, method = "GET" } = req const { action, providerId, error, method } = req
const { options, cookies } = await init({ const { options, cookies } = await init({
userOptions, authOptions,
action, action,
providerId, providerId,
host: req.host, url: req.url,
callbackUrl: req.body?.callbackUrl ?? req.query?.callbackUrl, callbackUrl: req.body?.callbackUrl ?? req.query?.callbackUrl,
csrfToken: req.body?.csrfToken, csrfToken: req.body?.csrfToken,
cookies: req.cookies, cookies: req.cookies,
@@ -159,11 +116,12 @@ export async function NextAuthHandler<
case "session": { case "session": {
const session = await routes.session({ options, sessionStore }) const session = await routes.session({ options, sessionStore })
if (session.cookies) cookies.push(...session.cookies) if (session.cookies) cookies.push(...session.cookies)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return { ...session, cookies } as any return { ...session, cookies } as any
} }
case "csrf": case "csrf":
return { return {
headers: [{ key: "Content-Type", value: "application/json" }], headers: { "Content-Type": "application/json" },
body: { csrfToken: options.csrfToken } as any, body: { csrfToken: options.csrfToken } as any,
cookies, cookies,
} }
@@ -280,7 +238,7 @@ export async function NextAuthHandler<
} }
break break
case "_log": case "_log":
if (userOptions.logger) { if (authOptions.logger) {
try { try {
const { code, level, ...metadata } = req.body ?? {} const { code, level, ...metadata } = req.body ?? {}
logger[level](code, metadata) logger[level](code, metadata)
@@ -299,3 +257,51 @@ export async function NextAuthHandler<
body: `Error: This action with HTTP ${method} is not supported by NextAuth.js` as any, body: `Error: This action with HTTP ${method} is not supported by NextAuth.js` as any,
} }
} }
/**
* The core functionality of `next-auth`.
* It receives a standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
* and returns a standard [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
*/
export async function AuthHandler(
request: Request,
options: AuthOptions
): Promise<Response> {
setLogger(options.logger, options.debug)
if (!options.trustHost) {
const error = new UntrustedHost(
`Host must be trusted. URL was: ${request.url}`
)
logger.error(error.code, error)
return new Response(JSON.stringify({ message: configErrorMessage }), {
status: 500,
headers: { "Content-Type": "application/json" },
})
}
const req = await toInternalRequest(request)
if (req instanceof Error) {
logger.error((req as any).code, req)
return new Response(
`Error: This action with HTTP ${request.method} is not supported.`,
{ status: 400 }
)
}
const internalResponse = await AuthHandlerInternal({ req, options })
const response = await toResponse(internalResponse)
// If the request expects a return URL, send it as JSON
// instead of doing an actual redirect.
const redirect = response.headers.get("Location")
if (request.headers.has("X-Auth-Return-Redirect") && redirect) {
response.headers.delete("Location")
response.headers.set("Content-Type", "application/json")
return new Response(JSON.stringify({ url: redirect }), {
headers: response.headers,
})
}
return response
}

View File

@@ -1,7 +1,6 @@
import { randomBytes, randomUUID } from "crypto" import { randomBytes, randomUUID } from "crypto"
import { NextAuthOptions } from ".." import { AuthOptions } from ".."
import logger from "../utils/logger" import logger from "../utils/logger"
import parseUrl from "../utils/parse-url"
import { adapterErrorHandler, eventsErrorHandler } from "./errors" import { adapterErrorHandler, eventsErrorHandler } from "./errors"
import parseProviders from "./lib/providers" import parseProviders from "./lib/providers"
import { createSecret } from "./lib/utils" import { createSecret } from "./lib/utils"
@@ -13,10 +12,11 @@ import { createCallbackUrl } from "./lib/callback-url"
import { RequestInternal } from "." import { RequestInternal } from "."
import type { InternalOptions } from "./types" import type { InternalOptions } from "./types"
import parseUrl from "../utils/parse-url"
interface InitParams { interface InitParams {
host?: string url: URL
userOptions: NextAuthOptions authOptions: AuthOptions
providerId?: string providerId?: string
action: InternalOptions["action"] action: InternalOptions["action"]
/** Callback URL value extracted from the incoming request. */ /** Callback URL value extracted from the incoming request. */
@@ -30,10 +30,10 @@ interface InitParams {
/** Initialize all internal options and cookies. */ /** Initialize all internal options and cookies. */
export async function init({ export async function init({
userOptions, authOptions,
providerId, providerId,
action, action,
host, url: reqUrl,
cookies: reqCookies, cookies: reqCookies,
callbackUrl: reqCallbackUrl, callbackUrl: reqCallbackUrl,
csrfToken: reqCsrfToken, csrfToken: reqCsrfToken,
@@ -42,12 +42,17 @@ export async function init({
options: InternalOptions options: InternalOptions
cookies: cookie.Cookie[] cookies: cookie.Cookie[]
}> { }> {
const url = parseUrl(host) // TODO: move this to web.ts
const parsed = parseUrl(
reqUrl.origin +
reqUrl.pathname.replace(`/${action}`, "").replace(`/${providerId}`, "")
)
const url = new URL(parsed.toString())
const secret = createSecret({ userOptions, url }) const secret = createSecret({ authOptions, url })
const { providers, provider } = parseProviders({ const { providers, provider } = parseProviders({
providers: userOptions.providers, providers: authOptions.providers,
url, url,
providerId, providerId,
}) })
@@ -66,7 +71,7 @@ export async function init({
buttonText: "", buttonText: "",
}, },
// Custom options override defaults // Custom options override defaults
...userOptions, ...authOptions,
// These computed settings can have values in userOptions but we override them // These computed settings can have values in userOptions but we override them
// and are request-specific. // and are request-specific.
url, url,
@@ -75,24 +80,24 @@ export async function init({
provider, provider,
cookies: { cookies: {
...cookie.defaultCookies( ...cookie.defaultCookies(
userOptions.useSecureCookies ?? url.base.startsWith("https://") authOptions.useSecureCookies ?? url.protocol === "https:"
), ),
// Allow user cookie options to override any cookie settings above // Allow user cookie options to override any cookie settings above
...userOptions.cookies, ...authOptions.cookies,
}, },
secret, secret,
providers, providers,
// Session options // Session options
session: { session: {
// If no adapter specified, force use of JSON Web Tokens (stateless) // If no adapter specified, force use of JSON Web Tokens (stateless)
strategy: userOptions.adapter ? "database" : "jwt", strategy: authOptions.adapter ? "database" : "jwt",
maxAge, maxAge,
updateAge: 24 * 60 * 60, updateAge: 24 * 60 * 60,
generateSessionToken: () => { generateSessionToken: () => {
// Use `randomUUID` if available. (Node 15.6+) // Use `randomUUID` if available. (Node 15.6+)
return randomUUID?.() ?? randomBytes(32).toString("hex") return randomUUID?.() ?? randomBytes(32).toString("hex")
}, },
...userOptions.session, ...authOptions.session,
}, },
// JWT options // JWT options
jwt: { jwt: {
@@ -100,13 +105,13 @@ export async function init({
maxAge, // same as session maxAge, maxAge, // same as session maxAge,
encode: jwt.encode, encode: jwt.encode,
decode: jwt.decode, decode: jwt.decode,
...userOptions.jwt, ...authOptions.jwt,
}, },
// Event messages // Event messages
events: eventsErrorHandler(userOptions.events ?? {}, logger), events: eventsErrorHandler(authOptions.events ?? {}, logger),
adapter: adapterErrorHandler(userOptions.adapter, logger), adapter: adapterErrorHandler(authOptions.adapter, logger),
// Callback functions // Callback functions
callbacks: { ...defaultCallbacks, ...userOptions.callbacks }, callbacks: { ...defaultCallbacks, ...authOptions.callbacks },
logger, logger,
callbackUrl: url.origin, callbackUrl: url.origin,
} }

View File

@@ -7,12 +7,11 @@ import {
InvalidCallbackUrl, InvalidCallbackUrl,
MissingAdapterMethods, MissingAdapterMethods,
} from "../errors" } from "../errors"
import parseUrl from "../../utils/parse-url"
import { defaultCookies } from "./cookie" import { defaultCookies } from "./cookie"
import type { RequestInternal } from ".." import type { RequestInternal } from ".."
import type { WarningCode } from "../../utils/logger" import type { WarningCode } from "../../utils/logger"
import type { NextAuthOptions } from "../types" import type { AuthOptions } from "../types"
type ConfigError = type ConfigError =
| MissingAPIRoute | MissingAPIRoute
@@ -40,15 +39,15 @@ function isValidHttpUrl(url: string, baseUrl: string) {
* REVIEW: Make some of these and corresponding docs less Next.js specific? * REVIEW: Make some of these and corresponding docs less Next.js specific?
*/ */
export function assertConfig(params: { export function assertConfig(params: {
options: NextAuthOptions options: AuthOptions
req: RequestInternal req: RequestInternal
}): ConfigError | WarningCode[] { }): ConfigError | WarningCode[] {
const { options, req } = params const { options, req } = params
const { url } = req
const warnings: WarningCode[] = [] const warnings: WarningCode[] = []
if (!warned) { if (!warned) {
if (!req.host) warnings.push("NEXTAUTH_URL") if (!url.origin) warnings.push("NEXTAUTH_URL")
// TODO: Make this throw an error in next major. This will also get rid of `NODE_ENV` // TODO: Make this throw an error in next major. This will also get rid of `NODE_ENV`
if (!options.secret && process.env.NODE_ENV !== "production") if (!options.secret && process.env.NODE_ENV !== "production")
@@ -70,21 +69,19 @@ export function assertConfig(params: {
const callbackUrlParam = req.query?.callbackUrl as string | undefined const callbackUrlParam = req.query?.callbackUrl as string | undefined
const url = parseUrl(req.host) if (callbackUrlParam && !isValidHttpUrl(callbackUrlParam, url.origin)) {
if (callbackUrlParam && !isValidHttpUrl(callbackUrlParam, url.base)) {
return new InvalidCallbackUrl( return new InvalidCallbackUrl(
`Invalid callback URL. Received: ${callbackUrlParam}` `Invalid callback URL. Received: ${callbackUrlParam}`
) )
} }
const { callbackUrl: defaultCallbackUrl } = defaultCookies( const { callbackUrl: defaultCallbackUrl } = defaultCookies(
options.useSecureCookies ?? url.base.startsWith("https://") options.useSecureCookies ?? url.protocol === "https://"
) )
const callbackUrlCookie = const callbackUrlCookie =
req.cookies?.[options.cookies?.callbackUrl?.name ?? defaultCallbackUrl.name] req.cookies?.[options.cookies?.callbackUrl?.name ?? defaultCallbackUrl.name]
if (callbackUrlCookie && !isValidHttpUrl(callbackUrlCookie, url.base)) { if (callbackUrlCookie && !isValidHttpUrl(callbackUrlCookie, url.origin)) {
return new InvalidCallbackUrl( return new InvalidCallbackUrl(
`Invalid callback URL. Received: ${callbackUrlCookie}` `Invalid callback URL. Received: ${callbackUrlCookie}`
) )

View File

@@ -2,11 +2,10 @@ import { merge } from "../../utils/merge"
import type { InternalProvider } from "../types" import type { InternalProvider } from "../types"
import type { import type {
InternalOAuthConfig, OAuthConfigInternal,
OAuthConfig, OAuthConfig,
Provider, Provider,
} from "../../providers" } from "../../providers"
import type { InternalUrl } from "../../utils/parse-url"
/** /**
* Adds `signinUrl` and `callbackUrl` to each provider * Adds `signinUrl` and `callbackUrl` to each provider
@@ -14,7 +13,7 @@ import type { InternalUrl } from "../../utils/parse-url"
*/ */
export default function parseProviders(params: { export default function parseProviders(params: {
providers: Provider[] providers: Provider[]
url: InternalUrl url: URL
providerId?: string providerId?: string
}): { }): {
providers: InternalProvider[] providers: InternalProvider[]
@@ -59,7 +58,7 @@ function normalizeOAuthOptions(
if (!oauthOptions) return if (!oauthOptions) return
const normalized = Object.entries(oauthOptions).reduce< const normalized = Object.entries(oauthOptions).reduce<
InternalOAuthConfig<Record<string, unknown>> OAuthConfigInternal<Record<string, unknown>>
>( >(
(acc, [key, value]) => { (acc, [key, value]) => {
if ( if (

View File

@@ -1,8 +1,7 @@
import { createHash } from "crypto" import { createHash } from "crypto"
import type { NextAuthOptions } from "../.." import type { AuthOptions } from "../.."
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { InternalUrl } from "../../utils/parse-url"
/** /**
* Takes a number in seconds and returns the date in the future. * Takes a number in seconds and returns the date in the future.
@@ -28,17 +27,14 @@ export function hashToken(token: string, options: InternalOptions<"email">) {
* If no secret option is specified then it creates one on the fly * If no secret option is specified then it creates one on the fly
* based on options passed here. If options contains unique data, such as * based on options passed here. If options contains unique data, such as
* OAuth provider secrets and database credentials it should be sufficent. If no secret provided in production, we throw an error. */ * OAuth provider secrets and database credentials it should be sufficent. If no secret provided in production, we throw an error. */
export function createSecret(params: { export function createSecret(params: { authOptions: AuthOptions; url: URL }) {
userOptions: NextAuthOptions const { authOptions, url } = params
url: InternalUrl
}) {
const { userOptions, url } = params
return ( return (
userOptions.secret ?? authOptions.secret ??
// TODO: Remove falling back to default secret, and error in dev if one isn't provided // TODO: Remove falling back to default secret, and error in dev if one isn't provided
createHash("sha256") createHash("sha256")
.update(JSON.stringify({ ...url, ...userOptions })) .update(JSON.stringify({ ...url, ...authOptions }))
.digest("hex") .digest("hex")
) )
} }

View File

@@ -1,5 +1,4 @@
import { Theme } from "../.." import { Theme } from "../.."
import { InternalUrl } from "../../utils/parse-url"
/** /**
* The following errors are passed as error query parameters to the default or overridden error page. * The following errors are passed as error query parameters to the default or overridden error page.
@@ -12,7 +11,7 @@ export type ErrorType =
| "verification" | "verification"
export interface ErrorProps { export interface ErrorProps {
url?: InternalUrl url?: URL
theme?: Theme theme?: Theme
error?: ErrorType error?: ErrorType
} }

View File

@@ -6,7 +6,7 @@ import ErrorPage from "./error"
import css from "../../css" import css from "../../css"
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { RequestInternal, OutgoingResponse } from ".." import type { RequestInternal, ResponseInternal } from ".."
import type { Cookie } from "../lib/cookie" import type { Cookie } from "../lib/cookie"
import type { ErrorType } from "./error" import type { ErrorType } from "./error"
@@ -27,11 +27,11 @@ type RenderPageParams = {
export default function renderPage(params: RenderPageParams) { export default function renderPage(params: RenderPageParams) {
const { url, theme, query, cookies } = params const { url, theme, query, cookies } = params
function send({ html, title, status }: any): OutgoingResponse { function send({ html, title, status }: any): ResponseInternal {
return { return {
cookies, cookies,
status, status,
headers: [{ key: "Content-Type", value: "text/html" }], headers: { "Content-Type": "text/html" },
body: `<!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"><style>${css()}</style><title>${title}</title></head><body class="__next-auth-theme-${ body: `<!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"><style>${css()}</style><title>${title}</title></head><body class="__next-auth-theme-${
theme?.colorScheme ?? "auto" theme?.colorScheme ?? "auto"
}"><div class="page">${renderToString(html)}</div></body></html>`, }"><div class="page">${renderToString(html)}</div></body></html>`,

View File

@@ -1,8 +1,7 @@
import { Theme } from "../.." import { Theme } from "../.."
import { InternalUrl } from "../../utils/parse-url"
export interface SignoutProps { export interface SignoutProps {
url: InternalUrl url: URL
csrfToken: string csrfToken: string
theme: Theme theme: Theme
} }

View File

@@ -4,7 +4,7 @@ import { hashToken } from "../lib/utils"
import getAdapterUserFromEmail from "../lib/email/getUserFromEmail" import getAdapterUserFromEmail from "../lib/email/getUserFromEmail"
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { RequestInternal, OutgoingResponse } from ".." import type { RequestInternal, ResponseInternal } from ".."
import type { Cookie, SessionStore } from "../lib/cookie" import type { Cookie, SessionStore } from "../lib/cookie"
import type { User } from "../.." import type { User } from "../.."
import type { AdapterSession } from "../../adapters" import type { AdapterSession } from "../../adapters"
@@ -18,7 +18,7 @@ export default async function callback(params: {
headers: RequestInternal["headers"] headers: RequestInternal["headers"]
cookies: RequestInternal["cookies"] cookies: RequestInternal["cookies"]
sessionStore: SessionStore sessionStore: SessionStore
}): Promise<OutgoingResponse> { }): Promise<ResponseInternal> {
const { options, query, body, method, headers, sessionStore } = params const { options, query, body, method, headers, sessionStore } = params
const { const {
provider, provider,

View File

@@ -1,4 +1,4 @@
import type { OutgoingResponse } from ".." import type { ResponseInternal } from ".."
import type { InternalProvider } from "../types" import type { InternalProvider } from "../types"
export interface PublicProvider { export interface PublicProvider {
@@ -16,9 +16,9 @@ export interface PublicProvider {
*/ */
export default function providers( export default function providers(
providers: InternalProvider[] providers: InternalProvider[]
): OutgoingResponse<Record<string, PublicProvider>> { ): ResponseInternal<Record<string, PublicProvider>> {
return { return {
headers: [{ key: "Content-Type", value: "application/json" }], headers: { "Content-Type": "application/json" },
body: providers.reduce<Record<string, PublicProvider>>( body: providers.reduce<Record<string, PublicProvider>>(
(acc, { id, name, type, signinUrl, callbackUrl }) => { (acc, { id, name, type, signinUrl, callbackUrl }) => {
acc[id] = { id, name, type, signinUrl, callbackUrl } acc[id] = { id, name, type, signinUrl, callbackUrl }

View File

@@ -2,7 +2,7 @@ import { fromDate } from "../lib/utils"
import type { Adapter } from "../../adapters" import type { Adapter } from "../../adapters"
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { OutgoingResponse } from ".." import type { ResponseInternal } from ".."
import type { Session } from "../.." import type { Session } from "../.."
import type { SessionStore } from "../lib/cookie" import type { SessionStore } from "../lib/cookie"
@@ -18,7 +18,7 @@ interface SessionParams {
export default async function session( export default async function session(
params: SessionParams params: SessionParams
): Promise<OutgoingResponse<Session | {}>> { ): Promise<ResponseInternal<Session | {}>> {
const { options, sessionStore } = params const { options, sessionStore } = params
const { const {
adapter, adapter,
@@ -29,9 +29,9 @@ export default async function session(
session: { strategy: sessionStrategy, maxAge: sessionMaxAge }, session: { strategy: sessionStrategy, maxAge: sessionMaxAge },
} = options } = options
const response: OutgoingResponse<Session | {}> = { const response: ResponseInternal<Session | {}> = {
body: {}, body: {},
headers: [{ key: "Content-Type", value: "application/json" }], headers: { "Content-Type": "application/json" },
cookies: [], cookies: [],
} }

View File

@@ -1,7 +1,7 @@
import getAuthorizationUrl from "../lib/oauth/authorization-url" import getAuthorizationUrl from "../lib/oauth/authorization-url"
import emailSignin from "../lib/email/signin" import emailSignin from "../lib/email/signin"
import getAdapterUserFromEmail from "../lib/email/getUserFromEmail" import getAdapterUserFromEmail from "../lib/email/getUserFromEmail"
import type { RequestInternal, OutgoingResponse } from ".." import type { RequestInternal, ResponseInternal } from ".."
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { Account } from "../.." import type { Account } from "../.."
@@ -10,7 +10,7 @@ export default async function signin(params: {
options: InternalOptions<"oauth" | "email"> options: InternalOptions<"oauth" | "email">
query: RequestInternal["query"] query: RequestInternal["query"]
body: RequestInternal["body"] body: RequestInternal["body"]
}): Promise<OutgoingResponse> { }): Promise<ResponseInternal> {
const { options, query, body } = params const { options, query, body } = params
const { url, callbacks, logger, provider } = options const { url, callbacks, logger, provider } = options

View File

@@ -1,13 +1,13 @@
import type { Adapter } from "../../adapters" import type { Adapter } from "../../adapters"
import type { InternalOptions } from "../types" import type { InternalOptions } from "../types"
import type { OutgoingResponse } from ".." import type { ResponseInternal } from ".."
import type { SessionStore } from "../lib/cookie" import type { SessionStore } from "../lib/cookie"
/** Handle requests to /api/auth/signout */ /** Handle requests to /api/auth/signout */
export default async function signout(params: { export default async function signout(params: {
options: InternalOptions options: InternalOptions
sessionStore: SessionStore sessionStore: SessionStore
}): Promise<OutgoingResponse> { }): Promise<ResponseInternal> {
const { options, sessionStore } = params const { options, sessionStore } = params
const { adapter, events, jwt, callbackUrl, logger, session } = options const { adapter, events, jwt, callbackUrl, logger, session } = options

View File

@@ -5,7 +5,7 @@ import type {
ProviderType, ProviderType,
EmailConfig, EmailConfig,
CredentialsConfig, CredentialsConfig,
InternalOAuthConfig, OAuthConfigInternal,
} from "../providers" } from "../providers"
import type { TokenSetParameters } from "openid-client" import type { TokenSetParameters } from "openid-client"
import type { JWT, JWTOptions } from "../jwt" import type { JWT, JWTOptions } from "../jwt"
@@ -14,8 +14,6 @@ import type { CookieSerializeOptions } from "cookie"
import type { NextApiRequest, NextApiResponse } from "next" import type { NextApiRequest, NextApiResponse } from "next"
import type { InternalUrl } from "../utils/parse-url"
export type Awaitable<T> = T | PromiseLike<T> export type Awaitable<T> = T | PromiseLike<T>
export type { LoggerInstance } export type { LoggerInstance }
@@ -25,7 +23,7 @@ export type { LoggerInstance }
* *
* [Documentation](https://next-auth.js.org/configuration/options#options) * [Documentation](https://next-auth.js.org/configuration/options#options)
*/ */
export interface NextAuthOptions { export interface AuthOptions {
/** /**
* An array of authentication providers for signing in * An array of authentication providers for signing in
* (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. * (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order.
@@ -210,7 +208,7 @@ export interface NextAuthOptions {
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options, * - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
* but **may have complex implications** or side effects. * but **may have complex implications** or side effects.
* You should **try to avoid using advanced options** unless you are very comfortable using them. * You should **try to avoid using advanced options** unless you are very comfortable using them.
* @default Boolean(process.env.AUTH_TRUST_HOST ?? process.env.VERCEL) * @default Boolean(process.env.NEXTAUTH_URL ?? process.env.AUTH_TRUST_HOST ?? process.env.VERCEL)
*/ */
trustHost?: boolean trustHost?: boolean
} }
@@ -501,7 +499,7 @@ export interface User extends DefaultUser {}
/** @internal */ /** @internal */
export type InternalProvider<T = ProviderType> = (T extends "oauth" export type InternalProvider<T = ProviderType> = (T extends "oauth"
? InternalOAuthConfig<any> ? OAuthConfigInternal<any>
: T extends "email" : T extends "email"
? EmailConfig ? EmailConfig
: T extends "credentials" : T extends "credentials"
@@ -511,7 +509,7 @@ export type InternalProvider<T = ProviderType> = (T extends "oauth"
callbackUrl: string callbackUrl: string
} }
export type NextAuthAction = export type AuthAction =
| "providers" | "providers"
| "session" | "session"
| "csrf" | "csrf"
@@ -528,12 +526,8 @@ export interface InternalOptions<
WithVerificationToken = TProviderType extends "email" ? true : false WithVerificationToken = TProviderType extends "email" ? true : false
> { > {
providers: InternalProvider[] providers: InternalProvider[]
/** url: URL
* Parsed from `NEXTAUTH_URL` or `x-forwarded-host` on Vercel. action: AuthAction
* @default "http://localhost:3000/api/auth"
*/
url: InternalUrl
action: NextAuthAction
provider: InternalProvider<TProviderType> provider: InternalProvider<TProviderType>
csrfToken?: string csrfToken?: string
csrfTokenVerified?: boolean csrfTokenVerified?: boolean

View File

@@ -1,6 +1,4 @@
export * from "./core/types" export * from "./core/types"
export type { AuthOptions as NextAuthOptions } from "./core/types"
export type { RequestInternal, OutgoingResponse } from "./core"
export * from "./next" export * from "./next"
export { default } from "./next" export { default } from "./next"

View File

@@ -94,7 +94,7 @@ export async function getToken<R extends boolean = false>(
const authorizationHeader = const authorizationHeader =
req.headers instanceof Headers req.headers instanceof Headers
? req.headers.get("authorization") ? req.headers.get("authorization")
: req.headers.authorization : req.headers?.authorization
if (!token && authorizationHeader?.split(" ")[0] === "Bearer") { if (!token && authorizationHeader?.split(" ")[0] === "Bearer") {
const urlEncodedToken = authorizationHeader.split(" ")[1] const urlEncodedToken = authorizationHeader.split(" ")[1]

View File

@@ -1,90 +1,74 @@
import { NextAuthHandler } from "../core" import { AuthHandler } from "../core"
import { detectHost } from "../utils/detect-host" import { getBody, getURL, setHeaders } from "../utils/node"
import { setCookie } from "./utils"
import type { import type {
GetServerSidePropsContext, GetServerSidePropsContext,
NextApiRequest, NextApiRequest,
NextApiResponse, NextApiResponse,
} from "next" } from "next"
import type { NextAuthOptions, Session } from ".." import type { AuthOptions, Session } from ".."
import type { import type {
CallbacksOptions, CallbacksOptions,
NextAuthAction,
NextAuthRequest, NextAuthRequest,
NextAuthResponse, NextAuthResponse,
} from "../core/types" } from "../core/types"
async function NextAuthNextHandler( async function NextAuthHandler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse, res: NextApiResponse,
options: NextAuthOptions options: AuthOptions
) { ) {
const { nextauth, ...query } = req.query const headers = new Headers(req.headers as any)
const url = getURL(req.url, headers)
if (url instanceof Error) {
if (process.env.NODE_ENV !== "production") throw url
const errorLogger = options.logger?.error ?? console.error
errorLogger("INVALID_URL", url)
res.status(400)
return res.json({
message:
"There is a problem with the server configuration. Check the server logs for more information.",
})
}
options.secret ??= options.jwt?.secret ?? process.env.NEXTAUTH_SECRET const request = new Request(url, {
options.trustHost ??= !!(process.env.AUTH_TRUST_HOST ?? process.env.VERCEL) headers,
const handler = await NextAuthHandler({
req: {
host: detectHost(
options.trustHost,
req.headers["x-forwarded-host"],
process.env.NEXTAUTH_URL ??
(process.env.NODE_ENV !== "production" && "http://localhost:3000")
),
body: req.body,
query,
cookies: req.cookies,
headers: req.headers,
method: req.method, method: req.method,
action: nextauth?.[0] as NextAuthAction, ...getBody(req),
providerId: nextauth?.[1],
error: (req.query.error as string | undefined) ?? nextauth?.[1],
},
options,
}) })
res.status(handler.status ?? 200) options.secret ??= options.jwt?.secret ?? process.env.NEXTAUTH_SECRET
options.trustHost ??= !!(
process.env.NEXTAUTH_URL ??
process.env.AUTH_TRUST_HOST ??
process.env.VERCEL ??
process.env.NODE_ENV !== "production"
)
handler.cookies?.forEach((cookie) => setCookie(res, cookie)) const response = await AuthHandler(request, options)
res.status(response.status)
setHeaders(response.headers, res)
handler.headers?.forEach((h) => res.setHeader(h.key, h.value)) return res.send(await response.text())
if (handler.redirect) {
// If the request expects a return URL, send it as JSON
// instead of doing an actual redirect.
if (req.body?.json !== "true") {
// Could chain. .end() when lowest target is Node 14
// https://github.com/nodejs/node/issues/33148
res.status(302).setHeader("Location", handler.redirect)
return res.end()
}
return res.json({ url: handler.redirect })
} }
return res.send(handler.body) function NextAuth(options: AuthOptions): any
}
function NextAuth(options: NextAuthOptions): any
function NextAuth( function NextAuth(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse, res: NextApiResponse,
options: NextAuthOptions options: AuthOptions
): any ): any
/** The main entry point to next-auth */ /** The main entry point to next-auth */
function NextAuth( function NextAuth(
...args: ...args: [AuthOptions] | [NextApiRequest, NextApiResponse, AuthOptions]
| [NextAuthOptions]
| [NextApiRequest, NextApiResponse, NextAuthOptions]
) { ) {
if (args.length === 1) { if (args.length === 1) {
return async (req: NextAuthRequest, res: NextAuthResponse) => return async (req: NextAuthRequest, res: NextAuthResponse) =>
await NextAuthNextHandler(req, res, args[0]) await NextAuthHandler(req, res, args[0])
} }
return NextAuthNextHandler(args[0], args[1], args[2]) return NextAuthHandler(args[0], args[1], args[2])
} }
export default NextAuth export default NextAuth
@@ -92,8 +76,8 @@ export default NextAuth
let experimentalWarningShown = false let experimentalWarningShown = false
let experimentalRSCWarningShown = false let experimentalRSCWarningShown = false
type GetServerSessionOptions = Partial<Omit<NextAuthOptions, "callbacks">> & { type GetServerSessionOptions = Partial<Omit<AuthOptions, "callbacks">> & {
callbacks?: Omit<NextAuthOptions['callbacks'], "session"> & { callbacks?: Omit<AuthOptions["callbacks"], "session"> & {
session?: (...args: Parameters<CallbacksOptions["session"]>) => any session?: (...args: Parameters<CallbacksOptions["session"]>) => any
} }
} }
@@ -135,7 +119,7 @@ export async function unstable_getServerSession<
experimentalRSCWarningShown = true experimentalRSCWarningShown = true
} }
let req, res, options: NextAuthOptions let req, res, options: AuthOptions
if (isRSC) { if (isRSC) {
options = Object.assign({}, args[0], { providers: [] }) options = Object.assign({}, args[0], { providers: [] })
@@ -153,50 +137,42 @@ export async function unstable_getServerSession<
} else { } else {
req = args[0] req = args[0]
res = args[1] res = args[1]
options = Object.assign(args[2], { providers: [] }) options = Object.assign({}, args[2], { providers: [] })
} }
const url = getURL("/api/auth/session", new Headers(req.headers))
if (url instanceof Error) {
if (process.env.NODE_ENV !== "production") throw url
const errorLogger = options.logger?.error ?? console.error
errorLogger("INVALID_URL", url)
res.status(400)
return res.json({
message:
"There is a problem with the server configuration. Check the server logs for more information.",
})
}
const request = new Request(url, { headers: new Headers(req.headers) })
options.secret ??= process.env.NEXTAUTH_SECRET options.secret ??= process.env.NEXTAUTH_SECRET
options.trustHost ??= !!(process.env.AUTH_TRUST_HOST ?? process.env.VERCEL) options.trustHost = true
const response = await AuthHandler(request, options)
const session = await NextAuthHandler<Session | {} | string>({ const { status = 200, headers } = response
options,
req: {
host: detectHost(
options.trustHost,
req.headers["x-forwarded-host"],
process.env.NEXTAUTH_URL ??
(process.env.NODE_ENV !== "production" && "http://localhost:3000")
),
action: "session",
method: "GET",
cookies: req.cookies,
headers: req.headers,
},
})
const { body, cookies, status = 200 } = session setHeaders(headers, res)
cookies?.forEach((cookie) => setCookie(res, cookie)) // This would otherwise break rendering
// with `getServerSideProps` that needs to always return HTML
res.removeHeader?.("Content-Type")
const data = await response.json()
if (!data || !Object.keys(data).length) return null
if (body && typeof body !== "string" && Object.keys(body).length) {
if (status === 200) { if (status === 200) {
// @ts-expect-error if (isRSC) delete data.expires
if (isRSC) delete body.expires return data as R
return body as R
}
throw new Error((body as any).message)
}
return null
}
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface ProcessEnv {
NEXTAUTH_URL?: string
VERCEL?: "1"
}
} }
throw new Error(data.message)
} }

View File

@@ -1,12 +1,12 @@
import type { NextMiddleware, NextFetchEvent } from "next/server" import type { NextMiddleware, NextFetchEvent } from "next/server"
import type { Awaitable, CookieOption, NextAuthOptions } from ".." import type { Awaitable, CookieOption, AuthOptions } from ".."
import type { JWT, JWTOptions } from "../jwt" import type { JWT, JWTOptions } from "../jwt"
import { NextResponse, NextRequest } from "next/server" import { NextResponse, NextRequest } from "next/server"
import { getToken } from "../jwt" import { getToken } from "../jwt"
import parseUrl from "../utils/parse-url" import parseUrl from "../utils/parse-url"
import { detectHost } from "../utils/detect-host" import { detectHost } from "../utils/web"
type AuthorizedCallback = (params: { type AuthorizedCallback = (params: {
token: JWT | null token: JWT | null
@@ -21,7 +21,7 @@ export interface NextAuthMiddlewareOptions {
* --- * ---
* [Documentation](https://next-auth.js.org/configuration/pages) * [Documentation](https://next-auth.js.org/configuration/pages)
*/ */
pages?: NextAuthOptions["pages"] pages?: AuthOptions["pages"]
/** /**
* You can override the default cookie names and options for any of the cookies * You can override the default cookie names and options for any of the cookies
@@ -39,7 +39,7 @@ export interface NextAuthMiddlewareOptions {
*/ */
cookies?: Partial< cookies?: Partial<
Record< Record<
keyof Pick<keyof NextAuthOptions["cookies"], "sessionToken">, keyof Pick<keyof AuthOptions["cookies"], "sessionToken">,
Omit<CookieOption, "options"> Omit<CookieOption, "options">
> >
> >
@@ -57,7 +57,7 @@ export interface NextAuthMiddlewareOptions {
* Callback that receives the user's JWT payload * Callback that receives the user's JWT payload
* and returns `true` to allow the user to continue. * and returns `true` to allow the user to continue.
* *
* This is similar to the `signIn` callback in `NextAuthOptions`. * This is similar to the `signIn` callback in `AuthOptions`.
* *
* If it returns `false`, the user is redirected to the sign-in page instead * If it returns `false`, the user is redirected to the sign-in page instead
* *
@@ -90,7 +90,7 @@ export interface NextAuthMiddlewareOptions {
* The same `secret` used in the `NextAuth` configuration. * The same `secret` used in the `NextAuth` configuration.
* Defaults to the `NEXTAUTH_SECRET` environment variable. * Defaults to the `NEXTAUTH_SECRET` environment variable.
*/ */
secret?: NextAuthOptions["secret"] secret?: AuthOptions["secret"]
/** /**
* If set to `true`, NextAuth.js will use either the `x-forwarded-host` or `host` headers, * If set to `true`, NextAuth.js will use either the `x-forwarded-host` or `host` headers,
* instead of `NEXTAUTH_URL` * instead of `NEXTAUTH_URL`
@@ -100,34 +100,33 @@ export interface NextAuthMiddlewareOptions {
* You should **try to avoid using advanced options** unless you are very comfortable using them. * You should **try to avoid using advanced options** unless you are very comfortable using them.
* @default Boolean(process.env.VERCEL ?? process.env.AUTH_TRUST_HOST) * @default Boolean(process.env.VERCEL ?? process.env.AUTH_TRUST_HOST)
*/ */
trustHost?: NextAuthOptions["trustHost"] trustHost?: AuthOptions["trustHost"]
} }
// TODO: `NextMiddleware` should allow returning `void`
// Simplify when https://github.com/vercel/next.js/pull/38625 is merged.
type NextMiddlewareResult = ReturnType<NextMiddleware> | void // eslint-disable-line @typescript-eslint/no-invalid-void-type
async function handleMiddleware( async function handleMiddleware(
req: NextRequest, req: NextRequest,
options: NextAuthMiddlewareOptions | undefined = {}, options: NextAuthMiddlewareOptions | undefined = {},
onSuccess?: (token: JWT | null) => Promise<NextMiddlewareResult> onSuccess?: (token: JWT | null) => ReturnType<NextMiddleware>
) { ) {
const { pathname, search, origin, basePath } = req.nextUrl const { pathname, search, origin, basePath } = req.nextUrl
const signInPage = options?.pages?.signIn ?? "/api/auth/signin" const signInPage = options?.pages?.signIn ?? "/api/auth/signin"
const errorPage = options?.pages?.error ?? "/api/auth/error" const errorPage = options?.pages?.error ?? "/api/auth/error"
options.trustHost = Boolean( options.trustHost ??= !!(
options.trustHost ?? process.env.VERCEL ?? process.env.AUTH_TRUST_HOST process.env.NEXTAUTH_URL ??
process.env.VERCEL ??
process.env.AUTH_TRUST_HOST
) )
const host = detectHost( const host = detectHost(
options.trustHost, options.trustHost,
req.headers.get("x-forwarded-host"), req.headers?.get("x-forwarded-host"),
process.env.NEXTAUTH_URL ?? process.env.NEXTAUTH_URL ??
(process.env.NODE_ENV !== "production" && "http://localhost:3000") (process.env.NODE_ENV !== "production" && "http://localhost:3000")
) )
const authPath = parseUrl(host).path const authPath = parseUrl(host).path
const publicPaths = ["/_next", "/favicon.ico"] const publicPaths = ["/_next", "/favicon.ico"]
// Avoid infinite redirects/invalid response // Avoid infinite redirects/invalid response
@@ -140,8 +139,8 @@ async function handleMiddleware(
return return
} }
const secret = options?.secret ?? process.env.NEXTAUTH_SECRET options.secret ??= process.env.NEXTAUTH_SECRET
if (!secret) { if (!options.secret) {
console.error( console.error(
`[next-auth][error][NO_SECRET]`, `[next-auth][error][NO_SECRET]`,
`\nhttps://next-auth.js.org/errors#no_secret` `\nhttps://next-auth.js.org/errors#no_secret`
@@ -155,9 +154,9 @@ async function handleMiddleware(
const token = await getToken({ const token = await getToken({
req, req,
decode: options?.jwt?.decode, decode: options.jwt?.decode,
cookieName: options?.cookies?.sessionToken?.name, cookieName: options?.cookies?.sessionToken?.name,
secret, secret: options.secret,
}) })
const isAuthorized = const isAuthorized =
@@ -182,7 +181,7 @@ export interface NextRequestWithAuth extends NextRequest {
export type NextMiddlewareWithAuth = ( export type NextMiddlewareWithAuth = (
request: NextRequestWithAuth, request: NextRequestWithAuth,
event: NextFetchEvent event: NextFetchEvent
) => NextMiddlewareResult | Promise<NextMiddlewareResult> ) => ReturnType<NextMiddleware>
export type WithAuthArgs = export type WithAuthArgs =
| [NextRequestWithAuth] | [NextRequestWithAuth]

View File

@@ -1,15 +0,0 @@
import { serialize } from "cookie"
import { Cookie } from "../core/lib/cookie"
export function setCookie(res, cookie: Cookie) {
// Preserve any existing cookies that have already been set in the same session
let setCookieHeader = res.getHeader("Set-Cookie") ?? []
// If not an array (i.e. a string with a single cookie) convert it into an array
if (!Array.isArray(setCookieHeader)) {
setCookieHeader = [setCookieHeader]
}
const { name, value, options } = cookie
const cookieHeader = serialize(name, value, options)
setCookieHeader.push(cookieHeader)
res.setHeader("Set-Cookie", setCookieHeader)
}

View File

@@ -160,7 +160,7 @@ export interface OAuthConfig<P> extends CommonProviderOptions, PartialIssuer {
} }
/** @internal */ /** @internal */
export interface InternalOAuthConfig<P> export interface OAuthConfigInternal<P>
extends Omit<OAuthConfig<P>, "authorization" | "token" | "userinfo"> { extends Omit<OAuthConfig<P>, "authorization" | "token" | "userinfo"> {
authorization?: AuthorizationEndpointHandler authorization?: AuthorizationEndpointHandler
token?: TokenEndpointHandler token?: TokenEndpointHandler

View File

@@ -18,7 +18,7 @@ import {
apiBaseUrl, apiBaseUrl,
fetchData, fetchData,
now, now,
NextAuthClientConfig, AuthClientConfig,
} from "../client/_utils" } from "../client/_utils"
import type { import type {
@@ -46,7 +46,7 @@ export * from "./types"
// relative URLs are valid in that context and so defaults to empty. // relative URLs are valid in that context and so defaults to empty.
// 2. When invoked server side the value is picked up from an environment // 2. When invoked server side the value is picked up from an environment
// variable and defaults to 'http://localhost:3000'. // variable and defaults to 'http://localhost:3000'.
const __NEXTAUTH: NextAuthClientConfig = { const __NEXTAUTH: AuthClientConfig = {
baseUrl: parseUrl(process.env.NEXTAUTH_URL ?? process.env.VERCEL_URL).origin, baseUrl: parseUrl(process.env.NEXTAUTH_URL ?? process.env.VERCEL_URL).origin,
basePath: parseUrl(process.env.NEXTAUTH_URL).path, basePath: parseUrl(process.env.NEXTAUTH_URL).path,
baseUrlServer: parseUrl( baseUrlServer: parseUrl(
@@ -241,13 +241,13 @@ export async function signIn<
method: "post", method: "post",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
}, },
// @ts-expect-error // @ts-expect-error
body: new URLSearchParams({ body: new URLSearchParams({
...options, ...options,
csrfToken: await getCsrfToken(), csrfToken: await getCsrfToken(),
callbackUrl, callbackUrl,
json: true,
}), }),
}) })
@@ -291,12 +291,11 @@ export async function signOut<R extends boolean = true>(
method: "post", method: "post",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
}, },
// @ts-expect-error
body: new URLSearchParams({ body: new URLSearchParams({
csrfToken: await getCsrfToken(), csrfToken: (await getCsrfToken()) ?? "",
callbackUrl, callbackUrl,
json: true,
}), }),
} }
const res = await fetch(`${baseUrl}/signout`, fetchOptions) const res = await fetch(`${baseUrl}/signout`, fetchOptions)

View File

@@ -1,12 +0,0 @@
/** Extract the host from the environment */
export function detectHost(
trusted: boolean,
forwardedValue: string | string[] | undefined | null,
defaultValue: string | false
): string | undefined {
if (trusted && forwardedValue) {
return Array.isArray(forwardedValue) ? forwardedValue[0] : forwardedValue
}
return defaultValue || undefined
}

View File

@@ -0,0 +1,161 @@
import type { IncomingMessage, ServerResponse } from "http"
import type { GetServerSidePropsContext, NextApiRequest } from "next"
export function setCookie(res, value: string) {
// Preserve any existing cookies that have already been set in the same session
let setCookieHeader = res.getHeader("Set-Cookie") ?? []
// If not an array (i.e. a string with a single cookie) convert it into an array
if (!Array.isArray(setCookieHeader)) {
setCookieHeader = [setCookieHeader]
}
setCookieHeader.push(value)
res.setHeader("Set-Cookie", setCookieHeader)
}
export function getBody(
req: IncomingMessage | NextApiRequest | GetServerSidePropsContext["req"]
) {
if (!("body" in req) || !req.body || req.method !== "POST") {
return
}
if (req.body instanceof ReadableStream) {
return { body: req.body }
}
return { body: JSON.stringify(req.body) }
}
/**
* Extract the full request URL from the environment.
* NOTE: It does not verify if the host should be trusted.
*/
export function getURL(url: string | undefined, headers: Headers): URL | Error {
try {
if (!url) throw new Error("Missing url")
if (process.env.NEXTAUTH_URL) {
const base = new URL(process.env.NEXTAUTH_URL)
if (!["http:", "https:"].includes(base.protocol)) {
throw new Error("Invalid protocol")
}
const hasCustomPath = base.pathname !== "/"
if (hasCustomPath) {
const apiAuthRe = /\/api\/auth\/?$/
const basePathname = base.pathname.match(apiAuthRe)
? base.pathname.replace(apiAuthRe, "")
: base.pathname
return new URL(basePathname.replace(/\/$/, "") + url, base.origin)
}
return new URL(url, base)
}
const proto =
headers.get("x-forwarded-proto") ??
(process.env.NODE_ENV !== "production" ? "http" : "https")
const host = headers.get("x-forwarded-host") ?? headers.get("host")
if (!["http", "https"].includes(proto)) throw new Error("Invalid protocol")
const origin = `${proto}://${host}`
if (!host) throw new Error("Missing host")
return new URL(url, origin)
} catch (error) {
return error as Error
}
}
/**
* Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
* that are within a single set-cookie field-value, such as in the Expires portion.
* This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
* Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
* Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
* Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
* @source https://github.com/nfriedly/set-cookie-parser/blob/3eab8b7d5d12c8ed87832532861c1a35520cf5b3/lib/set-cookie.js#L144
*/
function getSetCookies(cookiesString: string) {
if (typeof cookiesString !== "string") {
return []
}
const cookiesStrings: string[] = []
let pos = 0
let start
let ch
let lastComma: number
let nextStart
let cookiesSeparatorFound
function skipWhitespace() {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1
}
return pos < cookiesString.length
}
function notSpecialChar() {
ch = cookiesString.charAt(pos)
return ch !== "=" && ch !== ";" && ch !== ","
}
while (pos < cookiesString.length) {
start = pos
cookiesSeparatorFound = false
while (skipWhitespace()) {
ch = cookiesString.charAt(pos)
if (ch === ",") {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos
pos += 1
skipWhitespace()
nextStart = pos
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
// we found cookies separator
cookiesSeparatorFound = true
// pos is inside the next cookie, so back up and return it.
pos = nextStart
cookiesStrings.push(cookiesString.substring(start, lastComma))
start = pos
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1
}
} else {
pos += 1
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length))
}
}
return cookiesStrings
}
export function setHeaders(headers: Headers, res: ServerResponse) {
for (const [key, val] of headers.entries()) {
// See: https://github.com/whatwg/fetch/issues/973
const value = key === "set-cookie" ? getSetCookies(val) : val
res.setHeader(key, value)
}
}
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface ProcessEnv {
AUTH_TRUST_HOST?: string
NEXTAUTH_URL?: string
NEXTAUTH_SECRET?: string
VERCEL?: "1"
}
}
}

View File

@@ -11,11 +11,14 @@ export interface InternalUrl {
toString: () => string toString: () => string
} }
/** Returns an `URL` like object to make requests/redirects from server-side */ /**
export default function parseUrl(url?: string): InternalUrl { * TODO: Can we remove this?
* Returns an `URL` like object to make requests/redirects from server-side
*/
export default function parseUrl(url?: string | URL): InternalUrl {
const defaultUrl = new URL("http://localhost:3000/api/auth") const defaultUrl = new URL("http://localhost:3000/api/auth")
if (url && !url.startsWith("http")) { if (url && !url.toString().startsWith("http")) {
url = `https://${url}` url = `https://${url}`
} }

View File

@@ -0,0 +1,135 @@
import { serialize, parse as parseCookie } from "cookie"
import { UnknownAction } from "../core/errors"
import type { ResponseInternal, RequestInternal } from "../core"
import type { AuthAction } from "../core/types"
const decoder = new TextDecoder()
async function streamToString(stream): Promise<string> {
const chunks: Uint8Array[] = []
return await 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")))
})
}
async function readJSONBody(
body: ReadableStream | Buffer
): Promise<Record<string, any> | undefined> {
try {
if ("getReader" in body) {
const reader = body.getReader()
const bytes: number[] = []
while (true) {
const { value, done } = await reader.read()
if (done) break
bytes.push(...value)
}
const b = new Uint8Array(bytes)
return JSON.parse(decoder.decode(b))
}
// node-fetch
if (typeof Buffer !== "undefined" && Buffer.isBuffer(body)) {
return JSON.parse(body.toString("utf8"))
}
return JSON.parse(await streamToString(body))
} catch (e) {
console.error(e)
}
}
// prettier-ignore
const actions: AuthAction[] = [ "providers", "session", "csrf", "signin", "signout", "callback", "verify-request", "error", "_log" ]
export async function toInternalRequest(
req: Request
): Promise<RequestInternal | Error> {
try {
// TODO: .toString() should not inclide action and providerId
// see init.ts
const url = new URL(req.url.replace(/\/$/, ""))
const { pathname } = url
const action = actions.find((a) => pathname.includes(a))
if (!action) {
throw new UnknownAction("Cannot detect action.")
}
const providerIdOrAction = pathname.split("/").pop()
let providerId
if (
providerIdOrAction &&
!action.includes(providerIdOrAction) &&
["signin", "callback"].includes(action)
) {
providerId = providerIdOrAction
}
const cookieHeader = req.headers.get("cookie") ?? ""
return {
url,
action,
providerId,
method: req.method ?? "GET",
headers: Object.fromEntries(req.headers),
body: req.body ? await readJSONBody(req.body) : undefined,
cookies:
parseCookie(
Array.isArray(cookieHeader) ? cookieHeader.join(";") : cookieHeader
) ?? {},
error: url.searchParams.get("error") ?? undefined,
query: Object.fromEntries(url.searchParams),
}
} catch (error) {
return error
}
}
export function toResponse(res: ResponseInternal): Response {
const headers = new Headers(res.headers)
res.cookies?.forEach((cookie) => {
const { name, value, options } = cookie
const cookieHeader = serialize(name, value, options)
if (headers.has("Set-Cookie")) {
headers.append("Set-Cookie", cookieHeader)
} else {
headers.set("Set-Cookie", cookieHeader)
}
})
const body =
headers.get("content-type") === "application/json"
? JSON.stringify(res.body)
: res.body
const response = new Response(body, {
headers,
status: res.redirect ? 302 : res.status ?? 200,
})
if (res.redirect) {
response.headers.set("Location", res.redirect)
}
return response
}
// TODO: Remove
/** Extract the host from the environment */
export function detectHost(
trusted: boolean,
forwardedValue: string | string[] | undefined | null,
defaultValue: string | false
): string | undefined {
if (trusted && forwardedValue) {
return Array.isArray(forwardedValue) ? forwardedValue[0] : forwardedValue
}
return defaultValue || undefined
}

View File

@@ -4,12 +4,12 @@ import {
MissingAdapterMethods, MissingAdapterMethods,
MissingSecret, MissingSecret,
} from "../src/core/errors" } from "../src/core/errors"
import { handler } from "./lib" import { handler } from "./utils"
import EmailProvider from "../src/providers/email" import EmailProvider from "../src/providers/email"
it("Show error page if secret is not defined", async () => { it("Show error page if secret is not defined", async () => {
const { res, log } = await handler( const { res, log } = await handler(
{ providers: [], secret: undefined }, { providers: [], secret: undefined, trustHost: true },
{ prod: true } { prod: true }
) )
@@ -28,6 +28,7 @@ it("Show error page if adapter is missing functions when using with email", asyn
adapter: missingFunctionAdapter, adapter: missingFunctionAdapter,
providers: [EmailProvider({ sendVerificationRequest })], providers: [EmailProvider({ sendVerificationRequest })],
secret: "secret", secret: "secret",
trustHost: true,
}, },
{ prod: true } { prod: true }
) )
@@ -48,6 +49,7 @@ it("Show error page if adapter is not configured when using with email", async (
{ {
providers: [EmailProvider({ sendVerificationRequest })], providers: [EmailProvider({ sendVerificationRequest })],
secret: "secret", secret: "secret",
trustHost: true,
}, },
{ prod: true } { prod: true }
) )
@@ -64,7 +66,7 @@ it("Show error page if adapter is not configured when using with email", async (
it("Should show configuration error page on invalid `callbackUrl`", async () => { it("Should show configuration error page on invalid `callbackUrl`", async () => {
const { res, log } = await handler( const { res, log } = await handler(
{ providers: [] }, { providers: [], trustHost: true },
{ prod: true, params: { callbackUrl: "invalid-callback" } } { prod: true, params: { callbackUrl: "invalid-callback" } }
) )
@@ -80,7 +82,7 @@ it("Should show configuration error page on invalid `callbackUrl`", async () =>
it("Allow relative `callbackUrl`", async () => { it("Allow relative `callbackUrl`", async () => {
const { res, log } = await handler( const { res, log } = await handler(
{ providers: [] }, { providers: [], trustHost: true },
{ prod: true, params: { callbackUrl: "/callback" } } { prod: true, params: { callbackUrl: "/callback" } }
) )

View File

@@ -1,8 +1,9 @@
import { createCSRF, handler, mockAdapter } from "./lib" import { createCSRF, handler, mockAdapter } from "./utils"
import EmailProvider from "../src/providers/email" import EmailProvider from "../src/providers/email"
it("Send e-mail to the only address correctly", async () => { it("Send e-mail to the only address correctly", async () => {
const { secret, csrf } = await createCSRF() const { secret, csrf } = await createCSRF()
const sendVerificationRequest = jest.fn() const sendVerificationRequest = jest.fn()
const signIn = jest.fn(() => true) const signIn = jest.fn(() => true)
@@ -13,12 +14,13 @@ it("Send e-mail to the only address correctly", async () => {
providers: [EmailProvider({ sendVerificationRequest })], providers: [EmailProvider({ sendVerificationRequest })],
callbacks: { signIn }, callbacks: { signIn },
secret, secret,
trustHost: true,
}, },
{ {
path: "signin/email", path: "signin/email",
requestInit: { requestInit: {
method: "POST", method: "POST",
headers: { cookie: csrf.cookie }, headers: { cookie: csrf.cookie, "content-type": "application/json" },
body: JSON.stringify({ email: email, csrfToken: csrf.value }), body: JSON.stringify({ email: email, csrfToken: csrf.value }),
}, },
} }
@@ -53,12 +55,13 @@ it("Send e-mail to first address only", async () => {
providers: [EmailProvider({ sendVerificationRequest })], providers: [EmailProvider({ sendVerificationRequest })],
callbacks: { signIn }, callbacks: { signIn },
secret, secret,
trustHost: true,
}, },
{ {
path: "signin/email", path: "signin/email",
requestInit: { requestInit: {
method: "POST", method: "POST",
headers: { cookie: csrf.cookie }, headers: { cookie: csrf.cookie, "content-type": "application/json" },
body: JSON.stringify({ email: email, csrfToken: csrf.value }), body: JSON.stringify({ email: email, csrfToken: csrf.value }),
}, },
} }
@@ -93,12 +96,13 @@ it("Send e-mail to address with first domain", async () => {
providers: [EmailProvider({ sendVerificationRequest })], providers: [EmailProvider({ sendVerificationRequest })],
callbacks: { signIn }, callbacks: { signIn },
secret, secret,
trustHost: true,
}, },
{ {
path: "signin/email", path: "signin/email",
requestInit: { requestInit: {
method: "POST", method: "POST",
headers: { cookie: csrf.cookie }, headers: { cookie: csrf.cookie, "content-type": "application/json" },
body: JSON.stringify({ email: email, csrfToken: csrf.value }), body: JSON.stringify({ email: email, csrfToken: csrf.value }),
}, },
} }
@@ -139,12 +143,13 @@ it("Redirect to error page if multiple addresses aren't allowed", async () => {
}), }),
], ],
secret, secret,
trustHost: true,
}, },
{ {
path: "signin/email", path: "signin/email",
requestInit: { requestInit: {
method: "POST", method: "POST",
headers: { cookie: csrf.cookie }, headers: { cookie: csrf.cookie, "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
email: "email@email.com,email@email2.com", email: "email@email.com,email@email2.com",
csrfToken: csrf.value, csrfToken: csrf.value,
@@ -156,7 +161,6 @@ it("Redirect to error page if multiple addresses aren't allowed", async () => {
expect(signIn).toBeCalledTimes(0) expect(signIn).toBeCalledTimes(0)
expect(sendVerificationRequest).toBeCalledTimes(0) expect(sendVerificationRequest).toBeCalledTimes(0)
// @ts-expect-error
expect(log.error.mock.calls[0]).toEqual([ expect(log.error.mock.calls[0]).toEqual([
"SIGNIN_EMAIL_ERROR", "SIGNIN_EMAIL_ERROR",
{ error, providerId: "email" }, { error, providerId: "email" },

View File

@@ -1,7 +1,7 @@
import * as core from "../src/core" import * as core from "../src/core"
import { MissingSecret } from "../src/core/errors" import { MissingSecret } from "../src/core/errors"
import { unstable_getServerSession } from "../src/next" import { unstable_getServerSession } from "../src/next"
import { mockLogger } from "./lib" import { mockLogger } from "./utils"
const originalWarn = console.warn const originalWarn = console.warn
let logger = mockLogger() let logger = mockLogger()
@@ -83,9 +83,9 @@ describe("Return correct data", () => {
}) })
it("Should return null if there is no session", async () => { it("Should return null if there is no session", async () => {
const spy = jest.spyOn(core, "NextAuthHandler") const spy = jest.spyOn(core, "AuthHandler")
// @ts-expect-error // @ts-expect-error [Response.json](https://developer.mozilla.org/en-US/docs/Web/API/Response/json)
spy.mockReturnValue({ body: {} }) spy.mockReturnValue(Promise.resolve(Response.json(null)))
const session = await unstable_getServerSession(req, res, { const session = await unstable_getServerSession(req, res, {
providers: [], providers: [],
@@ -97,8 +97,7 @@ describe("Return correct data", () => {
}) })
it("Should return the session if one is found", async () => { it("Should return the session if one is found", async () => {
const mockedResponse = { const mockedBody = {
body: {
user: { user: {
name: "John Doe", name: "John Doe",
email: "test@example.com", email: "test@example.com",
@@ -106,12 +105,11 @@ describe("Return correct data", () => {
id: "1234", id: "1234",
}, },
expires: "", expires: "",
},
} }
const spy = jest.spyOn(core, "NextAuthHandler") const spy = jest.spyOn(core, "AuthHandler")
// @ts-expect-error // @ts-expect-error [Response.json](https://developer.mozilla.org/en-US/docs/Web/API/Response/json)
spy.mockReturnValue(mockedResponse) spy.mockReturnValue(Promise.resolve(Response.json(mockedBody)))
const session = await unstable_getServerSession(req, res, { const session = await unstable_getServerSession(req, res, {
providers: [], providers: [],
@@ -119,6 +117,6 @@ describe("Return correct data", () => {
secret: "secret", secret: "secret",
}) })
expect(session).toEqual(mockedResponse.body) expect(session).toEqual(mockedBody)
}) })
}) })

View File

@@ -0,0 +1,138 @@
import { getURL as getURLOriginal } from "../src/utils/node"
it("Should return error when missing url", () => {
expect(getURL(undefined, {})).toEqual(new Error("Missing url"))
})
it("Should return error when missing host", () => {
expect(getURL("/", {})).toEqual(new Error("Missing host"))
})
it("Should return error when invalid protocol", () => {
expect(
getURL("/", { host: "localhost", "x-forwarded-proto": "file" })
).toEqual(new Error("Invalid protocol"))
})
it("Should return error when invalid host", () => {
expect(getURL("/", { host: "/" })).toEqual(
new TypeError("Invalid base URL: http:///")
)
})
it("Should read host headers", () => {
expect(getURL("/api/auth/session", { host: "localhost" })).toBeURL(
"http://localhost/api/auth/session"
)
expect(
getURL("/custom/api/auth/session", { "x-forwarded-host": "localhost:3000" })
).toBeURL("http://localhost:3000/custom/api/auth/session")
// Prefer x-forwarded-host over host
expect(
getURL("/", { host: "localhost", "x-forwarded-host": "localhost:3000" })
).toBeURL("http://localhost:3000/")
})
it("Should read protocol headers", () => {
expect(
getURL("/", { host: "localhost", "x-forwarded-proto": "http" })
).toBeURL("http://localhost/")
})
describe("process.env.NEXTAUTH_URL", () => {
afterEach(() => delete process.env.NEXTAUTH_URL)
it("Should prefer over headers if present", () => {
process.env.NEXTAUTH_URL = "http://localhost:3000"
expect(getURL("/api/auth/session", { host: "localhost" })).toBeURL(
"http://localhost:3000/api/auth/session"
)
})
it("catch errors", () => {
process.env.NEXTAUTH_URL = "invald-url"
expect(getURL("/api/auth/session", {})).toEqual(
new TypeError("Invalid URL: invald-url")
)
process.env.NEXTAUTH_URL = "file://localhost"
expect(getURL("/api/auth/session", {})).toEqual(
new TypeError("Invalid protocol")
)
})
it("Supports custom base path", () => {
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/api/auth"
expect(getURL("/api/auth/session", {})).toBeURL(
"http://localhost:3000/custom/api/auth/session"
)
// With trailing slash
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/api/auth/"
expect(getURL("/api/auth/session", {})).toBeURL(
"http://localhost:3000/custom/api/auth/session"
)
// Multiple custom segments
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/path/api/auth"
expect(getURL("/api/auth/session", {})).toBeURL(
"http://localhost:3000/custom/path/api/auth/session"
)
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/path/api/auth/"
expect(getURL("/api/auth/session", {})).toBeURL(
"http://localhost:3000/custom/path/api/auth/session"
)
// No /api/auth
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/nextauth"
expect(getURL("/session", {})).toBeURL(
"http://localhost:3000/custom/nextauth/session"
)
// No /api/auth, with trailing slash
process.env.NEXTAUTH_URL = "http://localhost:3000/custom/nextauth/"
expect(getURL("/session", {})).toBeURL(
"http://localhost:3000/custom/nextauth/session"
)
})
})
// Utils
function getURL(
url: Parameters<typeof getURLOriginal>[0],
headers: HeadersInit
) {
return getURLOriginal(url, new Headers(headers))
}
expect.extend({
toBeURL(rec, exp) {
const r = rec.toString()
const e = exp.toString()
const printR = this.utils.printReceived
const printE = this.utils.printExpected
if (r === e) {
return {
message: () => `expected ${printE(e)} not to be ${printR(r)}`,
pass: true,
}
}
return {
message: () => `expected ${printE(e)}, got ${printR(r)}`,
pass: false,
}
},
})
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Matchers<R> {
toBeURL: (expected: string) => R
}
}
}

View File

@@ -1,68 +0,0 @@
import { createHash } from "crypto"
import { NextAuthHandler } from "../src/core"
import type { LoggerInstance, NextAuthOptions } from "../src"
import type { Adapter } from "../src/adapters"
export const mockLogger: () => LoggerInstance = () => ({
error: jest.fn(() => {}),
warn: jest.fn(() => {}),
debug: jest.fn(() => {}),
})
interface HandlerOptions {
prod?: boolean
path?: string
params?: URLSearchParams | Record<string, string>
requestInit?: RequestInit
}
export async function handler(
options: NextAuthOptions,
{ prod, path, params, requestInit }: HandlerOptions
) {
// @ts-expect-error
if (prod) process.env.NODE_ENV = "production"
const url = new URL(
`http://localhost/api/auth/${path ?? "signin"}?${new URLSearchParams(
params ?? {}
)}`
)
const req = new Request(url, { headers: { host: "" }, ...requestInit })
const logger = mockLogger()
const response = await NextAuthHandler({
req,
options: { secret: "secret", ...options, logger },
})
// @ts-expect-error
if (prod) process.env.NODE_ENV = "test"
return {
res: {
...response,
html:
response.headers?.[0].value === "text/html" ? response.body : undefined,
},
log: logger,
}
}
export function createCSRF() {
const secret = "secret"
const value = "csrf"
const token = createHash("sha256").update(`${value}${secret}`).digest("hex")
return {
secret,
csrf: { value, token, cookie: `next-auth.csrf-token=${value}|${token}` },
}
}
export function mockAdapter(): Adapter {
const adapter: Adapter = {
createVerificationToken: jest.fn(() => {}),
useVerificationToken: jest.fn(() => {}),
getUserByEmail: jest.fn(() => {}),
}
return adapter
}

View File

@@ -6,91 +6,64 @@ it("should not match pages as public paths", async () => {
pages: { signIn: "/", error: "/" }, pages: { signIn: "/", error: "/" },
secret: "secret", secret: "secret",
} }
const req = new NextRequest("http://127.0.0.1/protected/pathA", {
headers: { authorization: "" },
})
const handleMiddleware = withAuth(options) as NextMiddleware const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req, null as any)
expect(res).toBeDefined() const response = await handleMiddleware(
expect(res?.status).toBe(307) new NextRequest("http://127.0.0.1/protected/pathA"),
null as any
)
expect(response?.status).toBe(307)
expect(response?.headers.get("location")).toBe(
"http://localhost/?callbackUrl=%2Fprotected%2FpathA"
)
}) })
it("should not redirect on public paths", async () => { it("should not redirect on public paths", async () => {
const options: NextAuthMiddlewareOptions = { secret: "secret" } const options: NextAuthMiddlewareOptions = { secret: "secret" }
const req = new NextRequest("http://127.0.0.1/_next/foo", { const req = new NextRequest("http://127.0.0.1/_next/foo")
headers: { authorization: "" },
})
const handleMiddleware = withAuth(options) as NextMiddleware const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req, null as any) const res = await handleMiddleware(req, null as any)
expect(res).toBeUndefined() expect(res).toBeUndefined()
}) })
it("should redirect according to nextUrl basePath", async () => { it("should respect NextURL#basePath when redirecting", async () => {
const options: NextAuthMiddlewareOptions = { secret: "secret" } const options: NextAuthMiddlewareOptions = { secret: "secret" }
const handleMiddleware = withAuth(options) as NextMiddleware
const req = { const response1 = await handleMiddleware(
{
nextUrl: { nextUrl: {
pathname: "/protected/pathA", pathname: "/protected/pathA",
search: "", search: "",
origin: "http://127.0.0.1", origin: "http://127.0.0.1",
basePath: "/custom-base-path", basePath: "/custom-base-path",
}, },
headers: new Headers({ authorization: "" }), } as unknown as NextRequest,
} null as any
const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req as NextRequest, null as any)
expect(res).toBeDefined()
expect(res?.status).toEqual(307)
expect(res?.headers.get("location")).toContain(
"http://127.0.0.1/custom-base-path/api/auth/signin?callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA"
) )
}) expect(response1?.status).toEqual(307)
expect(response1?.headers.get("location")).toBe(
it("should redirect according to nextUrl basePath", async () => {
// given
const options: NextAuthMiddlewareOptions = { secret: "secret" }
const handleMiddleware = withAuth(options) as NextMiddleware
const req1 = {
nextUrl: {
pathname: "/protected/pathA",
search: "",
origin: "http://127.0.0.1",
basePath: "/custom-base-path",
},
headers: new Headers({ authorization: "" }),
}
// when
const res = await handleMiddleware(req1 as NextRequest, null as any)
// then
expect(res).toBeDefined()
expect(res?.status).toEqual(307)
expect(res?.headers.get("location")).toContain(
"http://127.0.0.1/custom-base-path/api/auth/signin?callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA" "http://127.0.0.1/custom-base-path/api/auth/signin?callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA"
) )
const req2 = { // Should not redirect when invoked on sign in page
const response2 = await handleMiddleware(
{
nextUrl: { nextUrl: {
pathname: "/api/auth/signin", pathname: "/api/auth/signin",
search: "callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA", searchParams: new URLSearchParams({
callbackUrl: "/custom-base-path/protected/pathA",
}),
origin: "http://127.0.0.1", origin: "http://127.0.0.1",
basePath: "/custom-base-path", basePath: "/custom-base-path",
}, },
headers: new Headers({ authorization: "" }), } as unknown as NextRequest,
}
// and when follow redirect
const resFromRedirectedUrl = await handleMiddleware(
req2 as NextRequest,
null as any null as any
) )
// then return sign in page expect(response2).toBeUndefined()
expect(resFromRedirectedUrl).toBeUndefined()
}) })

View File

@@ -0,0 +1,142 @@
import { nodeHandler } from "./utils"
it("Missing req.url throws in dev", async () => {
await expect(nodeHandler).rejects.toThrow(new Error("Missing url"))
})
const configErrorMessage =
"There is a problem with the server configuration. Check the server logs for more information."
it("Missing req.url returns config error in prod", async () => {
// @ts-expect-error
process.env.NODE_ENV = "production"
const { res, logger } = await nodeHandler()
expect(logger.error).toBeCalledTimes(1)
const error = new Error("Missing url")
expect(logger.error).toBeCalledWith("INVALID_URL", error)
expect(res.status).toBeCalledWith(400)
expect(res.json).toBeCalledWith({ message: configErrorMessage })
// @ts-expect-error
process.env.NODE_ENV = "test"
})
it("Missing host throws in dev", async () => {
await expect(
async () =>
await nodeHandler({
req: { query: { nextauth: ["session"] } },
})
).rejects.toThrow(Error)
})
it("Missing host config error in prod", async () => {
// @ts-expect-error
process.env.NODE_ENV = "production"
const { res, logger } = await nodeHandler({
req: { query: { nextauth: ["session"] } },
})
expect(res.status).toBeCalledWith(400)
expect(res.json).toBeCalledWith({ message: configErrorMessage })
expect(logger.error).toBeCalledWith("INVALID_URL", new Error("Missing url"))
// @ts-expect-error
process.env.NODE_ENV = "test"
})
it("Defined host throws 400 in production if not trusted", async () => {
// @ts-expect-error
process.env.NODE_ENV = "production"
const { res } = await nodeHandler({
req: { headers: { host: "http://localhost" } },
})
expect(res.status).toBeCalledWith(400)
// @ts-expect-error
process.env.NODE_ENV = "test"
})
it("Defined host throws 400 in production if trusted but invalid URL", async () => {
// @ts-expect-error
process.env.NODE_ENV = "production"
const { res } = await nodeHandler({
req: { headers: { host: "localhost" } },
options: { trustHost: true },
})
expect(res.status).toBeCalledWith(400)
// @ts-expect-error
process.env.NODE_ENV = "test"
})
it("Defined host does not throw in production if trusted and valid URL", async () => {
// @ts-expect-error
process.env.NODE_ENV = "production"
const { res } = await nodeHandler({
req: {
url: "/api/auth/session",
headers: { host: "http://localhost" },
},
options: { trustHost: true },
})
expect(res.status).toBeCalledWith(200)
expect(JSON.parse(res.send.mock.calls[0][0])).toEqual({})
// @ts-expect-error
process.env.NODE_ENV = "test"
})
it("Use process.env.NEXTAUTH_URL for host if present", async () => {
process.env.NEXTAUTH_URL = "http://localhost"
const { res } = await nodeHandler({
req: { url: "/api/auth/session" },
})
expect(res.status).toBeCalledWith(200)
expect(JSON.parse(res.send.mock.calls[0][0])).toEqual({})
})
it("Redirects if necessary", async () => {
process.env.NEXTAUTH_URL = "http://localhost"
const { res } = await nodeHandler({
req: {
method: "post",
url: "/api/auth/signin/github",
},
})
expect(res.status).toBeCalledWith(302)
expect(res.setHeader).toBeCalledWith("set-cookie", [
expect.stringMatching(
/next-auth.csrf-token=.*; Path=\/; HttpOnly; SameSite=Lax/
),
`next-auth.callback-url=${encodeURIComponent(
process.env.NEXTAUTH_URL
)}; Path=/; HttpOnly; SameSite=Lax`,
])
expect(res.setHeader).toBeCalledTimes(2)
expect(res.send).toBeCalledWith("")
})
it("Returns redirect if `X-Auth-Return-Redirect` header is present", async () => {
process.env.NEXTAUTH_URL = "http://localhost"
const { res } = await nodeHandler({
req: {
method: "post",
url: "/api/auth/signin/github",
headers: { "X-Auth-Return-Redirect": "1" },
},
})
expect(res.status).toBeCalledWith(200)
expect(res.setHeader).toBeCalledWith("content-type", "application/json")
expect(res.setHeader).toBeCalledWith("set-cookie", [
expect.stringMatching(
/next-auth.csrf-token=.*; Path=\/; HttpOnly; SameSite=Lax/
),
`next-auth.callback-url=${encodeURIComponent(
process.env.NEXTAUTH_URL
)}; Path=/; HttpOnly; SameSite=Lax`,
])
expect(res.setHeader).toBeCalledTimes(2)
expect(res.send).toBeCalledWith(
JSON.stringify({ url: "http://localhost/api/auth/signin?csrf=true" })
)
})

View File

@@ -1,5 +1,16 @@
import { mockLogger } from "./lib" import { mockLogger } from "./utils"
import type { InternalOptions, LoggerInstance, InternalProvider, CallbacksOptions, Account, Awaitable, Profile, Session, User, CookiesOptions } from "../src" import type {
InternalOptions,
LoggerInstance,
InternalProvider,
CallbacksOptions,
Account,
Awaitable,
Profile,
Session,
User,
CookiesOptions,
} from "../src"
import { createPKCE } from "../src/core/lib/oauth/pkce-handler" import { createPKCE } from "../src/core/lib/oauth/pkce-handler"
import { InternalUrl } from "../src/utils/parse-url" import { InternalUrl } from "../src/utils/parse-url"
import { JWT, JWTDecodeParams, JWTEncodeParams, JWTOptions } from "../src/jwt" import { JWT, JWTDecodeParams, JWTEncodeParams, JWTOptions } from "../src/jwt"
@@ -21,7 +32,7 @@ beforeEach(() => {
host: "localhost:3000", host: "localhost:3000",
path: "/api/auth", path: "/api/auth",
base: "http://localhost:3000/api/auth", base: "http://localhost:3000/api/auth",
toString: () => "http://localhost:3000/api/auth" toString: () => "http://localhost:3000/api/auth",
} }
provider = { provider = {
@@ -30,7 +41,7 @@ beforeEach(() => {
name: "testName", name: "testName",
signinUrl: "/", signinUrl: "/",
callbackUrl: "/", callbackUrl: "/",
checks: ["pkce", "state"] checks: ["pkce", "state"],
} }
jwt = { jwt = {
@@ -41,22 +52,41 @@ beforeEach(() => {
}, },
decode: function (params: JWTDecodeParams): Awaitable<JWT | null> { decode: function (params: JWTDecodeParams): Awaitable<JWT | null> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
} },
} }
callbacks = { callbacks = {
signIn: function (params: { user: User; account: Account; profile: Profile & Record<string, unknown>; email: { verificationRequest?: boolean | undefined }; credentials?: Record<string, CredentialInput> | undefined }): Awaitable<string | boolean> { signIn: function (params: {
user: User
account: Account
profile: Profile & Record<string, unknown>
email: { verificationRequest?: boolean | undefined }
credentials?: Record<string, CredentialInput> | undefined
}): Awaitable<string | boolean> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
redirect: function (params: { url: string; baseUrl: string }): Awaitable<string> { redirect: function (params: {
url: string
baseUrl: string
}): Awaitable<string> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
session: function (params: { session: Session; user: User; token: JWT }): Awaitable<Session> { session: function (params: {
session: Session
user: User
token: JWT
}): Awaitable<Session> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
jwt: function (params: { token: JWT; user?: User | undefined; account?: Account | undefined; profile?: Profile | undefined; isNewUser?: boolean | undefined }): Awaitable<JWT> { jwt: function (params: {
token: JWT
user?: User | undefined
account?: Account | undefined
profile?: Profile | undefined
isNewUser?: boolean | undefined
}): Awaitable<JWT> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
} },
} }
cookies = { cookies = {
@@ -65,7 +95,7 @@ beforeEach(() => {
csrfToken: { name: "", options: undefined }, csrfToken: { name: "", options: undefined },
pkceCodeVerifier: { name: "", options: {} }, pkceCodeVerifier: { name: "", options: {} },
state: { name: "", options: undefined }, state: { name: "", options: undefined },
nonce: { name: "", options: undefined } nonce: { name: "", options: undefined },
} }
options = { options = {
@@ -81,9 +111,9 @@ beforeEach(() => {
events: {}, events: {},
callbacks, callbacks,
cookies, cookies,
callbackUrl: '', callbackUrl: "",
providers: [], providers: [],
theme: {} theme: {},
} }
}) })

View File

@@ -1,5 +1,16 @@
import { mockLogger } from "./lib" import { mockLogger } from "./utils"
import type { InternalOptions, LoggerInstance, InternalProvider, CallbacksOptions, Account, Awaitable, Profile, Session, User, CookiesOptions } from "../src" import type {
InternalOptions,
LoggerInstance,
InternalProvider,
CallbacksOptions,
Account,
Awaitable,
Profile,
Session,
User,
CookiesOptions,
} from "../src"
import { createState } from "../src/core/lib/oauth/state-handler" import { createState } from "../src/core/lib/oauth/state-handler"
import { InternalUrl } from "../src/utils/parse-url" import { InternalUrl } from "../src/utils/parse-url"
import { JWT, JWTOptions, encode, decode } from "../src/jwt" import { JWT, JWTOptions, encode, decode } from "../src/jwt"
@@ -21,7 +32,7 @@ beforeEach(() => {
host: "localhost:3000", host: "localhost:3000",
path: "/api/auth", path: "/api/auth",
base: "http://localhost:3000/api/auth", base: "http://localhost:3000/api/auth",
toString: () => "http://localhost:3000/api/auth" toString: () => "http://localhost:3000/api/auth",
} }
provider = { provider = {
@@ -30,29 +41,48 @@ beforeEach(() => {
name: "testName", name: "testName",
signinUrl: "/", signinUrl: "/",
callbackUrl: "/", callbackUrl: "/",
checks: ["pkce", "state"] checks: ["pkce", "state"],
} }
jwt = { jwt = {
secret: "secret", secret: "secret",
maxAge: 0, maxAge: 0,
encode, encode,
decode decode,
} }
callbacks = { callbacks = {
signIn: function (params: { user: User; account: Account; profile: Profile & Record<string, unknown>; email: { verificationRequest?: boolean | undefined }; credentials?: Record<string, CredentialInput> | undefined }): Awaitable<string | boolean> { signIn: function (params: {
user: User
account: Account
profile: Profile & Record<string, unknown>
email: { verificationRequest?: boolean | undefined }
credentials?: Record<string, CredentialInput> | undefined
}): Awaitable<string | boolean> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
redirect: function (params: { url: string; baseUrl: string }): Awaitable<string> { redirect: function (params: {
url: string
baseUrl: string
}): Awaitable<string> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
session: function (params: { session: Session; user: User; token: JWT }): Awaitable<Session> { session: function (params: {
session: Session
user: User
token: JWT
}): Awaitable<Session> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
}, },
jwt: function (params: { token: JWT; user?: User | undefined; account?: Account | undefined; profile?: Profile | undefined; isNewUser?: boolean | undefined }): Awaitable<JWT> { jwt: function (params: {
token: JWT
user?: User | undefined
account?: Account | undefined
profile?: Profile | undefined
isNewUser?: boolean | undefined
}): Awaitable<JWT> {
throw new Error("Function not implemented.") throw new Error("Function not implemented.")
} },
} }
cookies = { cookies = {
@@ -61,7 +91,7 @@ beforeEach(() => {
csrfToken: { name: "", options: undefined }, csrfToken: { name: "", options: undefined },
pkceCodeVerifier: { name: "", options: undefined }, pkceCodeVerifier: { name: "", options: undefined },
state: { name: "", options: {} }, state: { name: "", options: {} },
nonce: { name: "", options: undefined } nonce: { name: "", options: undefined },
} }
options = { options = {
@@ -77,9 +107,9 @@ beforeEach(() => {
events: {}, events: {},
callbacks, callbacks,
cookies, cookies,
callbackUrl: '', callbackUrl: "",
providers: [], providers: [],
theme: {} theme: {},
} }
}) })

View File

@@ -0,0 +1,116 @@
import { createHash } from "crypto"
import { AuthHandler } from "../src/core"
import type { LoggerInstance, AuthOptions } from "../src"
import type { Adapter } from "../src/adapters"
import NextAuth from "../src/next"
import type { NextApiRequest, NextApiResponse } from "next"
export function mockLogger(): Record<keyof LoggerInstance, jest.Mock> {
return {
error: jest.fn(() => {}),
warn: jest.fn(() => {}),
debug: jest.fn(() => {}),
}
}
interface HandlerOptions {
prod?: boolean
path?: string
params?: URLSearchParams | Record<string, string>
requestInit?: RequestInit
}
export async function handler(
options: AuthOptions,
{ prod, path, params, requestInit }: HandlerOptions
) {
// @ts-expect-error
if (prod) process.env.NODE_ENV = "production"
const url = new URL(
`http://localhost:3000/api/auth/${path ?? "signin"}?${new URLSearchParams(
params ?? {}
)}`
)
const req = new Request(url, { headers: { host: "" }, ...requestInit })
const logger = mockLogger()
const response = await AuthHandler(req, {
secret: "secret",
...options,
logger,
})
// @ts-expect-error
if (prod) process.env.NODE_ENV = "test"
return {
res: {
status: response.status,
headers: response.headers,
body: response.body,
redirect: response.headers.get("location"),
html:
response.headers?.get("content-type") === "text/html"
? await response.clone().text()
: undefined,
},
log: logger,
}
}
export function createCSRF() {
const secret = "secret"
const value = "csrf"
const token = createHash("sha256").update(`${value}${secret}`).digest("hex")
return {
secret,
csrf: { value, token, cookie: `next-auth.csrf-token=${value}|${token}` },
}
}
export function mockAdapter(): Adapter {
const adapter: Adapter = {
createVerificationToken: jest.fn(() => {}),
useVerificationToken: jest.fn(() => {}),
getUserByEmail: jest.fn(() => {}),
} as unknown as Adapter
return adapter
}
export async function nodeHandler(
params: {
req?: Partial<NextApiRequest>
res?: Partial<NextApiResponse>
options?: Partial<AuthOptions>
} = {}
) {
const req = {
body: {},
cookies: {},
headers: {},
method: "GET",
...params.req,
}
const res = {
...params.res,
end: jest.fn(),
json: jest.fn(),
status: jest.fn().mockReturnValue({ end: jest.fn() }),
setHeader: jest.fn(),
removeHeader: jest.fn(),
send: jest.fn(),
}
const logger = mockLogger()
await NextAuth(req as any, res as any, {
providers: [],
secret: "secret",
logger,
...params.options,
})
return { req, res, logger }
}

151
pnpm-lock.yaml generated
View File

@@ -61,8 +61,7 @@ importers:
'@types/react-dom': ^18.0.6 '@types/react-dom': ^18.0.6
fake-smtp-server: ^0.8.0 fake-smtp-server: ^0.8.0
faunadb: ^4 faunadb: ^4
jsonwebtoken: ^8.5.1 next: 13.0.6
next: 13.0.2
next-auth: workspace:* next-auth: workspace:*
nodemailer: ^6 nodemailer: ^6
pg: ^8.7.3 pg: ^8.7.3
@@ -79,8 +78,7 @@ importers:
'@prisma/client': 3.15.2_prisma@3.15.2 '@prisma/client': 3.15.2_prisma@3.15.2
'@supabase/supabase-js': 2.0.5 '@supabase/supabase-js': 2.0.5
faunadb: 4.6.0 faunadb: 4.6.0
jsonwebtoken: 8.5.1 next: 13.0.6_biqbaboplfbrettd7655fr4n2y
next: 13.0.2_biqbaboplfbrettd7655fr4n2y
next-auth: link:../../packages/next-auth next-auth: link:../../packages/next-auth
nodemailer: 6.7.5 nodemailer: 6.7.5
react: 18.2.0 react: 18.2.0
@@ -474,7 +472,7 @@ importers:
jest-watch-typeahead: ^1.1.0 jest-watch-typeahead: ^1.1.0
jose: ^4.9.3 jose: ^4.9.3
msw: ^0.42.3 msw: ^0.42.3
next: 13.0.2 next: 13.0.6
oauth: ^0.9.15 oauth: ^0.9.15
openid-client: ^5.1.0 openid-client: ^5.1.0
postcss: ^8.4.14 postcss: ^8.4.14
@@ -528,7 +526,7 @@ importers:
jest-environment-jsdom: 28.1.1 jest-environment-jsdom: 28.1.1
jest-watch-typeahead: 1.1.0_jest@28.1.1 jest-watch-typeahead: 1.1.0_jest@28.1.1
msw: 0.42.3 msw: 0.42.3
next: 13.0.2_4cc5zw5azim2bix77d63le72su next: 13.0.6_4cc5zw5azim2bix77d63le72su
postcss: 8.4.14 postcss: 8.4.14
postcss-cli: 9.1.0_postcss@8.4.14 postcss-cli: 9.1.0_postcss@8.4.14
postcss-nested: 5.0.6_postcss@8.4.14 postcss-nested: 5.0.6_postcss@8.4.14
@@ -7538,107 +7536,107 @@ packages:
- supports-color - supports-color
dev: true dev: true
/@next/env/13.0.2: /@next/env/13.0.6:
resolution: {integrity: sha512-Qb6WPuRriGIQ19qd6NBxpcrFOfj8ziN7l9eZUfwff5gl4zLXluqtuZPddYZM/oWjN53ZYcuRXzL+oowKyJeYtA==} resolution: {integrity: sha512-yceT6DCHKqPRS1cAm8DHvDvK74DLIkDQdm5iV+GnIts8h0QbdHvkUIkdOvQoOODgpr6018skbmSQp12z5OWIQQ==}
/@next/swc-android-arm-eabi/13.0.2: /@next/swc-android-arm-eabi/13.0.6:
resolution: {integrity: sha512-X54UQCTFyOGnJP//Z71dPPlp4BCYcQL2ncikKXQcPzVpqPs4C3m+tKC8ivBNH6edAXkppwsLRz1/yQwgSZ9Swg==} resolution: {integrity: sha512-FGFSj3v2Bluw8fD/X+1eXIEB0PhoJE0zfutsAauRhmNpjjZshLDgoXMWm1jTRL/04K/o9gwwO2+A8+sPVCH1uw==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm] cpu: [arm]
os: [android] os: [android]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-android-arm64/13.0.2: /@next/swc-android-arm64/13.0.6:
resolution: {integrity: sha512-1P00Kv8uKaLubqo7JzPrTqgFAzSOmfb8iwqJrOb9in5IvTRtNGlkR4hU0sXzqbQNM/+SaYxze6Z5ry1IDyb/cQ==} resolution: {integrity: sha512-7MgbtU7kimxuovVsd7jSJWMkIHBDBUsNLmmlkrBRHTvgzx5nDBXogP0hzZm7EImdOPwVMPpUHRQMBP9mbsiJYQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-darwin-arm64/13.0.2: /@next/swc-darwin-arm64/13.0.6:
resolution: {integrity: sha512-1zGIOkInkOLRv0QQGZ+3wffYsyKI4vIy62LYTvDWUn7TAYqnmXwougp9NSLqDeagLwgsv2URrykyAFixA/YqxA==} resolution: {integrity: sha512-AUVEpVTxbP/fxdFsjVI9d5a0CFn6NVV7A/RXOb0Y+pXKIIZ1V5rFjPwpYfIfyOo2lrqgehMNQcyMRoTrhq04xg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-darwin-x64/13.0.2: /@next/swc-darwin-x64/13.0.6:
resolution: {integrity: sha512-ECDAjoMP1Y90cARaelS6X+k6BQx+MikAYJ8f/eaJrLur44NIOYc9HA/dgcTp5jenguY4yT8V+HCquLjAVle6fA==} resolution: {integrity: sha512-SasCDJlshglsPnbzhWaIF6VEGkQy2NECcAOxPwaPr0cwbbt4aUlZ7QmskNzgolr5eAjFS/xTr7CEeKJtZpAAtQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-freebsd-x64/13.0.2: /@next/swc-freebsd-x64/13.0.6:
resolution: {integrity: sha512-2DcL/ofQdBnQX3IoI9sjlIAyLCD1oZoUBuhrhWbejvBQjutWrI0JTEv9uG69WcxWhVMm3BCsjv8GK2/68OKp7A==} resolution: {integrity: sha512-6Lbxd9gAdXneTkwHyYW/qtX1Tdw7ND9UbiGsGz/SP43ZInNWnW6q0au4hEVPZ9bOWWRKzcVoeTBdoMpQk9Hx9w==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-linux-arm-gnueabihf/13.0.2: /@next/swc-linux-arm-gnueabihf/13.0.6:
resolution: {integrity: sha512-Y3OQF1CSBSWW2vGkmvOIuOUNqOq8qX7f1ZpcKUVWP3/Uq++DZmVi9d18lgnSe1I3QFqc+nXWyun9ljsN83j0sw==} resolution: {integrity: sha512-wNdi5A519e1P+ozEuYOhWPzzE6m1y7mkO6NFwn6watUwO0X9nZs7fT9THmnekvmFQpaZ6U+xf2MQ9poQoCh6jQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-linux-arm64-gnu/13.0.2: /@next/swc-linux-arm64-gnu/13.0.6:
resolution: {integrity: sha512-mNyzwsFF6kwZYEjnGicx9ksDZYEZvyzEc1BtCu8vdZi/v8UeixQwCiAT6FyYX9uxMPEkzk8qiU0t0u9gvltsKw==} resolution: {integrity: sha512-e8KTRnleQY1KLk5PwGV5hrmvKksCc74QRpHl5ffWnEEAtL2FE0ave5aIkXqErsPdXkiKuA/owp3LjQrP+/AH7Q==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-linux-arm64-musl/13.0.2: /@next/swc-linux-arm64-musl/13.0.6:
resolution: {integrity: sha512-M6SdYjWgRrY3tJBxz0663zCRPTu5BRONmxlftKWWHv9LjAJ59neTLaGj4rp0A08DkJglZIoCkLOzLrzST6TGag==} resolution: {integrity: sha512-/7RF03C3mhjYpHN+pqOolgME3guiHU5T3TsejuyteqyEyzdEyLHod+jcYH6ft7UZ71a6TdOewvmbLOtzHW2O8A==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-linux-x64-gnu/13.0.2: /@next/swc-linux-x64-gnu/13.0.6:
resolution: {integrity: sha512-pi63RoxvG4ES1KS06Zpm0MATVIXTs/TIbLbdckeLoM40u1d3mQl/+hSSrLRSxzc2OtyL8fh92sM4gkJrQXAMAw==} resolution: {integrity: sha512-kxyEXnYHpOEkFnmrlwB1QlzJtjC6sAJytKcceIyFUHbCaD3W/Qb5tnclcnHKTaFccizZRePXvV25Ok/eUSpKTw==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-linux-x64-musl/13.0.2: /@next/swc-linux-x64-musl/13.0.6:
resolution: {integrity: sha512-9Pv91gfYnDONgjtRm78n64b/c54+azeHtlnqBLTnIFWSMBDRl1/WDkhKWIj3fBGPLimtK7Tko3ULR3og9RRUPw==} resolution: {integrity: sha512-N0c6gubS3WW1oYYgo02xzZnNatfVQP/CiJq2ax+DJ55ePV62IACbRCU99TZNXXg+Kos6vNW4k+/qgvkvpGDeyA==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-win32-arm64-msvc/13.0.2: /@next/swc-win32-arm64-msvc/13.0.6:
resolution: {integrity: sha512-Nvewe6YZaizAkGHHprbMkYqQulBjZCHKBGKeFPwoPtOA+a2Qi4pZzc/qXFyC5/2A6Z0mr2U1zg9rd04WBYMwBw==} resolution: {integrity: sha512-QjeMB2EBqBFPb/ac0CYr7GytbhUkrG4EwFWbcE0vsRp4H8grt25kYpFQckL4Jak3SUrp7vKfDwZ/SwO7QdO8vw==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-win32-ia32-msvc/13.0.2: /@next/swc-win32-ia32-msvc/13.0.6:
resolution: {integrity: sha512-ZUBYGZw5G3QrqDpRq1EWi3aHmvPZM8ijK5TFL6UbH16cYQ0JpANmuG2P66KB93Qe/lWWzbeAZk/tj1XqwoCuPA==} resolution: {integrity: sha512-EQzXtdqRTcmhT/tCq81rIwE36Y3fNHPInaCuJzM/kftdXfa0F+64y7FAoMO13npX8EG1+SamXgp/emSusKrCXg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [ia32] cpu: [ia32]
os: [win32] os: [win32]
requiresBuild: true requiresBuild: true
optional: true optional: true
/@next/swc-win32-x64-msvc/13.0.2: /@next/swc-win32-x64-msvc/13.0.6:
resolution: {integrity: sha512-fA9uW1dm7C0mEYGcKlbmLcVm2sKcye+1kPxh2cM4jVR+kQQMtHWsjIzeSpe2grQLSDan06z4n6hbr8b1c3hA8w==} resolution: {integrity: sha512-pSkqZ//UP/f2sS9T7IvHLfEWDPTX0vRyXJnAUNisKvO3eF3e1xdhDX7dix/X3Z3lnN4UjSwOzclAI87JFbOwmQ==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
@@ -8213,8 +8211,8 @@ packages:
'@swc/core-win32-x64-msvc': 1.2.204 '@swc/core-win32-x64-msvc': 1.2.204
dev: true dev: true
/@swc/helpers/0.4.11: /@swc/helpers/0.4.14:
resolution: {integrity: sha512-rEUrBSGIoSFuYxwBYtlUFMlE2CwGhmW+w9355/5oduSw8e5h2+Tj4UrAGNNgP9915++wj5vkQo0UuOBqOAq4nw==} resolution: {integrity: sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw==}
dependencies: dependencies:
tslib: 2.4.0 tslib: 2.4.0
@@ -10492,7 +10490,7 @@ packages:
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true hasBin: true
dependencies: dependencies:
caniuse-lite: 1.0.30001358 caniuse-lite: 1.0.30001431
electron-to-chromium: 1.4.167 electron-to-chromium: 1.4.167
node-releases: 2.0.5 node-releases: 2.0.5
update-browserslist-db: 1.0.3_browserslist@4.21.0 update-browserslist-db: 1.0.3_browserslist@4.21.0
@@ -10710,7 +10708,7 @@ packages:
resolution: {integrity: sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==} resolution: {integrity: sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==}
dependencies: dependencies:
browserslist: 4.21.0 browserslist: 4.21.0
caniuse-lite: 1.0.30001358 caniuse-lite: 1.0.30001431
lodash.memoize: 4.1.2 lodash.memoize: 4.1.2
lodash.uniq: 4.5.0 lodash.uniq: 4.5.0
dev: true dev: true
@@ -19129,8 +19127,8 @@ packages:
/next-tick/1.1.0: /next-tick/1.1.0:
resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==} resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==}
/next/13.0.2_4cc5zw5azim2bix77d63le72su: /next/13.0.6_4cc5zw5azim2bix77d63le72su:
resolution: {integrity: sha512-uQ5z5e4D9mOe8+upy6bQdYYjo/kk1v3jMW87kTy2TgAyAsEO+CkwRnMgyZ4JoHEnhPZLHwh7dk0XymRNLe1gFw==} resolution: {integrity: sha512-COvigvms2LRt1rrzfBQcMQ2GZd86Mvk1z+LOLY5pniFtL4VrTmhZ9salrbKfSiXbhsD01TrDdD68ec3ABDyscA==}
engines: {node: '>=14.6.0'} engines: {node: '>=14.6.0'}
hasBin: true hasBin: true
peerDependencies: peerDependencies:
@@ -19147,35 +19145,34 @@ packages:
sass: sass:
optional: true optional: true
dependencies: dependencies:
'@next/env': 13.0.2 '@next/env': 13.0.6
'@swc/helpers': 0.4.11 '@swc/helpers': 0.4.14
caniuse-lite: 1.0.30001431 caniuse-lite: 1.0.30001431
postcss: 8.4.14 postcss: 8.4.14
react: 18.2.0 react: 18.2.0
react-dom: 18.2.0_react@18.2.0 react-dom: 18.2.0_react@18.2.0
styled-jsx: 5.1.0_5wvcx74lvxq2lfpc5x4ihgp2jm styled-jsx: 5.1.0_5wvcx74lvxq2lfpc5x4ihgp2jm
use-sync-external-store: 1.2.0_react@18.2.0
optionalDependencies: optionalDependencies:
'@next/swc-android-arm-eabi': 13.0.2 '@next/swc-android-arm-eabi': 13.0.6
'@next/swc-android-arm64': 13.0.2 '@next/swc-android-arm64': 13.0.6
'@next/swc-darwin-arm64': 13.0.2 '@next/swc-darwin-arm64': 13.0.6
'@next/swc-darwin-x64': 13.0.2 '@next/swc-darwin-x64': 13.0.6
'@next/swc-freebsd-x64': 13.0.2 '@next/swc-freebsd-x64': 13.0.6
'@next/swc-linux-arm-gnueabihf': 13.0.2 '@next/swc-linux-arm-gnueabihf': 13.0.6
'@next/swc-linux-arm64-gnu': 13.0.2 '@next/swc-linux-arm64-gnu': 13.0.6
'@next/swc-linux-arm64-musl': 13.0.2 '@next/swc-linux-arm64-musl': 13.0.6
'@next/swc-linux-x64-gnu': 13.0.2 '@next/swc-linux-x64-gnu': 13.0.6
'@next/swc-linux-x64-musl': 13.0.2 '@next/swc-linux-x64-musl': 13.0.6
'@next/swc-win32-arm64-msvc': 13.0.2 '@next/swc-win32-arm64-msvc': 13.0.6
'@next/swc-win32-ia32-msvc': 13.0.2 '@next/swc-win32-ia32-msvc': 13.0.6
'@next/swc-win32-x64-msvc': 13.0.2 '@next/swc-win32-x64-msvc': 13.0.6
transitivePeerDependencies: transitivePeerDependencies:
- '@babel/core' - '@babel/core'
- babel-plugin-macros - babel-plugin-macros
dev: true dev: true
/next/13.0.2_biqbaboplfbrettd7655fr4n2y: /next/13.0.6_biqbaboplfbrettd7655fr4n2y:
resolution: {integrity: sha512-uQ5z5e4D9mOe8+upy6bQdYYjo/kk1v3jMW87kTy2TgAyAsEO+CkwRnMgyZ4JoHEnhPZLHwh7dk0XymRNLe1gFw==} resolution: {integrity: sha512-COvigvms2LRt1rrzfBQcMQ2GZd86Mvk1z+LOLY5pniFtL4VrTmhZ9salrbKfSiXbhsD01TrDdD68ec3ABDyscA==}
engines: {node: '>=14.6.0'} engines: {node: '>=14.6.0'}
hasBin: true hasBin: true
peerDependencies: peerDependencies:
@@ -19192,28 +19189,27 @@ packages:
sass: sass:
optional: true optional: true
dependencies: dependencies:
'@next/env': 13.0.2 '@next/env': 13.0.6
'@swc/helpers': 0.4.11 '@swc/helpers': 0.4.14
caniuse-lite: 1.0.30001431 caniuse-lite: 1.0.30001431
postcss: 8.4.14 postcss: 8.4.14
react: 18.2.0 react: 18.2.0
react-dom: 18.2.0_react@18.2.0 react-dom: 18.2.0_react@18.2.0
styled-jsx: 5.1.0_react@18.2.0 styled-jsx: 5.1.0_react@18.2.0
use-sync-external-store: 1.2.0_react@18.2.0
optionalDependencies: optionalDependencies:
'@next/swc-android-arm-eabi': 13.0.2 '@next/swc-android-arm-eabi': 13.0.6
'@next/swc-android-arm64': 13.0.2 '@next/swc-android-arm64': 13.0.6
'@next/swc-darwin-arm64': 13.0.2 '@next/swc-darwin-arm64': 13.0.6
'@next/swc-darwin-x64': 13.0.2 '@next/swc-darwin-x64': 13.0.6
'@next/swc-freebsd-x64': 13.0.2 '@next/swc-freebsd-x64': 13.0.6
'@next/swc-linux-arm-gnueabihf': 13.0.2 '@next/swc-linux-arm-gnueabihf': 13.0.6
'@next/swc-linux-arm64-gnu': 13.0.2 '@next/swc-linux-arm64-gnu': 13.0.6
'@next/swc-linux-arm64-musl': 13.0.2 '@next/swc-linux-arm64-musl': 13.0.6
'@next/swc-linux-x64-gnu': 13.0.2 '@next/swc-linux-x64-gnu': 13.0.6
'@next/swc-linux-x64-musl': 13.0.2 '@next/swc-linux-x64-musl': 13.0.6
'@next/swc-win32-arm64-msvc': 13.0.2 '@next/swc-win32-arm64-msvc': 13.0.6
'@next/swc-win32-ia32-msvc': 13.0.2 '@next/swc-win32-ia32-msvc': 13.0.6
'@next/swc-win32-x64-msvc': 13.0.2 '@next/swc-win32-x64-msvc': 13.0.6
transitivePeerDependencies: transitivePeerDependencies:
- '@babel/core' - '@babel/core'
- babel-plugin-macros - babel-plugin-macros
@@ -24193,13 +24189,6 @@ packages:
use-isomorphic-layout-effect: 1.1.2_react@18.2.0 use-isomorphic-layout-effect: 1.1.2_react@18.2.0
dev: true dev: true
/use-sync-external-store/1.2.0_react@18.2.0:
resolution: {integrity: sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
dependencies:
react: 18.2.0
/utf-8-validate/5.0.9: /utf-8-validate/5.0.9:
resolution: {integrity: sha512-Yek7dAy0v3Kl0orwMlvi7TPtiCNrdfHNd7Gcc/pLq4BLXqfAmd0J7OWMizUQnTTJsyjKn02mU7anqwfmUP4J8Q==} resolution: {integrity: sha512-Yek7dAy0v3Kl0orwMlvi7TPtiCNrdfHNd7Gcc/pLq4BLXqfAmd0J7OWMizUQnTTJsyjKn02mU7anqwfmUP4J8Q==}
engines: {node: '>=6.14.2'} engines: {node: '>=6.14.2'}