# RequestShield Browser SDK

The RequestShield Browser SDK obtains single-use proof-of-work tokens and either attaches them automatically to configured Fetch and asynchronous XHR requests or returns them for application-controlled transport. The customer backend remains the authority that verifies a token and decides how to handle a missing token.

## Choose integration modes

Choose the frontend and backend modes independently:

| Side | Seamless | Manual |
| --- | --- | --- |
| Frontend (Browser SDK) | Configure `protect`; the SDK obtains and attaches a token to matching Fetch and asynchronous XHR requests. | Call `getToken()` and attach the returned token in application code. |
| Java backend | Use the Spring Boot 3 MVC starter and annotate the protected handler; the starter extracts the header, verifies the token and applies its enforcement policy. | Extract the token, call the Java core SDK's `verify(token)` and apply `VerificationResult` before the protected operation. |

For a new integration, prefer Seamless on both sides when the browser transport
is supported and the backend uses Spring Boot 3 MVC. Otherwise, prefer Manual
on both sides. All four combinations are supported, so an existing combination
or an explicit choice can be kept. Backend Seamless requires the token in
`X-IntelliFend-Token`, including when the frontend uses Manual mode.

`BLOCK` and `MONITOR` are Spring starter enforcement policies, separate from these
integration modes. Choosing frontend Seamless does not enable backend protection.

## Install

### npm / ESM

Install the SDK:

```console
npm install @intellifend/requestshieldjs
```

Import the API and initialize it with your app key:

```javascript
import { IntelliFend } from "@intellifend/requestshieldjs";

IntelliFend.init({
  appKey: "YOUR_APP_KEY",
  challengeUrl: "https://challenge.intellifend.ai",
  protect: ["/api/register"],
});
```

Without `challengeUrl`, the SDK uses `https://challenge.intellifend.ai`. If
IntelliFend supplies a different endpoint for your application, set it explicitly.
Pin the resolved version
in your application's lockfile for reproducible installations.

This SDK uses API v2 by default. Select API v1 with `apiVersion: "v1"` or
`data-api-version="v1"` on the script tag. The version is
separate from the service base URL; do not append `/v1` or `/v2` to
`challengeUrl`. Both versions use the same app key and backend token transport.

The ESM entry point exports `IntelliFend`, `IntelliFendError`, `VERSION`, and
TypeScript types. It does not attach a global or initialize itself. Use it in
browser applications with an ESM-capable toolchain.

### Script tag

You can also serve the packaged `dist/intellifend.js` file from your own static
host, together with the license and third-party notices. For example:

```html
<script
  src="/vendor/requestshield/intellifend.js"
  integrity="sha384-<digest-from-checksums.json>"
  crossorigin="anonymous"
  data-app-key="YOUR_APP_KEY"
  data-challenge-url="https://challenge.intellifend.ai"
  data-protect='["/api/register"]'
  defer>
</script>
```

Use the digest for `intellifend.js` from the packaged `dist/checksums.json`.
The script-tag build creates the `IntelliFend` global and initializes it from
script attributes. It never overwrites an existing `IntelliFend` global.
For an IntelliFend-hosted script, use the immutable URL and matching integrity
digest supplied for your SDK release.

### WebAssembly requirement

Version 2.0 requires WebAssembly, including when optional collection is disabled.
The module is embedded in the SDK bundle; it adds no separate module URL or
download. Pages enforcing CSP must allow `'wasm-unsafe-eval'` in `script-src`.
Existing script, service, and Web Worker permissions remain necessary.

`init()` is synchronous. If WebAssembly is unavailable, blocked, or fails,
`getToken()` resolves to `""`. Seamless mode sends the application
request without adding a token, and the backend applies its missing-token
policy. Test this path together with your CSP and browser requirements.

## Quick start

### Seamless mode

Pass the application endpoints that should receive a token in `protect`, as in
the initialization example above. To protect endpoints on another origin,
include their absolute HTTPS URLs:

