Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@unleash/proxy

Package Overview
Dependencies
Maintainers
5
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@unleash/proxy

The Unleash Proxy (Open-Source)

  • 0.12.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5.8K
increased by113.84%
Maintainers
5
Weekly downloads
 
Created
Source

Build & Tests npm Docker Pulls

The Unleash Proxy

The Unleash Proxy simplifies integration with frontend & native applications running in the context of a specific user. The Unleash proxy sits between the proxy SDK and the Unleash API and ensures that your internal feature toggle configuration is not exposed to the world.

The proxy offers:

  • High performance - a single proxy instance can handle thousands req/s, and can be horizontally scaled.
  • Privacy for end-users - Your end users are not exposed to the unleash API and can be hosted by you This ensures no user data (userId, IPs, etc) is shared.
  • Secure - It is controlled by you, and can hosted on your domain. In addition no feature toggle configuration is shared with the user, only evaluated toggles.

You can read more about the proxy in our documentation

Run The Unleash Proxy

The Unleash proxy is a small stateless HTTP application you run. The only requirement is that it needs to be able to talk with the Unleash API (either Unleash OSS or Unleash Hosted).

Run with Docker

The easies way to run Unleash is via Docker. We have published a docker image on docker hub.

Step 1: Pull

docker pull unleashorg/unleash-proxy

Step 2: Start

docker run \
   -e UNLEASH_PROXY_CLIENT_KEYS=some-secret \
   -e UNLEASH_URL=https://app.unleash-hosted.com/demo/api/ \
   -e UNLEASH_API_TOKEN=56907a2fa53c1d16101d509a10b78e36190b0f918d9f122d \
   -p 3000:3000 \
   unleashorg/unleash-proxy

You should see the following output:

Unleash-proxy is listening on port 3000!

Step 3: verify

In order to verify the proxy you can use curl and see that you get a few evaluated feature toggles back:

curl http://localhost:3000/proxy -H "Authorization: some-secret"  

Expected output would be something like:

{
	"toggles": [{
		"name": "demo",
		"enabled": true,
		"variant": {
			"name": "disabled",
			"enabled": false
		}
	}, {
		"name": "demoApp.step1",
		"enabled": true,
		"variant": {
			"name": "disabled",
			"enabled": false
		}
	}]
}

Health endpoint

The proxy will try to synchronize with the Unleash API at startup, until it has successfully done that the proxy will return HTTP 503 - Not Read? for all request. You can use the health endpoint to validate that the proxy is ready to recieve requests:

curl http://localhost:3000/proxy/health -I
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag
Content-Type: text/html; charset=utf-8
Content-Length: 2
ETag: W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"
Date: Fri, 04 Jun 2021 10:38:27 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Available options

