# Customer-context service example

This customer-hosted Node.js 22+ service reads one approved warehouse view through
Voiceflow's API tool. It does not connect a real account until you configure and
run it. Local tests use transport/driver fixtures, not authenticated providers.

Download package.json, context.mjs, providers.mjs, server.mjs, tool.mjs,
context.test.mjs and providers.test.mjs into one directory. Run `npm install`,
then `npm test`. Retain the generated package-lock.json in your own deployment.

## Common configuration and ownership

Your application developer owns the HTTPS deployment and authenticated customer
mapping. Your data owner owns CONTEXT_VIEW, its approved columns and source
freshness. Use one service instance/configuration per provider account/tenant.

- WAREHOUSE_PROVIDER: snowflake, bigquery, redshift, fabric or databricks.
- CONTEXT_TENANT_ID: fixed application tenant ID, letters/numbers/underscore/hyphen.
- CONTEXT_VIEW: fixed approved view; never supplied by the customer or model.
- CONTEXT_SERVICE_TOKEN: at least 32 random bytes encoded as hex. Store the same
  value in the Voiceflow restricted Secret warehouse_context_service_token.
- CONTEXT_SIGNING_KEY: a separate random key of at least 32 bytes encoded as hex.
  Keep it only on the application backend and context service.
- CONTEXT_MAX_AGE_SECONDS: allowed source age, default 900, range 1–86400.
- HOST/PORT: default 127.0.0.1:8080. Bind HOST=0.0.0.0 inside a container whose
  existing HTTPS ingress is configured to forward this route. Limit ingress
  request size and apply your existing rate limits; do not expose the local port.

Generate each random value separately with Node's crypto.randomBytes(32).toString('hex').
Put values in your server's secret manager; do not commit or send them to the model.

## View contract

Expose only tenant_id and customer_id (strings, each at most 80 characters),
plan_name and support_tier (nonempty strings, at most 80 characters), open_cases
(nonnegative integer) and last_synced_at (UTC ISO 8601 text from the source's last
completed refresh). The view must have at most one row per tenant/customer pair.
Map your real source columns to these names. Do not replace last_synced_at with
the query's current timestamp: that would hide stale upstream data.

The fixed SQL selects these six columns, binds both tenant/customer parameters,
and fetches at most two rows to detect duplicate identity. It performs no writes.
A zero-row result is found:false. Duplicate, mismatched or stale data fails closed.
Only the four approved customer fields and the source/fetch timestamps are returned.

## Provider configuration