```javascript
IntelliFend.init({
  appKey: "YOUR_APP_KEY",
  challengeUrl: "https://challenge.intellifend.ai",
  protect: ["/api/register", "https://api.example.com/login"],
});
```

The SDK adds `X-IntelliFend-Token` to matching Fetch and asynchronous XHR requests
when it obtains a non-empty token. Protect the corresponding business mutation
on the backend; browser matching and token attachment are not authorization
controls.

### Manual mode

Obtain a token immediately before the protected request and carry it unchanged. The header is the recommended carrier:

```javascript
const token = await IntelliFend.getToken({ action: "register" });
const headers = new Headers({ "Content-Type": "application/json" });

if (token) {
  headers.set("X-IntelliFend-Token", token);
}

await fetch("/api/register", {
  method: "POST",
  headers,
  body: JSON.stringify(formData),
});
```

`getToken()` returns `""` when it cannot obtain a token and never rejects. Continue the application request so the backend can apply its configured missing-token or availability policy.

## Configuration and API reference

### `IntelliFend.init(config)`

| Option | Required | Description |
| --- | --- | --- |
| `appKey` | Yes | Public app key supplied by IntelliFend. |
| `apiVersion` | No | Challenge API version: `"v1"` or `"v2"`. Defaults to `"v2"`. |
| `challengeUrl` | No | Absolute Challenge Server base URL. Defaults to `https://challenge.intellifend.ai`. It must use HTTP(S) and contain no credentials, query, or fragment. |
| `timeoutMs` | No | Positive whole-flow time budget for create, solve, verify, and retries. Defaults to 5,000 ms. |
| `protect` | No | Endpoint paths or URLs for Seamless mode, optionally containing named path parameters as described below. Omit or pass an empty list for Manual-only operation. |
| `telemetry` | No | Enables the optional browser signal collection on API v2. Default `false`; collection stays disabled on v1. |

`init()` validates synchronously and throws `IntelliFendError` with code `invalid_config` for invalid input. Reinitialization replaces the previous valid configuration; a failing reinitialization leaves that configuration in place. Unknown configuration keys are ignored.

Script-tag integrations use the equivalent attributes `data-app-key`, `data-api-version`, `data-challenge-url`, and `data-protect`. `data-api-version` accepts exactly `"v1"` or `"v2"`; omitting it selects v2. `data-protect` must be a JSON array of strings. The collector accepts only the exact `data-telemetry="true"` and `data-telemetry="false"` values; invalid supplied values use the same sanitized `invalid_config` auto-init warning.

Each token flow retains its API version through create, solve, verify, and retries,
including when the SDK is reinitialized during that flow.
This SDK requires WebAssembly and the documented CSP permissions with either
API version. Integrations pinned to Browser SDK 1.0.0 continue using API v1.

Custom service URLs are normalized for surrounding whitespace and trailing
slashes while retaining path prefixes. All attempts share the configured token
timeout, which defaults to 5,000 ms. `getToken()` returns a token or `""` if
acquisition fails.

### Optional browser signal collection

On API v2, `telemetry: true` collects a bounded summary of browser
interaction and timezone information in page memory for up to five minutes.
This summary accompanies token requests and includes timezone information.

The collector does not retain raw events, typed text, key values, DOM references,
or mouse paths. It uses no cookies, browser storage, or persistent identity and
sends no separate telemetry request. Collection is disabled by default, and a
collection failure does not fail token acquisition.

### `IntelliFend.getToken(options?)`

| Option | Description |
| --- | --- |
| `action` | Optional non-empty, case-sensitive action carried in the signed token. It is not an authorization decision by itself; compare it only with trusted backend configuration after normal token verification succeeds. |
| `timeoutMs` | Optional per-call timeout. It may narrow, but never widen, the timeout set by `init()`. |
| `signal` | Optional `AbortSignal` that cancels the complete token flow. |

The method always resolves to a string: the issued token or `""` for validation, cancellation, timeout, transport, service, response, or solver failure.

### Endpoint matching

Use named path parameters for endpoints whose path contains an identifier.

For npm/ESM initialization:

```javascript
import { IntelliFend } from "@intellifend/requestshieldjs";

IntelliFend.init({
  appKey: "YOUR_APP_KEY",
  protect: ["/api/orders/:orderId/items"],
});
```

For script-tag initialization, use the equivalent attribute:

```html
data-protect='["/api/orders/:orderId/items"]'
```

- A root-relative entry is resolved once against the current page origin.
- An absolute entry must not contain credentials. Cross-origin entries require HTTPS, except for `localhost`, `127.0.0.1`, and `[::1]`; same-origin HTTP is allowed.
- Origin must match exactly. A parameter such as `:orderId` occupies a whole pathname segment and matches exactly one non-empty segment, never a `/`. Names start with an ASCII letter or `_`, followed by ASCII letters, digits, or `_`.
- Multiple parameters are allowed, for example `/api/accounts/:accountId/orders/:orderId`. Names are descriptive; repeating a name does not require equal values. Parameters are allowed only in the pathname, never in the origin.
- Every other segment matches literally. Rules without parameters keep exact matching; rules never become prefix matches. Path case and trailing slash remain significant.
- Escape a literal leading colon by doubling it: `/api/orders/::orderId` matches `/api/orders/:orderId` only, and `/api/orders/:::orderId` matches `/api/orders/::orderId` only. When upgrading from exact-only matching, change any existing literal colon-leading segment to this escaped form before enabling the new syntax.
- A colon-leading segment that is neither a valid parameter nor a `::` escape is invalid configuration, including `:`, `:123`, and `:order-id`. Invalid raw path segments are rejected even if URL dot-segment normalization would remove them. Other punctuation is literal; wildcard hosts, wildcard paths, regular expressions, and catch-all parameters are not supported.
- Query strings and fragments in rules and requests are ignored. `/api/orders/:id?include=details` still requires one `:id` segment; `?` does not make the parameter optional.
- Browser URL normalization applies, including dot-segment removal. The SDK does not decode percent escapes: `%2F` and `%5C` remain within one segment, and a literal `%3AorderId` differs from `:orderId`. Literal encoded segments must match their normalized URL spelling, including percent-escape case.
- Relative application URLs use `document.baseURI` at the native call boundary: Fetch captures it when `fetch()` is called, and XHR captures it when `open()` is called. A later `<base>` change cannot retarget a delayed protected request.
- Rules apply to every HTTP method.
- Seamless mode covers Fetch and asynchronous XHR. It does not cover synchronous XHR, native form navigation, `sendBeacon`, WebSocket, EventSource, service-worker-owned traffic, or transports cached before SDK initialization.
- Fetch requests whose effective mode is `no-cors` are sent unchanged because JavaScript cannot add the token header.

For `/api/orders/:orderId/items` on the page origin:

| Request URL | Matches? |
| --- | --- |
| `/api/orders/12345/items` | Yes |
| `/api/orders/abc-123/items` | Yes |
| `/api/orders/12345/items?include=details` | Yes |
| `/api/orders//items` | No: empty segment |
| `/api/orders/12345/items/extra` | No: extra segment |
| `/api/orders/12345/items/` | No: trailing slash |
| `/api/orders/12345/Items` | No: different case |
| Same pathname on another origin | No |

Absolute rules such as
`https://api.example.com/api/orders/:orderId/items` use the same
path syntax and require that exact origin. Exact rules and parameter rules can
coexist; overlapping rules still produce only one application request and one
token attachment. Invalid patterns follow the normal `invalid_config` behavior
of `init()` or script-tag initialization.

Matching only decides whether the frontend attaches a token. Configure backend
verification for every corresponding route, including dynamic routes; a browser
rule does not enable backend protection or bind token claims to that route.