OptionEnvironment VariableDefault valueRequiredDescription
unleashUrlUNLEASH_URLn/ayesAPI Url to the Unleash instance to connect to
unleashApiTokenUNLEASH_API_TOKENn/ayesAPI token (client) needed to connect to Unleash API.
clientKeysUNLEASH_PROXY_CLIENT_KEYSn/ayesList of client keys that the proxy should accept. When querying the proxy, Proxy SDKs must set the request's client keys header to one of these values. The default client keys header is Authorization.
proxySecretsUNLEASH_PROXY_SECRETSn/anoDeprecated alias for clientKeys. Please use clientKeys instead.
n/aPORT or PROXY_PORT3000noThe port where the proxy should listen.
proxyBasePathPROXY_BASE_PATH""noThe base path to run the proxy from. "/proxy" will be added at the end. For instance, if proxyBasePath is "base/path", the proxy will run at /base/path/proxy.
unleashAppNameUNLEASH_APP_NAME"unleash-proxy"noApp name to used when registering with Unleash
unleashInstanceIdUNLEASH_INSTANCE_IDgeneratednoUnleash instance id to used when registering with Unleash
refreshIntervalUNLEASH_FETCH_INTERVAL5000noHow often the proxy should query Unleash for updates, defined in ms.
metricsIntervalUNLEASH_METRICS_INTERVAL30000noHow often the proxy should send usage metrics back to Unleash, defined in ms.
environmentUNLEASH_ENVIRONMENTundefinednoIf set this will be the environment used by the proxy in the Unleash Context. It will not be possible for proxy SDKs to override the environment if set.
projectNameUNLEASH_PROJECT_NAMEundefinednoThe projectName (id) to fetch feature toggles for. The proxy will only return know about feature toggles that belongs to the project, if specified.
loggern/aSimpleLoggernoRegister a custom logger.
useJsonLoggerJSON_LOGGERfalsenoSets the default logger to log as one-line JSON. This has no effect if a custom logger is provided.
logLevelLOG_LEVEL "warn"noUsed to set logLevel. Supported options: "debug", "info", "warn", "error" and "fatal"
customStrategiesUNLEASH_CUSTOM_STRATEGIES_FILE[]noUse this option to inject implementation of custom activation strategies. If you are using UNLEASH_CUSTOM_STRATEGIES_FILE you need to provide a valid path to a javascript file which exports an array of custom activation strategies and the SDK will automatically load these
trustProxyTRUST_PROXY falsenoBy enabling the trustProxy option, Unleash Proxy will have knowledge that it's sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed. The proxy will automatically enrich the ip address in the Unleash Context. Can either be true/false (Trust all proxies), trust only given IP/CIDR (e.g. '127.0.0.1') as a string. May be a list of comma separated values (e.g. '127.0.0.1,192.168.1.1/24'
namePrefixUNLEASH_NAME_PREFIXundefinednoUsed to filter features by using prefix when requesting backend values.
tagsUNLEASH_TAGSundefinednoUsed to filter features by using tags set for features. Format should be tagName:tagValue,tagName2:tagValue2
clientKeysHeaderNameCLIENT_KEY_HEADER_NAME"authorization"noThe name of the HTTP header to use for client keys. Incoming requests must set the value of this header to one of the Proxy's clientKeys to be authorized successfully.
storageProvidern/aundefinednoRegister a custom storage provider. Refer to the section on custom storage providers in the Node.js SDK's readme for more information.
enableOASENABLE_OASfalsenoSet to true to expose the proxy's OpenAPI spec at /docs/openapi.json and an interactive OpenAPI UI at /docs/openapi. Read more in the OpenAPI section.
enableAllEndpointENABLE_ALL_ENDPOINTfalsenoSet to true to expose the /proxy/all endpoint. Refer to the section on returning all toggles for more info.
corsn/an/anoPass custom options for CORS module
cors.allowedHeadersCORS_ALLOWED_HEADERSn/anoHeaders to allow for CORS
cors.credentialsCORS_CREDENTIALSfalsenoAllow credentials in CORS requests
cors.exposedHeadersCORS_EXPOSED_HEADERS"ETag"noHeaders to expose for CORS
cors.maxAgeCORS_MAX_AGE172800noMaximum number of seconds to cache CORS results
cors.methodsCORS_METHODS"GET, POST"noMethods to allow for CORS
cors.optionsSuccessStatusCORS_OPTIONS_SUCCESS_STATUS204noIf the Options call passes CORS, which http status to return
cors.originCORS_ORIGIN*noOrigin URL or list of comma separated list of URLs to whitelist for CORS
cors.preflightContinueCORS_PREFLIGHT_CONTINUEfalseno

Experimental options

Some functionality is under validation and introduced as experimental, to allow us to test new functionality early. You should expect these to change in any future feature release.

OptionEnvironment VariableDefault valueRequiredDescription
expBootstrapn/an/anoWhere the Proxy can bootstrap configuration from. See Node.js SDK for details.
expBootstrap.urlEXP_BOOTSTRAP_URLn/anoUrl where the Proxy can bootstrap configuration from. See Node.js SDK for details.
expBootstrap.urlHeaders.AuthorizationEXP_BOOTSTRAP_AUTHORIZATIONn/anoAuthorization header value to be used when bootstrapping
expServerSideSdkConfig.tokensEXP_SERVER_SIDE_SDK_CONFIG_TOKENSn/anoAPI tokens that can be used by Server SDKs (and proxies) to read feature toggle configuration from this Proxy instance.
expCustomEnrichersEXP_CUSTOM_ENRICHERS_FILE[]noUse this option to inject implementation of custom context enrichers. If you are using EXP_CUSTOM_ENRICHERS_FILE you need to provide a valid path to a javascript file which exports an array of custom context enrichers and the SDK will automatically load these

Run with Node.js:

STEP 1: Install dependency

npm install @unleash/proxy

STEP 2: use in your code