Snowflake: SNOWFLAKE_ORIGIN (account HTTPS origin ending in snowflakecomputing.com),
SNOWFLAKE_TOKEN (service user's programmatic access token), SNOWFLAKE_WAREHOUSE,
SNOWFLAKE_DATABASE, SNOWFLAKE_SCHEMA and SNOWFLAKE_ROLE. Grant the role warehouse,
database and schema USAGE and SELECT only on the approved view. Service-user PATs
require the provider's network policy and permitted authentication method. Allow
the service's actual egress; configure an expiry/rotation owner. The adapter uses
the SQL API, binds TEXT values, polls a pending handle and rejects extra partitions.

BigQuery: BIGQUERY_PROJECT (query/billing project), BIGQUERY_LOCATION and
BIGQUERY_MAX_BYTES (positive decimal query byte ceiling). CONTEXT_VIEW must be
project.dataset.view. Use Application Default Credentials for the service's
identity, with jobs.create on the query project and only the necessary view data
access (an authorized view can restrict underlying data). The library obtains
current request credentials. The adapter disables query caching and polls an
unfinished query job; pagination or provider errors are not reported as success.

Redshift: AWS_REGION, REDSHIFT_WORKGROUP (this recipe is Serverless),
REDSHIFT_DATABASE and REDSHIFT_SECRET_ARN. Use the AWS SDK credential chain on the
service, preferably a workload role. The Secrets Manager secret contains the
restricted database user's username/password. Grant its SQL role schema USAGE and
SELECT only on the approved view; grant the workload ExecuteStatement,
DescribeStatement, GetStatementResult, CancelStatement and the necessary scoped
GetSecretValue/decryption permissions. IAM API access alone is not SQL access.
The adapter polls FINISHED before fetching typed rows and attempts cancellation
on unfinished failures. Rotate the database secret through its assigned owner.

Databricks: this recipe covers an AWS workspace. DATABRICKS_ORIGIN ends in
cloud.databricks.com. Set DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRET and
DATABRICKS_WAREHOUSE_ID. Assign the service principal to the workspace, grant its
SQL entitlement/warehouse CAN USE, catalog/schema USE and SELECT on the approved
view. Create an OAuth M2M secret. The adapter obtains a workspace token per lookup,
uses named STRING parameters, waits for SUCCEEDED and rejects truncated/chunked
results. Access-token renewal is automatic per request; the client secret still
needs expiry monitoring/rotation. Never fetch an external result URL with auth.

Fabric: FABRIC_SERVER is the Warehouse SQL hostname ending in
.datawarehouse.fabric.microsoft.com; FABRIC_DATABASE is the exact warehouse name.
Set FABRIC_TENANT_ID, FABRIC_CLIENT_ID, FABRIC_CLIENT_SECRET, FABRIC_WORKSPACE_ID and FABRIC_WAREHOUSE_ID. The Entra/Fabric
administrators enable the service-principal tenant setting, give item connect
access and grant SELECT on the approved view. Avoid a broad workspace role that
implicitly grants other data. This path uses encrypted TDS on TCP 1433, not Fabric
item-management REST APIs. Permit egress/firewall access and test the selected
initial catalog. A new service principal also needs Fabric security-token initialization through a successful public Fabric REST call. Before SQL, this adapter obtains a Fabric-audience application token and reads the intended Warehouse item by workspace/item ID, requiring a matching ID. It repeats after 24 hours of active use; an idle service refreshes on its next lookup, before SQL. This applies the documented any-public-API rule using Get Warehouse and needs the corresponding item read permission. It is separate from the 30-day Fabric token lifecycle and the SQL driver token. The mssql driver acquires a database token for each new connection; the
pool is closed after each read. Rotate the Entra application secret before expiry.

## Identity and application integration

After the application has authenticated a login, authorize and resolve its tenant
and customer ID on the backend. Use trustedContextTurn on EVERY launch, text turn
and supported resume path. This example accepts launch/text only; add another
action only after validating that action's runtime contract. It discards browser
variables, state, config and identity overrides. Keep runtime credentials/session
keys server-side; a browser with direct runtime access can bypass your proxy.

```js
import { trustedContextTurn } from './context.mjs';
const mapping = { tenantID: authenticatedTenant, customerID: authorizedCustomer,
                  provider: process.env.WAREHOUSE_PROVIDER };
const runtimeBody = trustedContextTurn(browserBody, mapping,
                                      process.env.CONTEXT_SIGNING_KEY);
// Forward runtimeBody using your backend-owned Voiceflow runtime session.
// Your existing authenticated proxy owns transport, session retention and errors.
```

The application must integrate this helper behind its actual sign-in/session
middleware; this bundle does not supply or simulate a login provider. For a
standalone test, use issueLookupToken(mapping, key) on the backend and supply its
returned value as the explicit lookup_token input. It expires after 120 seconds;
create a fresh token for another test rather than extending a fixture's validity.

## Run and verify

Configure the common and chosen provider values in the supervised service's
secret/environment configuration, then start `node server.mjs` behind HTTPS.
Use POST /v1/customer-context with Authorization: Bearer CONTEXT_SERVICE_TOKEN
and JSON {"lookup_token":"SIGNED_APPLICATION_TOKEN"}. The service token and lookup
token are different values. Keep the signing key out of both requests and Voiceflow.

Expected success: HTTP 200, ok:true, found:true, customer.customer_id matching the
login, approved fields, source_updated_at and fetched_at. A valid zero-row lookup
returns HTTP 200, ok:true, found:false. Invalid authorization is 401/403; stale,
ambiguous or unavailable provider data is 503. No response is cacheable. A
10-second service deadline returns unavailable; it does not prove that a remote
query stopped. Provider cold starts can require a later user-driven retry; do not
loop calls in the agent or claim that an accepted statement has completed.

Test two customers, cross-tenant IDs, a changed/expired lookup token, duplicate
rows, stale source timestamps, unavailable compute and revoked provider access.
Then test the attached Voiceflow agent and its actual answer. A standalone 200
cannot establish agent routing, privacy or that source ingestion is current.