## Integration behavior

### Fail-through and header precedence

If token acquisition, endpoint matching, interception, or header preparation fails, the SDK sends the original application request once without adding a token. A protected Fetch call is snapshotted synchronously, so mutating its URL, options, headers, or body after `fetch()` returns does not change a delayed dispatch. A pre-existing non-empty `X-IntelliFend-Token` value always wins and suppresses automatic token acquisition. This browser fail-through is not an allow decision; the backend owns missing-token policy and verification.

Protected asynchronous XHR also captures its body when `send()` is called.
Later edits to URLSearchParams, FormData, ArrayBuffer/view bytes, or a Document
do not change the delayed request. Native XHR retains responsibility for body
serialization, file names, MIME types, and document charset handling. GET/HEAD
bodies remain ignored. If capture fails, the original native `send()` runs
immediately with the original body and retains its native validation errors.

### Token lifetime and single use

Tokens are short-lived and single-use. Use one token for one protected application request, obtain a fresh token for a retry, and never reuse a token after native Fetch or XHR dispatch may have sent it. Seamless mode never gives the same token to two requests.

### CORS

For a cross-origin protected application API, allow the `X-IntelliFend-Token` request header in that API's CORS policy. This is separate from the Challenge Server connection.

### Manual transport

`X-IntelliFend-Token` is the recommended carrier for frontend Manual mode and is
required by backend Seamless. A dedicated request-body or form field is also
valid with backend Manual, where application code extracts it before verification.
Never place a token in a URL path, query string, or fragment because those
locations are commonly logged and cached.

### Challenge Server proxies

A Challenge Server proxy must forward binary request and response bodies unchanged, accept `POST` requests with no request `Content-Type`, and preserve the browser `Origin`. Do not parse or reserialize the bodies as JSON. Challenge create and verify requests deliberately set no author headers so their normal cross-origin POSTs remain CORS simple requests without an OPTIONS preflight.

### CSP

For 2.0, pages with Content Security Policy need `'wasm-unsafe-eval'` in
`script-src` alongside the approved script origin, `connect-src` permission for
the service origins, and `worker-src blob:` for the
proof-of-work Web Worker. Keep JavaScript evaluation blocked; broad
`'unsafe-eval'` is unnecessary. For the standard service, allow these connections
alongside the application's other required sources:

```http
connect-src 'self' https://challenge.intellifend.ai https://challenge.intellifend.org;
```

### Subresource Integrity

Pin an immutable `requestshield/v<version>/intellifend.js` URL, use the matching `sha384-...` value from that release's `checksums.json`, and set `crossorigin="anonymous"`. Do not combine a fixed integrity value with `requestshield/latest/` or the mutable root alias. The static host must authorize the cross-origin script request through CORS.

### Sensitive values

Do not log raw tokens or raw challenges. Redact the selected token carrier in proxies and application logs without changing the value sent for verification.

## Browser compatibility and performance

The SDK targets Chrome/Edge 97+, Firefox 102+, and Safari/iOS 16+ with
WebAssembly and the required CSP permission. Test your integration on the
browsers and devices your application supports. Proof-of-work runs off the
main thread in a Web Worker.
Completion time depends on the device and service-selected challenge. Token
acquisition has a configurable timeout of five seconds by default. On timeout,
`getToken()` returns `""`, and the backend applies its missing-token policy.

## License

The proprietary SDK is licensed by Request Shield under [LICENSE.txt](LICENSE.txt).
Integration with authorized IntelliFend services has no SDK royalty; service
access and charges remain separate. Public distribution does not make the SDK
open source. Preserve the license and [third-party notices](THIRD_PARTY_NOTICES.txt) when
bundling or redistributing it with your application.

## Support

Contact IntelliFend support for an application key, the approved Challenge Server URL, an immutable bundle URL and SRI digest, or integration assistance. Include the SDK version and sanitized error context; never include tokens, challenges, or credentials.