const port = 3000;

const { createApp } = require('@unleash/proxy');


const app = createApp({
    unleashUrl: 'https://app.unleash-hosted.com/demo/api/',
    unleashApiToken: '56907a2fa53c1d16101d509a10b78e36190b0f918d9f122d',
    clientKeys: ['proxy-secret', 'another-proxy-secret', 's1'],
    refreshInterval: 1000,
    // logLevel: 'info',
    // projectName: 'order-team',
    // environment: 'development',
});

app.listen(port, () =>
    // eslint-disable-next-line no-console
    console.log(`Unleash Proxy listening on http://localhost:${port}/proxy`),
);

Proxy clients

To make the integration simple we have developed proxy client SDKs. You can find them all in our documentation:

OpenAPI

The proxy can optionally expose a runtime-generated OpenAPI JSON spec and a corresponding OpenAPI UI for its API. The OpenAPI UI page is an interactive page where you can discover and test the API endpoints the proxy exposes. The JSON spec can be used to generate an OpenAPI client with OpenAPI tooling such as the OpenAPI generator.

To enable the JSON spec and UI, set ENABLE_OAS (environment variable) or enableOAS (in-code configuration variable) to true.

The spec and UI can then be found at <base url>/docs/openapi.json and <base url>/docs/openapi respectively.

Return enabled and disabled toggles

By default, the proxy only returns enabled toggles. However, in certain use cases, you might want it to return all toggles, regardless of whether they're enabled or disabled. The /proxy/all endpoint does this.

Because returning all toggles regardless of their state is a potential security vulnerability, the endpoint has to be explicitly enabled. To enable it, set the enableAllEndpoint configuration option or the ENABLE_ALL_ENDPOINT environment variable to true.

POST API

The proxy also offers a POST API used to evaluate toggles This can be used to evaluate a list of know toggle names or to retrieve all enabled toggles for a given context.

a) Evaluate list of known toggles

This method will allow you to send a list of toggle names together with an Unleash Context and evaluate them accordingly. It will return enablement of all provided toggles.

URL: POST https://proxy-host.server/proxy

Content Type: application/json

Body:

{
	"toggles": ["demoApp.step1"],
	"context": {
		"appName": "someApp",
		"sessionId": "233312AFF22",
	}
}

Result:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag
Cache-control: public, max-age=2
Connection: keep-alive
Content-Length: 122
Content-Type: application/json; charset=utf-8
Date: Wed, 30 Nov 2022 14:46:48 GMT
ETag: W/"7a-RMKUyY0BWIhjahpVPWnNdXyDw6I"
Keep-Alive: timeout=5
Vary: Accept-Encoding

{
    "toggles": [
        {
            "enabled": false,
            "impressionData": true,
            "name": "demoApp.step1",
            "variant": {
                "enabled": false,
                "name": "disabled"
            }
        }
    ]
}

a) Evaluate all enabled toggles

This method will allow you to get all enabled toggles for a given context.

URL: POST https://proxy-host.server/proxy

Content Type: application/json

Body:

{
	"context": {
		"appName": "someApp",
		"sessionId": "233312AFF22",
	}
}

Result:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag
Cache-control: public, max-age=2
Connection: keep-alive
Content-Length: 465
Content-Type: application/json; charset=utf-8
Date: Wed, 30 Nov 2022 14:48:55 GMT
ETag: W/"1d1-dm6tkvMpkx42mZmojNSNKmHid1M"
Keep-Alive: timeout=5
Vary: Accept-Encoding

{
    "toggles": [
        {
            "enabled": true,
            "impressionData": false,
            "name": "demoApp.step2",
            "variant": {
                "enabled": true,
                "name": "userWithId",
                "payload": {
                    "type": "string",
                    "value": "90732934"
                }
            }
        },
        {
            "enabled": true,
            "impressionData": false,
            "name": "demoApp.step3",
            "variant": {
                "enabled": true,
                "name": "C",
                "payload": {
                    "type": "string",
                    "value": "hello"
                }
            }
        },
        {
            "enabled": true,
            "impressionData": true,
            "name": "demoApp.step4",
            "variant": {
                "enabled": true,
                "name": "Orange",
                "payload": {
                    "type": "string",
                    "value": "orange"
                }
            }
        }
    ]
}


Keywords

FAQs

Package last updated on 05 Dec 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc