From 54ff292219ceb43abf015870585bbbf57fff48b3 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 12 Sep 2026 19:46:14 -0700 Subject: [PATCH 1/3] feat(react-native): add the headless React Native binding An AuthProvider over the shared session store, always on bearer transport; useAuth, useAuthClient, useLoginMethods and usePasskeySupport; and the native ports: createSecureStoreTokenStorage over expo-secure-store, createNativePasskeyPort over react-native-passkeys (mapping native failures onto the DOMException names the client's error readers understand), createWebBrowserOAuthRedirect over an expo-web-browser auth session resolving the callback's code and state, and describeDevice for passkey metadata. Each port takes its native module as a parameter, so an app installs only what it uses and Metro never resolves a module it did not. No screens: the app brings its own, the way a web app that skips AuthRoutes does. The flows, session state and token custody come from @seamless-auth/client. --- .changeset/react-native-binding.md | 17 + README.md | 15 +- jest.config.ts | 6 +- package-lock.json | 23 +- package.json | 7 +- packages/client/src/ports/passkeys.ts | 9 + packages/react-native/CHANGELOG.md | 1 + packages/react-native/LICENSE | 661 ++++++++++++++++++ packages/react-native/README.md | 140 ++++ packages/react-native/jest.config.ts | 22 + packages/react-native/package.json | 52 ++ packages/react-native/rollup.config.js | 33 + packages/react-native/src/AuthProvider.tsx | 130 ++++ packages/react-native/src/deviceInfo.ts | 37 + .../react-native/src/hooks/useAuthClient.ts | 13 + .../src/hooks/useAuthorizedFetch.ts | 13 + .../react-native/src/hooks/useLoginMethods.ts | 74 ++ .../src/hooks/usePasskeySupport.ts | 41 ++ packages/react-native/src/index.ts | 90 +++ .../react-native/src/ports/nativePasskeys.ts | 114 +++ .../src/ports/secureStoreTokenStorage.ts | 94 +++ .../src/ports/webBrowserOAuthRedirect.ts | 77 ++ packages/react-native/tests/ports.test.ts | 265 +++++++ packages/react-native/tests/provider.test.tsx | 178 +++++ packages/react-native/tsconfig.build.json | 15 + packages/react-native/tsconfig.dev.json | 4 + packages/react-native/tsconfig.json | 9 + 27 files changed, 2128 insertions(+), 12 deletions(-) create mode 100644 .changeset/react-native-binding.md create mode 100644 packages/react-native/CHANGELOG.md create mode 100644 packages/react-native/LICENSE create mode 100644 packages/react-native/README.md create mode 100644 packages/react-native/jest.config.ts create mode 100644 packages/react-native/package.json create mode 100644 packages/react-native/rollup.config.js create mode 100644 packages/react-native/src/AuthProvider.tsx create mode 100644 packages/react-native/src/deviceInfo.ts create mode 100644 packages/react-native/src/hooks/useAuthClient.ts create mode 100644 packages/react-native/src/hooks/useAuthorizedFetch.ts create mode 100644 packages/react-native/src/hooks/useLoginMethods.ts create mode 100644 packages/react-native/src/hooks/usePasskeySupport.ts create mode 100644 packages/react-native/src/index.ts create mode 100644 packages/react-native/src/ports/nativePasskeys.ts create mode 100644 packages/react-native/src/ports/secureStoreTokenStorage.ts create mode 100644 packages/react-native/src/ports/webBrowserOAuthRedirect.ts create mode 100644 packages/react-native/tests/ports.test.ts create mode 100644 packages/react-native/tests/provider.test.tsx create mode 100644 packages/react-native/tsconfig.build.json create mode 100644 packages/react-native/tsconfig.dev.json create mode 100644 packages/react-native/tsconfig.json diff --git a/.changeset/react-native-binding.md b/.changeset/react-native-binding.md new file mode 100644 index 0000000..0ba8f0d --- /dev/null +++ b/.changeset/react-native-binding.md @@ -0,0 +1,17 @@ +--- +'@seamless-auth/react-native': minor +--- + +First release of `@seamless-auth/react-native`, the headless React Native binding. + +An `AuthProvider` over the shared session store, always on bearer transport; `useAuth`, +`useAuthClient`, `useLoginMethods` and `usePasskeySupport`; and the native ports: +`createSecureStoreTokenStorage` (expo-secure-store), `createNativePasskeyPort` +(react-native-passkeys, mapping native failures onto the DOMException names the client's error +readers understand), `createWebBrowserOAuthRedirect` (expo-web-browser auth session, resolving the +callback's `code` and `state`), and `describeDevice` for passkey metadata. Each port takes its +native module as a parameter, so an app installs only what it uses and Metro never resolves a +module it did not. + +No screens: the app brings its own, the same way a web app that skips `AuthRoutes` does. The flows, +session state, and token custody come from `@seamless-auth/client`. diff --git a/README.md b/README.md index f2cddb7..4264277 100644 --- a/README.md +++ b/README.md @@ -3,15 +3,16 @@ This repository is an npm workspace that publishes the client-side packages for [Seamless Auth](https://github.com/fells-code/seamless-auth-api): -| Package | What it is | -| ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| [`@seamless-auth/client`](packages/client/README.md) | Framework-agnostic core: the headless auth client, session store, result and error types. | -| [`@seamless-auth/react`](packages/react/README.md) | React binding: `AuthProvider`, hooks, and optional prebuilt auth screens. Depends on the client package. | +| Package | What it is | +| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| [`@seamless-auth/client`](packages/client/README.md) | Framework-agnostic core: the headless auth client, session store, result and error types. | +| [`@seamless-auth/react`](packages/react/README.md) | React binding: `AuthProvider`, hooks, and optional prebuilt auth screens. Depends on the client package. | +| [`@seamless-auth/react-native`](packages/react-native/README.md) | Headless React Native binding: provider, hooks, and the native ports for passkeys, keystore token storage, and in-app browser OAuth. | Most React applications only install `@seamless-auth/react`; it brings the client -core with it. The client package exists so that other bindings (React Native -next) share one implementation of the auth flows and session state instead of -re-implementing them. +core with it. The client package exists so that the bindings share one +implementation of the auth flows and session state instead of re-implementing +them; `@seamless-auth/react-native` is the second binding over it. ## Working in this repository diff --git a/jest.config.ts b/jest.config.ts index ff7db69..c51f687 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -1,5 +1,9 @@ export default { - projects: ['/packages/client', '/packages/react'], + projects: [ + '/packages/client', + '/packages/react', + '/packages/react-native', + ], collectCoverage: true, collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/**/*.d.ts'], coverageThreshold: { diff --git a/package-lock.json b/package-lock.json index fdab5a2..458196f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,8 @@ "license": "AGPL-3.0-only", "workspaces": [ "packages/client", - "packages/react" + "packages/react", + "packages/react-native" ], "devDependencies": { "@changesets/cli": "^2.31.0", @@ -3062,6 +3063,10 @@ "resolved": "packages/react", "link": true }, + "node_modules/@seamless-auth/react-native": { + "resolved": "packages/react-native", + "link": true + }, "node_modules/@seamless-auth/types": { "version": "0.20.0", "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.20.0.tgz", @@ -13890,6 +13895,22 @@ "react-dom": "^18.0.0 || ^19.0.0", "react-router-dom": "^6.4.0 || ^7.15.1" } + }, + "packages/react-native": { + "name": "@seamless-auth/react-native", + "version": "0.0.0", + "license": "AGPL-3.0-only", + "dependencies": { + "@seamless-auth/client": "^0.0.0", + "@seamless-auth/types": "^0.20.0" + }, + "engines": { + "node": ">=24.0.0 <25.0.0", + "npm": ">=9.0.0 <13.0.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0" + } } } } diff --git a/package.json b/package.json index 5715c11..f99bdf6 100644 --- a/package.json +++ b/package.json @@ -5,17 +5,18 @@ "type": "module", "workspaces": [ "packages/client", - "packages/react" + "packages/react", + "packages/react-native" ], "engines": { "node": ">=24.0.0 <25.0.0", "npm": ">=9.0.0 <13.0.0" }, "scripts": { - "build": "npm run build -w @seamless-auth/client && npm run build -w @seamless-auth/react", + "build": "npm run build -w @seamless-auth/client && npm run build -w @seamless-auth/react && npm run build -w @seamless-auth/react-native", "test": "jest", "coverage": "npm test -- --coverage", - "typecheck": "npm run typecheck -w @seamless-auth/client && npm run typecheck -w @seamless-auth/react", + "typecheck": "npm run typecheck -w @seamless-auth/client && npm run typecheck -w @seamless-auth/react && npm run typecheck -w @seamless-auth/react-native", "lint": "eslint ./packages", "format": "prettier --write .", "format:check": "prettier --check .", diff --git a/packages/client/src/ports/passkeys.ts b/packages/client/src/ports/passkeys.ts index 848d29d..5e0e081 100644 --- a/packages/client/src/ports/passkeys.ts +++ b/packages/client/src/ports/passkeys.ts @@ -11,6 +11,15 @@ import type { RegistrationResponseJSON, } from '@simplewebauthn/browser'; +// Re-exported so a binding can type its port without depending on the +// browser package itself. +export type { + AuthenticationResponseJSON, + PublicKeyCredentialCreationOptionsJSON, + PublicKeyCredentialRequestOptionsJSON, + RegistrationResponseJSON, +}; + /** * The passkey ceremonies, as the platform runs them. * diff --git a/packages/react-native/CHANGELOG.md b/packages/react-native/CHANGELOG.md new file mode 100644 index 0000000..bae621e --- /dev/null +++ b/packages/react-native/CHANGELOG.md @@ -0,0 +1 @@ +# @seamless-auth/react-native diff --git a/packages/react-native/LICENSE b/packages/react-native/LICENSE new file mode 100644 index 0000000..162676c --- /dev/null +++ b/packages/react-native/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/react-native/README.md b/packages/react-native/README.md new file mode 100644 index 0000000..639fdf1 --- /dev/null +++ b/packages/react-native/README.md @@ -0,0 +1,140 @@ +# @seamless-auth/react-native + +The React Native binding for Seamless Auth. Headless: an `AuthProvider`, the +hooks a screen needs, and the native ports for passkeys, secure token storage, +and in-app browser OAuth. You bring the screens; the flows, session state, and +token custody come from `@seamless-auth/client`. + +The app talks to your backend's Seamless Auth server adapter (the same `/auth` +mount your web app uses) over bearer transport: the client holds the auth +API's tokens, presents the right one on each request, keeps the pair in the +platform keystore between launches, and refreshes through `POST /auth/refresh` +when the access token expires. Your backend needs `@seamless-auth/express` or +`@seamless-auth/fastify` 0.16 or later, and its own routes accept the same +access token once `requireAuth` is given `authServerUrl` and `audience`. + +## Install + +```bash +npx expo install @seamless-auth/react-native expo-secure-store react-native-passkeys expo-web-browser +``` + +`expo-secure-store`, `react-native-passkeys` and `expo-web-browser` are not +dependencies of this package. Each port takes the module as a parameter, so an +app that does not use OAuth, for example, never installs `expo-web-browser` and +Metro never looks for it. + +## Wire it up + +```tsx +import * as Passkeys from 'react-native-passkeys'; +import * as SecureStore from 'expo-secure-store'; +import * as WebBrowser from 'expo-web-browser'; +import { + AuthProvider, + createNativePasskeyPort, + createSecureStoreTokenStorage, + createWebBrowserOAuthRedirect, +} from '@seamless-auth/react-native'; + +const ports = { + passkeys: createNativePasskeyPort(Passkeys), + tokenStorage: createSecureStoreTokenStorage(SecureStore), + oauthRedirect: createWebBrowserOAuthRedirect(WebBrowser), +}; + +export default function App() { + return ( + + + + ); +} +``` + +Build `ports` once, at module scope or in a `useMemo`: the provider keys its +session on the port identities. + +On an Android emulator the host machine is `http://10.0.2.2:`, not +`localhost`. + +## Use it + +```tsx +import { + useAuth, + useAuthClient, + useLoginMethods, + usePasskeySupport, +} from '@seamless-auth/react-native'; + +function SignIn() { + const { login, handlePasskeyLogin, isAuthenticated, loading } = useAuth(); + const client = useAuthClient(); + const { loginMethods } = useLoginMethods(); + const { passkeySupported } = usePasskeySupport(); + + const start = async (identifier: string) => { + const { data, error } = await login(identifier, passkeySupported); + if (error) return; + + if (passkeySupported && data.loginMethods?.includes('passkey')) { + const passkey = await handlePasskeyLogin(); + if (!passkey.error) return; + } + + await client.requestLoginEmailOtp(); + // navigate to your code screen; then client.verifyLoginEmailOtp(code) + }; + // ... +} +``` + +`useAuthorizedFetch()` is a fetch for your own API that carries the access +token and refreshes it once on a 401; a path resolves on `apiHost`: + +```ts +const authorizedFetch = useAuthorizedFetch(); +const plan = await authorizedFetch('/api/plan/mine').then(r => r.json()); +``` + +`useAuth()` carries the session state and actions (`user`, `credentials`, +`isAuthenticated`, `loading`, `logout`, `refreshSession`, `registerPasskey`, +step-up and organization helpers) and `useAuthClient()` returns the headless +client for the multi-step flows. The client is the same instance the session +drives, which is what carries a sign-in from `/login` through its OTP or +passkey step. + +Every method returns a `SeamlessAuthResult`: `{ data, error: null }` or +`{ data: null, error }`. Nothing throws for a failed request. + +### Passkeys + +Native passkeys need the relying party to be an associated domain of the app: +`apple-app-site-association` (`webcredentials`) and `assetlinks.json` hosted +over HTTPS on the RP ID domain, an `associatedDomains` entitlement on iOS, and +the app's signing certificate hash in the auth API's `ORIGINS` as +`android:apk-key-hash:` on Android. There is no `localhost` +exemption on either platform. OTP and magic link work without any of that. + +`registerPasskey(describeDevice(Platform, 'My phone'))` records the device +rather than a user agent. + +### Magic links + +Request one with `client.requestMagicLink()`, then poll +`client.checkMagicLink()` every few seconds; the poll returns the session once +the link has been opened anywhere. If the app also receives the link as a +universal link, call `client.verifyMagicLink(token)` and then +`checkMagicLink()`. + +### OAuth + +`startOAuthLogin({ providerId, redirectUri })` returns the provider URL; open +it with `ports.oauthRedirect.open(url, redirectUri)`, which resolves with the +callback's `code` and `state`, and finish with `finishOAuthLogin`. +`redirectUri` must be registered with the provider and allowed by the auth API. + +## License + +AGPL-3.0-only. See [LICENSE](LICENSE). diff --git a/packages/react-native/jest.config.ts b/packages/react-native/jest.config.ts new file mode 100644 index 0000000..67b2542 --- /dev/null +++ b/packages/react-native/jest.config.ts @@ -0,0 +1,22 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +export default { + displayName: 'react-native', + preset: 'ts-jest', + testEnvironment: 'jsdom', + rootDir: '.', + setupFilesAfterEnv: ['/../../jest.setup.ts'], + transform: { + '^.+\\.(t|j)sx?$': ['ts-jest', { useESM: true, tsconfig: '/tsconfig.json' }], + }, + extensionsToTreatAsEsm: ['.ts', '.tsx'], + moduleNameMapper: { + '^@/(.*)$': '/src/$1', + '^@seamless-auth/client$': '/../client/src/index.ts', + }, + testMatch: ['/tests/**/*.(test|spec).[tj]s?(x)'], +}; diff --git a/packages/react-native/package.json b/packages/react-native/package.json new file mode 100644 index 0000000..61c1f5d --- /dev/null +++ b/packages/react-native/package.json @@ -0,0 +1,52 @@ +{ + "name": "@seamless-auth/react-native", + "version": "0.0.0", + "description": "Headless React Native binding for Seamless Auth: provider, hooks, and the native ports for passkeys, secure token storage, and in-app browser OAuth.", + "type": "module", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "types": "./dist/index.d.ts", + "files": [ + "dist", + "README.md", + "CHANGELOG.md", + "LICENSE" + ], + "engines": { + "node": ">=24.0.0 <25.0.0", + "npm": ">=9.0.0 <13.0.0" + }, + "scripts": { + "build": "node ../../scripts/clean-dist.mjs && rollup -c && tsc-alias -p tsconfig.build.json", + "typecheck": "tsc --noEmit -p tsconfig.dev.json", + "check-npm-build": "npm pack --dry-run" + }, + "repository": { + "type": "git", + "url": "https://github.com/fells-code/seamless-auth-react.git", + "directory": "packages/react-native" + }, + "author": "Fells Code, LLC", + "license": "AGPL-3.0-only", + "bugs": { + "url": "https://github.com/fells-code/seamless-auth-react/issues" + }, + "homepage": "https://github.com/fells-code/seamless-auth-react/tree/main/packages/react-native#readme", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "provenance": true + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0" + }, + "dependencies": { + "@seamless-auth/client": "^0.0.0", + "@seamless-auth/types": "^0.20.0" + }, + "sideEffects": false +} diff --git a/packages/react-native/rollup.config.js b/packages/react-native/rollup.config.js new file mode 100644 index 0000000..2481508 --- /dev/null +++ b/packages/react-native/rollup.config.js @@ -0,0 +1,33 @@ +import alias from '@rollup/plugin-alias'; +import commonjs from '@rollup/plugin-commonjs'; +import terser from '@rollup/plugin-terser'; +import typescript from '@rollup/plugin-typescript'; +import path from 'path'; +import peerDepsExternal from 'rollup-plugin-peer-deps-external'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +export default [ + { + input: 'src/index.ts', + output: { + file: 'dist/index.js', + format: 'esm', + sourcemap: true, + }, + external: ['react', 'react/jsx-runtime', '@seamless-auth/client'], + plugins: [ + peerDepsExternal(), + alias({ + entries: [{ find: '@', replacement: path.resolve(__dirname, 'src') }], + }), + commonjs(), + typescript({ + tsconfig: './tsconfig.build.json', + }), + terser(), + ], + }, +]; diff --git a/packages/react-native/src/AuthProvider.tsx b/packages/react-native/src/AuthProvider.tsx new file mode 100644 index 0000000..3885ec5 --- /dev/null +++ b/packages/react-native/src/AuthProvider.tsx @@ -0,0 +1,130 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { + createAuthSession, + createMemoryTokenStorage, + type AuthSessionActions, + type AuthSessionState, + type OAuthRedirectPort, + type PasskeyPort, + type SeamlessAuthClient, + type TokenStoragePort, +} from '@seamless-auth/client'; +import React, { + createContext, + type ReactNode, + useContext, + useEffect, + useMemo, + useSyncExternalStore, +} from 'react'; + +/** + * What a React Native application plugs in for its platform. Unlike the web + * binding there are no defaults here: a native app has no browser to fall back + * to, and each port wraps a native module the app chose to install. + */ +export interface NativeAuthPorts { + passkeys: PasskeyPort; + oauthRedirect?: OAuthRedirectPort; + /** Where the session lives between launches. Defaults to memory, which signs out on restart. */ + tokenStorage?: TokenStoragePort; +} + +export interface AuthContextType extends AuthSessionState, AuthSessionActions { + apiHost: string; + magicLinkRedirectUri?: string; + /** The client behind the session. `useAuthClient()` returns this same instance. */ + client: SeamlessAuthClient; + ports: NativeAuthPorts; +} + +const AuthContext = createContext(undefined); + +export const useAuth = (): AuthContextType => { + const context = useContext(AuthContext); + if (!context) { + throw new Error('useAuth must be used within an AuthProvider'); + } + return context; +}; + +export interface AuthProviderProps { + children: ReactNode; + /** The origin the server adapter is reachable at, for example `https://api.example.com`. */ + apiHost: string; + /** Where the adapter is mounted on that origin. Defaults to `/auth`. */ + basePath?: string; + /** Where a magic link should land, when the deployment allows the app to choose. */ + magicLinkRedirectUri?: string; + ports: NativeAuthPorts; + /** The fetch to use, for tests and instrumented builds. Defaults to the global one. */ + fetch?: typeof fetch; +} + +/** + * The session for a React Native application, always over bearer transport: + * the client holds the auth API's tokens, presents the right one on each + * request, stores the pair through `ports.tokenStorage`, and refreshes + * through `POST /refresh` when the access token expires. + */ +export const AuthProvider: React.FC = ({ + children, + apiHost, + basePath, + magicLinkRedirectUri, + ports, + fetch: fetchImpl, +}) => { + const { passkeys, oauthRedirect, tokenStorage } = ports; + + const session = useMemo( + () => + createAuthSession({ + apiHost, + magicLinkRedirectUri, + passkeys, + transport: { + mode: 'bearer', + basePath, + tokenStorage: tokenStorage ?? createMemoryTokenStorage(), + fetch: fetchImpl, + }, + // There is no "seen before" flag on native: the keystore holding a + // session is the signal, and it is read by the transport itself. + detectPreviousSignIn: false, + }), + [apiHost, basePath, magicLinkRedirectUri, passkeys, tokenStorage, fetchImpl] + ); + + const state = useSyncExternalStore( + session.subscribe, + session.getState, + session.getState + ); + + // Not destroyed on cleanup, for the reason the web binding gives: React may + // mount, clean up, and mount the same memoised store again, and a destroyed + // store refuses updates. + useEffect(() => { + void session.actions.refreshSession(); + }, [session]); + + const value = useMemo( + () => ({ + ...state, + ...session.actions, + apiHost, + magicLinkRedirectUri, + client: session.client, + ports: { passkeys, oauthRedirect, tokenStorage }, + }), + [state, session, apiHost, magicLinkRedirectUri, passkeys, oauthRedirect, tokenStorage] + ); + + return {children}; +}; diff --git a/packages/react-native/src/deviceInfo.ts b/packages/react-native/src/deviceInfo.ts new file mode 100644 index 0000000..e7a9c08 --- /dev/null +++ b/packages/react-native/src/deviceInfo.ts @@ -0,0 +1,37 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import type { PasskeyMetadata } from '@seamless-auth/client'; + +/** The part of React Native's `Platform` this reads. */ +export interface PlatformLike { + OS: string; + Version: string | number; +} + +/** + * The metadata a passkey enrolment records, from the platform rather than a + * user agent string, which a native app does not have. + * + * ```ts + * import { Platform } from 'react-native'; + * registerPasskey(describeDevice(Platform, 'My iPhone')); + * ``` + */ +export function describeDevice( + platform: PlatformLike, + friendlyName?: string +): PasskeyMetadata { + const os = + platform.OS === 'ios' ? 'iOS' : platform.OS === 'android' ? 'Android' : platform.OS; + + return { + friendlyName: friendlyName ?? `${os} device`, + platform: platform.OS, + browser: 'native', + deviceInfo: `${os} ${String(platform.Version)}`, + }; +} diff --git a/packages/react-native/src/hooks/useAuthClient.ts b/packages/react-native/src/hooks/useAuthClient.ts new file mode 100644 index 0000000..6c454c0 --- /dev/null +++ b/packages/react-native/src/hooks/useAuthClient.ts @@ -0,0 +1,13 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { useAuth } from '@/AuthProvider'; + +/** + * The client behind the provider's session: the same instance the store + * drives, which is what holds the sign-in in flight. + */ +export const useAuthClient = () => useAuth().client; diff --git a/packages/react-native/src/hooks/useAuthorizedFetch.ts b/packages/react-native/src/hooks/useAuthorizedFetch.ts new file mode 100644 index 0000000..619c9df --- /dev/null +++ b/packages/react-native/src/hooks/useAuthorizedFetch.ts @@ -0,0 +1,13 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { useAuth } from '@/AuthProvider'; + +/** + * A fetch for the application's own API that carries the access token and + * refreshes it once on a 401. A path resolves on `apiHost`. + */ +export const useAuthorizedFetch = () => useAuth().client.authorizedFetch; diff --git a/packages/react-native/src/hooks/useLoginMethods.ts b/packages/react-native/src/hooks/useLoginMethods.ts new file mode 100644 index 0000000..d7f4c8e --- /dev/null +++ b/packages/react-native/src/hooks/useLoginMethods.ts @@ -0,0 +1,74 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { useEffect, useState } from 'react'; + +import type { LoginMethod } from '@seamless-auth/client'; +import { useAuthClient } from '@/hooks/useAuthClient'; + +/** + * Used only until the instance answers, and if it never does. + * + * Deliberately the narrowest useful set, and matching the auth server's own + * defaults. Offering a method that turns out to be disabled sends a user down a + * path that fails, which is worse than showing one option too few. + */ +export const FALLBACK_LOGIN_METHODS: LoginMethod[] = ['passkey', 'magic_link']; + +/** + * Which sign-in methods this instance has enabled, read from the auth server + * rather than assumed. + * + * `loginMethods` stays null until the answer arrives, and stays null if the + * request fails. A caller must treat that as "unknown" and not as "none": the + * screens use it to decide what is safe to offer, and guessing in either + * direction is worse than waiting. `loading` is what a caller renders against. + */ +export const useLoginMethods = () => { + const authClient = useAuthClient(); + const [loginMethods, setLoginMethods] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let active = true; + + const read = async () => { + try { + const { data, error } = await authClient.getPublicSystemConfig(); + + if (active && !error && data?.loginMethods?.length) { + setLoginMethods(data.loginMethods); + } + } catch { + // Backstop only. The client reports request failures through `error`, + // not by throwing, and either way the methods stay unknown. Leaving + // `loading` true here would hang every screen that waits on it. + } finally { + if (active) { + setLoading(false); + } + } + }; + + void read(); + + return () => { + active = false; + }; + }, [authClient]); + + return { loginMethods, loading }; +}; + +/** + * Whether a user who declines a passkey would still have a way to sign in. + * + * Returns false while the methods are unknown, so a failed or in-flight request + * never produces a skip control that could strand someone in an account they + * cannot get back into. + */ +export const hasNonPasskeyLoginMethod = (loginMethods: LoginMethod[] | null) => + Boolean(loginMethods?.some(method => method !== 'passkey')); diff --git a/packages/react-native/src/hooks/usePasskeySupport.ts b/packages/react-native/src/hooks/usePasskeySupport.ts new file mode 100644 index 0000000..c64b2d3 --- /dev/null +++ b/packages/react-native/src/hooks/usePasskeySupport.ts @@ -0,0 +1,41 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { useEffect, useState } from 'react'; + +import { useAuth } from '@/AuthProvider'; + +/** Whether this device can enrol and use passkeys, from the passkey port. */ +export const usePasskeySupport = () => { + const { ports } = useAuth(); + const [passkeySupported, setPasskeySupported] = useState(false); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let active = true; + + const checkSupport = async () => { + try { + const supported = + ports.passkeys.isSupported() && + (await ports.passkeys.isPlatformAuthenticatorAvailable()); + if (active) setPasskeySupported(supported); + } catch { + if (active) setPasskeySupported(false); + } finally { + if (active) setLoading(false); + } + }; + + void checkSupport(); + + return () => { + active = false; + }; + }, [ports.passkeys]); + + return { passkeySupported, loading }; +}; diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts new file mode 100644 index 0000000..e5d3f61 --- /dev/null +++ b/packages/react-native/src/index.ts @@ -0,0 +1,90 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +export { AuthProvider, useAuth } from '@/AuthProvider'; +export type { AuthContextType, AuthProviderProps, NativeAuthPorts } from '@/AuthProvider'; +export { describeDevice } from '@/deviceInfo'; +export type { PlatformLike } from '@/deviceInfo'; +export { useAuthClient } from '@/hooks/useAuthClient'; +export { useAuthorizedFetch } from '@/hooks/useAuthorizedFetch'; +export { + FALLBACK_LOGIN_METHODS, + hasNonPasskeyLoginMethod, + useLoginMethods, +} from '@/hooks/useLoginMethods'; +export { usePasskeySupport } from '@/hooks/usePasskeySupport'; +export { createNativePasskeyPort } from '@/ports/nativePasskeys'; +export type { NativePasskeysLike } from '@/ports/nativePasskeys'; +export { createSecureStoreTokenStorage } from '@/ports/secureStoreTokenStorage'; +export type { + SecureStoreLike, + SecureStoreTokenStorageOptions, +} from '@/ports/secureStoreTokenStorage'; +export { + createWebBrowserOAuthRedirect, + parseOAuthCallbackUrl, +} from '@/ports/webBrowserOAuthRedirect'; +export type { WebBrowserLike } from '@/ports/webBrowserOAuthRedirect'; + +// The client surface an application reaches for, re-exported so a native app +// installs one package. +export { + createSeamlessAuthClient, + encodePrfSalt, + extractPasskeyPrfResult, + getOAuthErrorCode, + getPasskeyPolicyErrorCode, + getWebAuthnErrorDetail, + hasScopedRole, + isUnauthenticated, + PasskeyCeremonyError, + roleGrantsAccess, + SeamlessAuthError, +} from '@seamless-auth/client'; +export type { + Credential, + CredentialUpdateResult, + CurrentUserResult, + FinishOAuthLoginInput, + FinishOAuthLoginResult, + LoginInput, + LoginMethod, + LoginStartResult, + MessageResult, + OAuthErrorCode, + OAuthProvider, + OAuthProvidersResult, + OAuthRedirectOutcome, + OAuthRedirectPort, + Organization, + OrganizationMembership, + OrganizationSwitchResult, + PasskeyAttachment, + PasskeyLoginData, + PasskeyMetadata, + PasskeyPolicyErrorCode, + PasskeyPort, + PasskeyPrfInput, + PasskeyPrfResult, + PasskeyRegistrationData, + PublicSystemConfigResult, + RegisterInput, + RegisterPasskeyOptions, + SeamlessAuthClient, + SeamlessAuthClientOptions, + SeamlessAuthResult, + StartOAuthLoginInput, + StartOAuthLoginResult, + StepUpMethod, + StepUpPrfData, + StepUpStatus, + StoredTokens, + TokenStoragePort, + TotpEnrollmentStartResult, + TotpStatus, + User, + WebAuthnErrorDetail, +} from '@seamless-auth/client'; diff --git a/packages/react-native/src/ports/nativePasskeys.ts b/packages/react-native/src/ports/nativePasskeys.ts new file mode 100644 index 0000000..73cffe7 --- /dev/null +++ b/packages/react-native/src/ports/nativePasskeys.ts @@ -0,0 +1,114 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { + PasskeyCeremonyError, + type AuthenticationResponseJSON, + type PasskeyPort, + type RegistrationResponseJSON, +} from '@seamless-auth/client'; + +/** + * The part of `react-native-passkeys` this port uses. Passed in rather than + * imported, for the same reason as the secure store: the library is a native + * module the application chooses to install. + * + * The request and response shapes are the WebAuthn JSON the auth API speaks, + * but the library declares its own copies of those types, so they are generic + * here and cast once at the seam rather than fought over. + */ +export interface NativePasskeysLike { + isSupported(): boolean; + create(request: CreateRequest): Promise; + get(request: GetRequest): Promise; +} + +/** + * Maps what the native library throws onto the DOMException names the client + * and its error readers already understand. The library surfaces the + * platform's own error codes; the ones that mean "the user did not complete + * it" become `NotAllowedError`, a duplicate becomes `InvalidStateError`, and + * anything else keeps its own name so it stays diagnosable. + */ +function toCeremonyError(thrown: unknown): PasskeyCeremonyError { + const error = thrown as { name?: unknown; code?: unknown; message?: unknown } | null; + const code = typeof error?.code === 'string' ? error.code : undefined; + const rawName = typeof error?.name === 'string' ? error.name : 'UnknownError'; + const message = + typeof error?.message === 'string' ? error.message : 'Passkey ceremony failed.'; + + const cancelled = /cancel|abort|dismiss|NotAllowed|UserCancelled|1001/i; + const duplicate = /InvalidState|exists|excluded|already/i; + + const name = cancelled.test(`${rawName} ${code ?? ''} ${message}`) + ? 'NotAllowedError' + : duplicate.test(`${rawName} ${code ?? ''} ${message}`) + ? 'InvalidStateError' + : rawName; + + return new PasskeyCeremonyError(name, message, code ?? name, thrown); +} + +/** + * Passkeys through the platform's native APIs (ASAuthorization on iOS, + * Credential Manager on Android) via `react-native-passkeys`. + * + * The relying party must be an associated domain of the app. There is no + * `localhost` exemption on either platform, so this works only against a + * hosted `apple-app-site-association` and `assetlinks.json`. + * + * ```ts + * import * as Passkeys from 'react-native-passkeys'; + * const passkeys = createNativePasskeyPort(Passkeys); + * ``` + */ +export function createNativePasskeyPort( + native: NativePasskeysLike +): PasskeyPort { + return { + isSupported: () => native.isSupported(), + + // A mobile platform that supports passkeys at all has a platform + // authenticator: that is what the biometric prompt is. + isPlatformAuthenticatorAvailable: async () => native.isSupported(), + + async create(optionsJSON) { + let result: RegistrationResponseJSON | null; + try { + result = (await native.create( + optionsJSON as unknown as CreateRequest + )) as RegistrationResponseJSON | null; + } catch (error) { + throw toCeremonyError(error); + } + if (!result) { + throw new PasskeyCeremonyError( + 'NotAllowedError', + 'Passkey registration was cancelled.' + ); + } + return result; + }, + + async get(optionsJSON) { + let result: AuthenticationResponseJSON | null; + try { + result = (await native.get( + optionsJSON as unknown as GetRequest + )) as AuthenticationResponseJSON | null; + } catch (error) { + throw toCeremonyError(error); + } + if (!result) { + throw new PasskeyCeremonyError( + 'NotAllowedError', + 'Passkey sign-in was cancelled.' + ); + } + return result; + }, + }; +} diff --git a/packages/react-native/src/ports/secureStoreTokenStorage.ts b/packages/react-native/src/ports/secureStoreTokenStorage.ts new file mode 100644 index 0000000..1aefded --- /dev/null +++ b/packages/react-native/src/ports/secureStoreTokenStorage.ts @@ -0,0 +1,94 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import type { StoredTokens, TokenStoragePort } from '@seamless-auth/client'; + +/** + * The part of `expo-secure-store` this port uses. The module is passed in + * rather than imported, so an application that does not install it never has + * Metro fail the bundle on a module this package would otherwise require. + */ +export interface SecureStoreLike { + getItemAsync(key: string, options?: unknown): Promise; + setItemAsync(key: string, value: string, options?: unknown): Promise; + deleteItemAsync(key: string, options?: unknown): Promise; +} + +export interface SecureStoreTokenStorageOptions { + /** Keystore entry name. Defaults to `seamless-auth.session`. */ + key?: string; + /** Passed through to every `expo-secure-store` call, for `keychainAccessible` and the like. */ + storeOptions?: unknown; +} + +const DEFAULT_KEY = 'seamless-auth.session'; + +/** + * A bearer session in the platform keystore (Keychain on iOS, Keystore-backed + * encrypted storage on Android) through `expo-secure-store`. + * + * Never throws. A keystore that is locked, missing, or holding something that + * does not parse reads as no session, which signs the user out rather than + * breaking every request. + * + * ```ts + * import * as SecureStore from 'expo-secure-store'; + * const tokenStorage = createSecureStoreTokenStorage(SecureStore); + * ``` + */ +export function createSecureStoreTokenStorage( + store: SecureStoreLike, + options: SecureStoreTokenStorageOptions = {} +): TokenStoragePort { + const key = options.key ?? DEFAULT_KEY; + + return { + async get() { + try { + const raw = await store.getItemAsync(key, options.storeOptions); + if (!raw) return null; + + const parsed: unknown = JSON.parse(raw); + if ( + parsed && + typeof parsed === 'object' && + typeof (parsed as StoredTokens).accessToken === 'string' && + typeof (parsed as StoredTokens).refreshToken === 'string' + ) { + const { accessToken, refreshToken } = parsed as StoredTokens; + return { accessToken, refreshToken }; + } + return null; + } catch { + return null; + } + }, + + async set(tokens) { + try { + await store.setItemAsync( + key, + JSON.stringify({ + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken, + }), + options.storeOptions + ); + } catch { + // A keystore that refuses the write leaves the session in memory for + // this process only. The next launch starts signed out. + } + }, + + async remove() { + try { + await store.deleteItemAsync(key, options.storeOptions); + } catch { + // Nothing to do: the entry is either gone or was never written. + } + }, + }; +} diff --git a/packages/react-native/src/ports/webBrowserOAuthRedirect.ts b/packages/react-native/src/ports/webBrowserOAuthRedirect.ts new file mode 100644 index 0000000..4eebfad --- /dev/null +++ b/packages/react-native/src/ports/webBrowserOAuthRedirect.ts @@ -0,0 +1,77 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import type { OAuthRedirectPort } from '@seamless-auth/client'; + +/** + * The part of `expo-web-browser` this port uses. Passed in rather than + * imported, like the other native modules. + */ +export interface WebBrowserLike { + openAuthSessionAsync( + url: string, + redirectUrl?: string, + options?: unknown + ): Promise<{ type: string; url?: string }>; +} + +/** + * Reads `code` and `state` off the URL the provider sent the user back to. + * Exported for the screens that handle a deep link themselves. + */ +export function parseOAuthCallbackUrl( + url: string +): { code: string; state: string } | null { + let params: URLSearchParams; + try { + params = new URL(url).searchParams; + } catch { + // A custom scheme such as `myapp://oauth/callback?code=...` does not + // always parse as a URL on every runtime; fall back to the query string. + const query = url.split('?')[1]; + if (!query) return null; + params = new URLSearchParams(query.split('#')[0]); + } + + const code = params.get('code'); + const state = params.get('state'); + return code && state ? { code, state } : null; +} + +/** + * Opens the provider in an in-app browser session (`ASWebAuthenticationSession` + * on iOS, a Custom Tab on Android) and hands the callback straight back, so + * the sign-in finishes without the app being reopened through a deep link. + * + * `redirectUri` must be the one the provider returns to, registered with the + * provider and allowed by the auth API: a universal link or the app's scheme. + * + * ```ts + * import * as WebBrowser from 'expo-web-browser'; + * const oauthRedirect = createWebBrowserOAuthRedirect(WebBrowser); + * ``` + */ +export function createWebBrowserOAuthRedirect( + browser: WebBrowserLike, + options?: unknown +): OAuthRedirectPort { + return { + async open(authorizationUrl, redirectUri) { + const result = await browser.openAuthSessionAsync( + authorizationUrl, + redirectUri, + options + ); + + if (result.type !== 'success' || !result.url) { + return { type: 'cancelled' }; + } + + const callback = parseOAuthCallbackUrl(result.url); + return callback ? { type: 'callback', ...callback } : { type: 'cancelled' }; + }, + }; +} diff --git a/packages/react-native/tests/ports.test.ts b/packages/react-native/tests/ports.test.ts new file mode 100644 index 0000000..fd4f70f --- /dev/null +++ b/packages/react-native/tests/ports.test.ts @@ -0,0 +1,265 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { PasskeyCeremonyError } from '@seamless-auth/client'; + +import { describeDevice } from '../src/deviceInfo'; +import { createNativePasskeyPort } from '../src/ports/nativePasskeys'; +import { createSecureStoreTokenStorage } from '../src/ports/secureStoreTokenStorage'; +import { + createWebBrowserOAuthRedirect, + parseOAuthCallbackUrl, +} from '../src/ports/webBrowserOAuthRedirect'; + +function fakeSecureStore(initial: Record = {}) { + const items = new Map(Object.entries(initial)); + return { + items, + getItemAsync: jest.fn( + async (key: string, _options?: unknown) => items.get(key) ?? null + ), + setItemAsync: jest.fn(async (key: string, value: string, _options?: unknown) => { + items.set(key, value); + }), + deleteItemAsync: jest.fn(async (key: string, _options?: unknown) => { + items.delete(key); + }), + }; +} + +describe('createSecureStoreTokenStorage', () => { + it('round-trips the pair as one keystore entry', async () => { + const store = fakeSecureStore(); + const storage = createSecureStoreTokenStorage(store); + + await storage.set({ accessToken: 'a', refreshToken: 'r' }); + expect(store.setItemAsync).toHaveBeenCalledWith( + 'seamless-auth.session', + JSON.stringify({ accessToken: 'a', refreshToken: 'r' }), + undefined + ); + + await expect(storage.get()).resolves.toEqual({ accessToken: 'a', refreshToken: 'r' }); + + await storage.remove(); + await expect(storage.get()).resolves.toBeNull(); + }); + + it('uses the configured key and passes store options through', async () => { + const store = fakeSecureStore(); + const storeOptions = { keychainAccessible: 'whenUnlocked' }; + const storage = createSecureStoreTokenStorage(store, { + key: 'app.session', + storeOptions, + }); + + await storage.set({ accessToken: 'a', refreshToken: 'r' }); + await storage.get(); + await storage.remove(); + + expect(store.setItemAsync.mock.calls[0][0]).toBe('app.session'); + expect(store.setItemAsync.mock.calls[0][2]).toBe(storeOptions); + expect(store.getItemAsync).toHaveBeenCalledWith('app.session', storeOptions); + expect(store.deleteItemAsync).toHaveBeenCalledWith('app.session', storeOptions); + }); + + it('reads anything it cannot parse as no session', async () => { + const storage = createSecureStoreTokenStorage( + fakeSecureStore({ 'seamless-auth.session': 'not json' }) + ); + await expect(storage.get()).resolves.toBeNull(); + + const partial = createSecureStoreTokenStorage( + fakeSecureStore({ 'seamless-auth.session': JSON.stringify({ accessToken: 'a' }) }) + ); + await expect(partial.get()).resolves.toBeNull(); + }); + + it('never throws when the keystore does', async () => { + const failing = { + getItemAsync: jest.fn(async () => { + throw new Error('locked'); + }), + setItemAsync: jest.fn(async () => { + throw new Error('locked'); + }), + deleteItemAsync: jest.fn(async () => { + throw new Error('locked'); + }), + }; + const storage = createSecureStoreTokenStorage(failing); + + await expect(storage.get()).resolves.toBeNull(); + await expect( + storage.set({ accessToken: 'a', refreshToken: 'r' }) + ).resolves.toBeUndefined(); + await expect(storage.remove()).resolves.toBeUndefined(); + }); +}); + +describe('createNativePasskeyPort', () => { + const native = () => ({ + isSupported: jest.fn(() => true), + create: jest.fn(), + get: jest.fn(), + }); + + it('runs the ceremonies through the native module with the JSON it was handed', async () => { + const module = native(); + module.create.mockResolvedValue({ id: 'cred-1' }); + module.get.mockResolvedValue({ id: 'cred-1', response: {} }); + const port = createNativePasskeyPort(module); + + const creation = { challenge: 'c' } as never; + const request = { challenge: 'c' } as never; + + await expect(port.create(creation)).resolves.toEqual({ id: 'cred-1' }); + await expect(port.get(request)).resolves.toMatchObject({ id: 'cred-1' }); + expect(module.create).toHaveBeenCalledWith(creation); + expect(module.get).toHaveBeenCalledWith(request); + expect(port.isSupported()).toBe(true); + await expect(port.isPlatformAuthenticatorAvailable()).resolves.toBe(true); + }); + + it('reports a null result as a dismissed prompt', async () => { + const module = native(); + module.create.mockResolvedValue(null); + module.get.mockResolvedValue(null); + const port = createNativePasskeyPort(module); + + await expect(port.create({} as never)).rejects.toMatchObject({ + name: 'NotAllowedError', + code: 'NotAllowedError', + }); + await expect(port.get({} as never)).rejects.toBeInstanceOf(PasskeyCeremonyError); + }); + + it.each([ + [ + { name: 'Error', code: 'UserCancelled', message: 'The user cancelled' }, + 'NotAllowedError', + ], + [ + { name: 'ASAuthorizationError', code: '1001', message: 'canceled' }, + 'NotAllowedError', + ], + [ + { + name: 'Error', + code: 'CreateCredentialException', + message: 'credential already exists', + }, + 'InvalidStateError', + ], + [ + { name: 'SecurityError', code: 'RP_MISMATCH', message: 'rp id mismatch' }, + 'SecurityError', + ], + ])('maps a native failure %j onto %s', async (thrown, expectedName) => { + const module = native(); + module.create.mockRejectedValue(Object.assign(new Error(thrown.message), thrown)); + const port = createNativePasskeyPort(module); + + const error = await port.create({} as never).catch(e => e); + + expect(error).toBeInstanceOf(PasskeyCeremonyError); + expect(error.name).toBe(expectedName); + expect(error.code).toBe(thrown.code); + expect(error.cause).toMatchObject({ message: thrown.message }); + }); + + it('keeps an unrecognised failure diagnosable', async () => { + const module = native(); + module.get.mockRejectedValue('string failure'); + const port = createNativePasskeyPort(module); + + const error = await port.get({} as never).catch(e => e); + + expect(error.name).toBe('UnknownError'); + expect(error.message).toBe('Passkey ceremony failed.'); + }); +}); + +describe('parseOAuthCallbackUrl', () => { + it('reads code and state from an https callback', () => { + expect( + parseOAuthCallbackUrl('https://app.example.com/oauth/callback?code=c1&state=s1#x') + ).toEqual({ code: 'c1', state: 's1' }); + }); + + it('reads code and state from a custom scheme', () => { + expect(parseOAuthCallbackUrl('roxtarget://oauth/callback?state=s1&code=c1')).toEqual({ + code: 'c1', + state: 's1', + }); + }); + + it('returns null when either value is missing', () => { + expect( + parseOAuthCallbackUrl('https://app.example.com/oauth/callback?code=c1') + ).toBeNull(); + expect(parseOAuthCallbackUrl('roxtarget://oauth/callback')).toBeNull(); + }); +}); + +describe('createWebBrowserOAuthRedirect', () => { + it('opens the provider in an auth session and hands the callback back', async () => { + const browser = { + openAuthSessionAsync: jest.fn(async () => ({ + type: 'success', + url: 'roxtarget://oauth/callback?code=c1&state=s1', + })), + }; + const options = { preferEphemeralSession: true }; + + const outcome = await createWebBrowserOAuthRedirect(browser, options).open( + 'https://idp.example.com/authorize', + 'roxtarget://oauth/callback' + ); + + expect(browser.openAuthSessionAsync).toHaveBeenCalledWith( + 'https://idp.example.com/authorize', + 'roxtarget://oauth/callback', + options + ); + expect(outcome).toEqual({ type: 'callback', code: 'c1', state: 's1' }); + }); + + it.each([ + [{ type: 'cancel' }], + [{ type: 'dismiss' }], + [{ type: 'success', url: 'roxtarget://oauth/callback?error=access_denied' }], + ])('reports %j as cancelled', async result => { + const browser = { openAuthSessionAsync: jest.fn(async () => result) }; + + await expect( + createWebBrowserOAuthRedirect(browser).open( + 'https://idp.example.com', + 'roxtarget://cb' + ) + ).resolves.toEqual({ type: 'cancelled' }); + }); +}); + +describe('describeDevice', () => { + it('describes an iPhone', () => { + expect(describeDevice({ OS: 'ios', Version: '26.0' })).toEqual({ + friendlyName: 'iOS device', + platform: 'ios', + browser: 'native', + deviceInfo: 'iOS 26.0', + }); + }); + + it('describes an Android device with a chosen name', () => { + expect(describeDevice({ OS: 'android', Version: 36 }, 'Pixel')).toEqual({ + friendlyName: 'Pixel', + platform: 'android', + browser: 'native', + deviceInfo: 'Android 36', + }); + }); +}); diff --git a/packages/react-native/tests/provider.test.tsx b/packages/react-native/tests/provider.test.tsx new file mode 100644 index 0000000..02123b8 --- /dev/null +++ b/packages/react-native/tests/provider.test.tsx @@ -0,0 +1,178 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the GNU Affero General Public License v3.0 + * See LICENSE file in the project root for full license information + */ + +import { act, render, screen, waitFor } from '@testing-library/react'; +import React from 'react'; + +import { AuthProvider, useAuth } from '../src/AuthProvider'; +import { useAuthClient } from '../src/hooks/useAuthClient'; +import { useAuthorizedFetch } from '../src/hooks/useAuthorizedFetch'; +import { useLoginMethods } from '../src/hooks/useLoginMethods'; +import { usePasskeySupport } from '../src/hooks/usePasskeySupport'; +import { createSecureStoreTokenStorage } from '../src/ports/secureStoreTokenStorage'; + +const API = 'https://api.example.com'; + +function json(status: number, body: unknown) { + return { + ok: status < 400, + status, + json: async () => body, + clone() { + return { json: async () => body }; + }, + } as unknown as Response; +} + +const passkeys = { + isSupported: () => true, + isPlatformAuthenticatorAvailable: async () => true, + create: jest.fn(), + get: jest.fn(), +}; + +function fakeSecureStore(initial: Record = {}) { + const items = new Map(Object.entries(initial)); + return { + getItemAsync: async (key: string) => items.get(key) ?? null, + setItemAsync: async (key: string, value: string) => { + items.set(key, value); + }, + deleteItemAsync: async (key: string) => { + items.delete(key); + }, + items, + }; +} + +const Consumer = () => { + const auth = useAuth(); + const client = useAuthClient(); + const authorizedFetch = useAuthorizedFetch(); + const { passkeySupported, loading: passkeyLoading } = usePasskeySupport(); + const { loginMethods } = useLoginMethods(); + + return ( + <> + {auth.user ? auth.user.email : 'none'} + {String(auth.loading)} + {String(client === auth.client)} + + {String(authorizedFetch === auth.client.authorizedFetch)} + + + {passkeyLoading ? 'checking' : String(passkeySupported)} + + {loginMethods?.join(',') ?? 'unknown'} + + ); +}; + +describe('AuthProvider (react-native)', () => { + it('restores a session from the keystore over bearer transport', async () => { + const store = fakeSecureStore({ + 'seamless-auth.session': JSON.stringify({ + accessToken: 'access-1', + refreshToken: 'r-1', + }), + }); + const calls: Array<{ url: string; init: RequestInit }> = []; + const fetchImpl = jest.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + calls.push({ url: String(input), init: init ?? {} }); + if (String(input).endsWith('/users/me')) { + return json(200, { + user: { id: 'u1', email: 'user@example.com', phone: null, roles: ['athlete'] }, + credentials: [], + }); + } + return json(200, { loginMethods: ['passkey', 'email_otp'] }); + }) as unknown as typeof fetch; + + await act(async () => { + render( + + + + ); + }); + + await waitFor(() => + expect(screen.getByTestId('user')).toHaveTextContent('user@example.com') + ); + expect(screen.getByTestId('same-client')).toHaveTextContent('true'); + expect(screen.getByTestId('same-fetch')).toHaveTextContent('true'); + await waitFor(() => expect(screen.getByTestId('passkeys')).toHaveTextContent('true')); + await waitFor(() => + expect(screen.getByTestId('methods')).toHaveTextContent('passkey,email_otp') + ); + + const me = calls.find(c => c.url === `${API}/auth/users/me`); + expect(me).toBeDefined(); + expect((me!.init.headers as Record).Authorization).toBe( + 'Bearer access-1' + ); + expect( + (me!.init.headers as Record)['x-seamless-auth-transport'] + ).toBe('bearer'); + expect(me!.init.credentials).toBeUndefined(); + }); + + it('starts signed out when the keystore is empty, without asking for a refresh', async () => { + const calls: string[] = []; + const fetchImpl = jest.fn(async (input: RequestInfo | URL) => { + calls.push(String(input)); + return json(401, { error: 'unauthenticated' }); + }) as unknown as typeof fetch; + + await act(async () => { + render( + + + + ); + }); + + await waitFor(() => expect(screen.getByTestId('loading')).toHaveTextContent('false')); + expect(screen.getByTestId('user')).toHaveTextContent('none'); + expect(calls.filter(url => url.endsWith('/refresh'))).toHaveLength(0); + }); + + it('honours a custom mount path', async () => { + const calls: string[] = []; + const fetchImpl = jest.fn(async (input: RequestInfo | URL) => { + calls.push(String(input)); + return json(401, {}); + }) as unknown as typeof fetch; + + await act(async () => { + render( + + + + ); + }); + + await waitFor(() => expect(calls).toContain(`${API}/identity/users/me`)); + }); + + it('throws when useAuth is used outside the provider', () => { + const spy = jest.spyOn(console, 'error').mockImplementation(() => undefined); + try { + expect(() => render()).toThrow(/within an AuthProvider/); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/packages/react-native/tsconfig.build.json b/packages/react-native/tsconfig.build.json new file mode 100644 index 0000000..22f66ac --- /dev/null +++ b/packages/react-native/tsconfig.build.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "declaration": true, + "declarationDir": "./dist", + "outDir": "./dist", + "sourceMap": true, + "rootDir": "./src", + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["src"], + "exclude": ["tests", "**/*.test.ts", "**/*.spec.ts"] +} diff --git a/packages/react-native/tsconfig.dev.json b/packages/react-native/tsconfig.dev.json new file mode 100644 index 0000000..a6668d6 --- /dev/null +++ b/packages/react-native/tsconfig.dev.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "include": ["src", "tests", "../../jest.setup.ts"] +} diff --git a/packages/react-native/tsconfig.json b/packages/react-native/tsconfig.json new file mode 100644 index 0000000..9b7c6d3 --- /dev/null +++ b/packages/react-native/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "paths": { + "@/*": ["./src/*"], + "@seamless-auth/client": ["../client/src/index.ts"] + } + } +} From ddcdd8f351d87b9cca492a27bfffa17be37b1739 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 12 Sep 2026 21:29:30 -0700 Subject: [PATCH 2/3] fix(client): flatten Headers instances before merging request headers Spreading a Headers instance copies its internals rather than its entries. On React Native the polyfill keeps a map field, and the nested object made Expo's native fetch refuse every authorizedFetch call whose caller built its headers with new Headers(). The caller's headers are now read as entries, whatever shape they came in, and replace a default of the same name case-insensitively instead of travelling beside it. --- packages/client/src/transport.ts | 46 +++++++++++++++++--- packages/client/tests/transport.node.test.ts | 29 ++++++++++++ 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/packages/client/src/transport.ts b/packages/client/src/transport.ts index 74e42a9..f9da6aa 100644 --- a/packages/client/src/transport.ts +++ b/packages/client/src/transport.ts @@ -111,6 +111,31 @@ function buildUrl(apiHost: string, basePath: string, path: string): string { return `${host}${mount}${path}`; } +/** + * The caller's headers as a plain object, whatever shape they came in. + * + * A `Headers` instance or an entries array cannot be spread: spreading a + * `Headers` copies its internals (React Native's polyfill keeps a `map` + * field), and the resulting nested object makes the native fetch on Expo + * refuse the whole request. + */ +function plainHeaders(headers: HeadersInit | undefined): Record { + if (!headers) return {}; + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + // Duck-typed rather than `instanceof Headers`, so a polyfilled instance + // from another realm is flattened too. + if (typeof (headers as Headers).forEach === 'function') { + const out: Record = {}; + (headers as Headers).forEach((value, key) => { + out[key] = value; + }); + return out; + } + return { ...(headers as Record) }; +} + function withHeaders( init: RequestInit | undefined, extra: Record @@ -119,14 +144,21 @@ function withHeaders( // proxies reject a bodyless GET that advertises a request content type. const hasBody = init?.body != null; - return { - ...init, - headers: { - ...(hasBody ? { 'Content-Type': 'application/json' } : {}), - ...extra, - ...init?.headers, - }, + const headers: Record = { + ...(hasBody ? { 'Content-Type': 'application/json' } : {}), + ...extra, }; + // Header names are case-insensitive, and a `Headers` instance lower-cases + // them, so the caller's `content-type` replaces the default `Content-Type` + // rather than travelling beside it. + for (const [name, value] of Object.entries(plainHeaders(init?.headers))) { + for (const existing of Object.keys(headers)) { + if (existing.toLowerCase() === name.toLowerCase()) delete headers[existing]; + } + headers[name] = value; + } + + return { ...init, headers }; } interface SessionBody { diff --git a/packages/client/tests/transport.node.test.ts b/packages/client/tests/transport.node.test.ts index a365042..b68044d 100644 --- a/packages/client/tests/transport.node.test.ts +++ b/packages/client/tests/transport.node.test.ts @@ -428,6 +428,35 @@ describe('bearer transport', () => { expect(headersOf(calls[0])).toEqual({ Authorization: 'Bearer access-1' }); }); + it('authorizedFetch flattens Headers instances and entry arrays into plain headers', async () => { + const storage = createMemoryTokenStorage(); + await storage.set({ accessToken: 'access-1', refreshToken: 'refresh-1' }); + const { calls, fetchImpl } = scriptedFetch(() => jsonResponse(200, {})); + const transport = bearer(fetchImpl, storage); + + const asInstance = new Headers(); + asInstance.set('Content-Type', 'application/json'); + await transport.authorizedFetch(`${API}/api/plan`, { + method: 'POST', + body: '{}', + headers: asInstance, + }); + await transport.authorizedFetch(`${API}/api/plan`, { + headers: [['X-Trace', 'abc']], + }); + + // Spreading a Headers instance would have produced an object with no + // usable keys (or a nested `map` on React Native) and lost the header. + expect(headersOf(calls[0])).toEqual({ + Authorization: 'Bearer access-1', + 'content-type': 'application/json', + }); + expect(headersOf(calls[1])).toEqual({ + Authorization: 'Bearer access-1', + 'X-Trace': 'abc', + }); + }); + it('authorizedFetch refreshes once on a 401 and retries', async () => { const storage = createMemoryTokenStorage(); await storage.set({ accessToken: 'access-old', refreshToken: 'refresh-old' }); From 48009947f0d506941c1cb74d006a2e22643c55db Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 12 Sep 2026 21:36:46 -0700 Subject: [PATCH 3/3] fix(client): send authorizedFetch calls under the adapter mount as adapter calls An application reaching the adapter's own routes through authorizedFetch (its session list, a passthrough it adds) got no transport header, so in bearer transport the adapter answered in cookie mode and refused the call. A URL under the mount now takes the same road as the client's own calls: the header, the route's identity, and its effect on the held tokens. --- packages/client/README.md | 5 +- packages/client/src/transport.ts | 51 ++++++++++++-------- packages/client/tests/transport.node.test.ts | 17 +++++++ packages/react-native/README.md | 3 +- 4 files changed, 54 insertions(+), 22 deletions(-) diff --git a/packages/client/README.md b/packages/client/README.md index 74d529b..963e3e8 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -56,7 +56,10 @@ mirroring the server adapter's own map. `client.authorizedFetch(input, init)` is a fetch for the application's own API that carries the session the same way: cookies in cookie transport, the access token with one refresh-and-retry on a 401 in bearer transport. It never reads -tokens out of the response, since that body is the application's. +tokens out of the response, since that body is the application's. A URL under +the adapter's own mount (`/auth/sessions`, a passthrough the adapter adds) is +sent the way the client's own calls are, transport header included, so an +application can reach every adapter route through the one fetch. ## Ports diff --git a/packages/client/src/transport.ts b/packages/client/src/transport.ts index f9da6aa..1e65ae1 100644 --- a/packages/client/src/transport.ts +++ b/packages/client/src/transport.ts @@ -347,29 +347,40 @@ export function createTransport(options: TransportOptions): Transport { return response; } + const mount = `${buildUrl(options.apiHost, basePath, '')}/`; + + const fetchUnderMount: FetchWithAuth = async (input, init) => { + const path = normalizePath(input); + const rule = resolveRouteRule(path); + + const response = await sendWithRefresh( + buildUrl(options.apiHost, basePath, path), + init, + rule.identity, + true + ); + + if (response.ok && rule.effect) { + await applyEffect(rule.effect, response); + } + + return response; + }; + return { mode, clearTokens, - fetch: async (input, init) => { - const path = normalizePath(input); - const rule = resolveRouteRule(path); - - const response = await sendWithRefresh( - buildUrl(options.apiHost, basePath, path), - init, - rule.identity, - true - ); - - if (response.ok && rule.effect) { - await applyEffect(rule.effect, response); - } - - return response; - }, + fetch: fetchUnderMount, // The transport header is the adapter's; an application's own API only - // needs the bearer token, which requireAuth reads. - authorizedFetch: (input, init) => - sendWithRefresh(String(input), init, 'access', false), + // needs the bearer token, which requireAuth reads. A URL under the + // adapter's own mount (its session list, a passthrough it adds) is the + // adapter's, though, and without the header it would answer in cookie + // mode, so it takes the same road as the client's own calls. + authorizedFetch: (input, init) => { + const url = String(input); + return url.startsWith(mount) + ? fetchUnderMount(url.slice(mount.length - 1), init) + : sendWithRefresh(url, init, 'access', false); + }, }; } diff --git a/packages/client/tests/transport.node.test.ts b/packages/client/tests/transport.node.test.ts index b68044d..cf0d2ed 100644 --- a/packages/client/tests/transport.node.test.ts +++ b/packages/client/tests/transport.node.test.ts @@ -457,6 +457,23 @@ describe('bearer transport', () => { }); }); + it('authorizedFetch treats a URL under the adapter mount as an adapter call', async () => { + const storage = createMemoryTokenStorage(); + await storage.set({ accessToken: 'access-1', refreshToken: 'refresh-1' }); + const { calls, fetchImpl } = scriptedFetch(() => jsonResponse(200, { sessions: [] })); + + const response = await bearer(fetchImpl, storage).authorizedFetch(`${API}/auth/sessions`, { + method: 'GET', + }); + + expect(response.status).toBe(200); + expect(calls[0].url).toBe(`${API}/auth/sessions`); + expect(headersOf(calls[0])).toEqual({ + Authorization: 'Bearer access-1', + [AUTH_TRANSPORT_HEADER]: 'bearer', + }); + }); + it('authorizedFetch refreshes once on a 401 and retries', async () => { const storage = createMemoryTokenStorage(); await storage.set({ accessToken: 'access-old', refreshToken: 'refresh-old' }); diff --git a/packages/react-native/README.md b/packages/react-native/README.md index 639fdf1..5f21fcc 100644 --- a/packages/react-native/README.md +++ b/packages/react-native/README.md @@ -91,7 +91,8 @@ function SignIn() { ``` `useAuthorizedFetch()` is a fetch for your own API that carries the access -token and refreshes it once on a 401; a path resolves on `apiHost`: +token and refreshes it once on a 401; a path resolves on `apiHost`, and a path +under the adapter's mount (`/auth/sessions`) is sent as an adapter call: ```ts const authorizedFetch = useAuthorizedFetch();