Give Claude Code a small script that calls NetSuite’s REST API with a token for a role that can only see what it needs. Then allow the script’s query command in Claude Code’s permission rules and leave everything else to ask. Claude Code can then answer questions from your account’s real data. Give the role View and nothing higher, and NetSuite won’t let it change those records at all. The rules are a second stop: every command that could write waits for your approval, in auto mode too.
I’ve worked this way on a client account since September 2026. Claude Code checks what a custom record holds before I change the script that writes it, compares the sandbox with production, and walks File Cabinet folders when a deploy complains about missing files. All of that is reading. The one write I’ve needed, copying a configuration record from production to the sandbox, was a single command and I ran it myself.
One date to know first. This uses token-based authentication (TBA). Oracle’s TBA end-of-support page says that starting in 2027.1 “you will no longer be able to create new integrations that use TBA for SOAP and REST web services, and RESTlets”, and support for existing ones is tentatively planned to end in 2028.2. If you’re setting up from scratch from 2027.1 on, use OAuth 2.0 client credentials instead. The permission rules below carry over unchanged, and so does the role once it has the Log in using OAuth 2.0 Access Tokens permission. The signing in the script doesn’t.
Start with a role, not with Administrator
The role decides what Claude Code can see. SuiteQL enforces the same role-based access restrictions as SuiteAnalytics Workbook, so a query returns only what the role could see in Workbook. That makes the role the real fence, and the permission rules a second one.
Administrator is the wrong role for this. Oracle says that using it for REST web services isn’t recommended for security reasons, and it’s awkward to get a token for anyway. A token on an Administrator role can only be created by that administrator, for their own use, through Manage Access Tokens in the Settings portlet or the token endpoint. Nobody else can issue one. On the account I work on, my Administrator login never showed up in the token picker on the Access Tokens page, so the token went on a custom role instead, which is where it belonged.
Create a role under Setup > Users/Roles > User Management > Manage Roles with the permissions Oracle lists for REST web services: REST Web Services and Log in using Access Tokens at Full, and SuiteAnalytics Workbook at Edit. Then add View, and only View, on each record type you want Claude Code to read. View lets a user see existing records but not create, edit or delete them. I left customer records off on purpose. Assign the role to your user when it’s saved.
Roles are per account, so the same role name can carry different permissions in each. On the account I work on, a query the sandbox refused ran fine in production. Test each account rather than assuming one matches the other.
The integration record and the token
Three screens. The features and the token go in each account you query. The integration record goes in production.
- Turn the features on. In Setup > Company > Enable Features, on the SuiteCloud subtab, check Token-based Authentication under Manage Authentication and REST Web Services under SuiteTalk (Web Services). SuiteAnalytics Workbook is on the Analytics subtab.
- Create the integration record. Go to Setup > Integration > Manage Integrations > New. On the Authentication subtab, check Token-based Authentication (TBA) and clear User Credentials, so the application authenticates only with tokens. Leave TBA: IssueToken Endpoint and TBA: Authorization Flow clear. With only the TBA box checked, tokens are created through the UI, which is all you need. The consumer key and secret appear once, when you first save. Copy them straight into the env file below. A sandbox refresh copies production’s integration records across with their settings, and removes any that existed only in the sandbox. If your sandbox hasn’t been refreshed since you created the record, create one there too, and expect the next refresh to replace it with production’s.
- Issue the token. Go to Setup > Users/Roles > Access Tokens, click New Access Token, and select the Application Name, your User and the new Role. The role only appears once it’s assigned to your user, and Oracle’s TBA permissions page covers who can issue tokens to whom. The token ID and secret appear once, on the confirmation page.
Tokens don’t expire. Revoke one when you stop using it, from the same Access Tokens list.
The script
It’s one file with no dependencies beyond Node’s own fs, path, crypto and https. It signs each request with OAuth 1.0 and HMAC-SHA256, runs SuiteQL with paging, and does single-record get, post and patch on the REST record service. It refuses to run unless NS_ENV names the account, so nothing ever defaults to production.
Put it at tools/netsuite/ns.js in your repo:
#!/usr/bin/env node
// Minimal NetSuite REST client: OAuth 1.0 (HMAC-SHA256) signing, SuiteQL, record GET/POST/PATCH.
// No dependencies. Requires NS_ENV=sandbox|production; refuses to run without it so there is
// no default that silently targets production.
//
// NS_ENV=sandbox node tools/netsuite/ns.js suiteql "SELECT id, itemid FROM item WHERE ROWNUM <= 5"
// NS_ENV=sandbox node tools/netsuite/ns.js suiteql --csv "..."
// NS_ENV=sandbox node tools/netsuite/ns.js get <record type> <internal id>
// NS_ENV=sandbox node tools/netsuite/ns.js post <record type> '<json body>'
// NS_ENV=sandbox node tools/netsuite/ns.js patch <record type> <internal id> '<json body>'
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const https = require("https");
function loadEnv() {
const env = process.env.NS_ENV;
if (!env || !["sandbox", "production"].includes(env)) {
console.error("NS_ENV must be 'sandbox' or 'production'. Nothing was sent.");
process.exit(2);
}
const file = path.join(__dirname, `.env.${env}`);
if (!fs.existsSync(file)) {
console.error(`Missing ${file}`);
process.exit(2);
}
const cfg = {};
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
const m = line.match(/^\s*([A-Z_]+)\s*=\s*(.*?)\s*$/);
if (m && !line.trim().startsWith("#")) cfg[m[1]] = m[2].replace(/^["']|["']$/g, "");
}
for (const k of ["NS_ACCOUNT", "NS_CONSUMER_KEY", "NS_CONSUMER_SECRET", "NS_TOKEN_ID", "NS_TOKEN_SECRET"]) {
if (!cfg[k]) {
console.error(`${k} is empty in ${file}`);
process.exit(2);
}
}
// Realm keeps the underscore and case (1234567_SB1); the hostname wants lowercase and a hyphen.
cfg.realm = cfg.NS_ACCOUNT;
cfg.host = `${cfg.NS_ACCOUNT.toLowerCase().replace(/_/g, "-")}.suitetalk.api.netsuite.com`;
cfg.env = env;
return cfg;
}
const enc = (s) =>
encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
function authHeader(cfg, method, url, query) {
const oauth = {
oauth_consumer_key: cfg.NS_CONSUMER_KEY,
oauth_token: cfg.NS_TOKEN_ID,
oauth_signature_method: "HMAC-SHA256",
oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
oauth_nonce: crypto.randomBytes(16).toString("hex"),
oauth_version: "1.0",
};
const params = { ...oauth, ...query };
const normalised = Object.keys(params)
.sort()
.map((k) => `${enc(k)}=${enc(params[k])}`)
.join("&");
const base = [method.toUpperCase(), enc(url), enc(normalised)].join("&");
const key = `${enc(cfg.NS_CONSUMER_SECRET)}&${enc(cfg.NS_TOKEN_SECRET)}`;
oauth.oauth_signature = crypto.createHmac("sha256", key).update(base).digest("base64");
const parts = Object.keys(oauth)
.sort()
.map((k) => `${enc(k)}="${enc(oauth[k])}"`);
return `OAuth realm="${cfg.realm}", ${parts.join(", ")}`;
}
function request(cfg, method, pathname, query = {}, body = null, extraHeaders = {}) {
const url = `https://${cfg.host}${pathname}`;
const qs = Object.keys(query).length
? "?" + Object.keys(query).map((k) => `${enc(k)}=${enc(query[k])}`).join("&")
: "";
const payload = body == null ? null : JSON.stringify(body);
const headers = {
Authorization: authHeader(cfg, method, url, query),
"Content-Type": "application/json",
Accept: "application/json",
...extraHeaders,
};
if (payload) headers["Content-Length"] = Buffer.byteLength(payload);
return new Promise((resolve, reject) => {
const req = https.request(url + qs, { method, headers }, (res) => {
let data = "";
res.on("data", (c) => (data += c));
res.on("end", () => {
let json = null;
try { json = data ? JSON.parse(data) : null; } catch { /* leave raw */ }
resolve({ status: res.statusCode, headers: res.headers, json, raw: data });
});
});
req.on("error", reject);
if (payload) req.write(payload);
req.end();
});
}
function fail(res, what) {
const detail = res.json && res.json["o:errorDetails"]
? res.json["o:errorDetails"].map((e) => e.detail).join(" | ")
: res.raw.slice(0, 600);
console.error(`${what} failed: HTTP ${res.status}\n${detail}`);
process.exit(1);
}
async function suiteql(cfg, q) {
const rows = [];
let offset = 0;
const limit = 1000;
for (;;) {
const res = await request(
cfg, "POST", "/services/rest/query/v1/suiteql",
{ limit: String(limit), offset: String(offset) },
{ q },
{ Prefer: "transient" }
);
if (res.status !== 200) fail(res, "SuiteQL");
rows.push(...(res.json.items || []));
if (!res.json.hasMore) break;
offset += limit;
}
return rows.map(({ links, ...r }) => r);
}
function toCsv(rows) {
if (!rows.length) return "";
// SuiteQL omits null fields per row, so take the union of keys in first-seen order.
const cols = [];
for (const r of rows) for (const k of Object.keys(r)) if (!cols.includes(k)) cols.push(k);
const cell = (v) => {
const s = v == null ? "" : String(v);
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
return [cols.join(","), ...rows.map((r) => cols.map((c) => cell(r[c])).join(","))].join("\n");
}
async function main() {
const cfg = loadEnv();
const [cmd, ...rest] = process.argv.slice(2);
const csv = rest.includes("--csv");
const args = rest.filter((a) => a !== "--csv");
if (cmd === "suiteql") {
const q = args.join(" ");
if (!q) { console.error("suiteql needs a query"); process.exit(2); }
const rows = await suiteql(cfg, q);
process.stdout.write(csv ? toCsv(rows) + "\n" : JSON.stringify(rows, null, 2) + "\n");
console.error(`[${cfg.env}] ${rows.length} row(s)`);
return;
}
if (cmd === "get") {
const [type, id] = args;
const res = await request(cfg, "GET", `/services/rest/record/v1/${type}/${id}`);
if (res.status !== 200) fail(res, `GET ${type}/${id}`);
console.log(JSON.stringify(res.json, null, 2));
return;
}
if (cmd === "post" || cmd === "patch") {
const isPost = cmd === "post";
const [type, idOrBody, maybeBody] = args;
const id = isPost ? null : idOrBody;
const body = JSON.parse(isPost ? idOrBody : maybeBody);
const p = `/services/rest/record/v1/${type}${id ? "/" + id : ""}`;
const res = await request(cfg, isPost ? "POST" : "PATCH", p, {}, body);
if (res.status !== 204 && res.status !== 200) fail(res, `${cmd.toUpperCase()} ${p}`);
// NetSuite answers 204 with the new record's URL in Location.
const loc = res.headers.location || "";
console.log(JSON.stringify({ status: res.status, id: loc.split("/").pop() || id }, null, 2));
return;
}
console.error("commands: suiteql [--csv] <query> | get <type> <id> | post <type> <json> | patch <type> <id> <json>");
process.exit(2);
}
main().catch((e) => { console.error(e); process.exit(1); });It’s CommonJS. In a project whose package.json has "type": "module", Node treats .js files as ES modules and require fails, so name it ns.cjs there and use that name everywhere below.
The credentials go in tools/netsuite/.env.sandbox and tools/netsuite/.env.production, one per account. Commit a template:
# Copy to .env.production or .env.sandbox and fill in.
# Both real files are gitignored. This one is committed as the template.
#
# Tokens are per account. A sandbox refresh copies production's integration
# records over the sandbox's, consumer key and secret included, and deletes
# the access tokens. After a refresh, use production's consumer key and
# secret here and issue a new sandbox token.
NS_ACCOUNT=1234567
NS_CONSUMER_KEY=
NS_CONSUMER_SECRET=
NS_TOKEN_ID=
NS_TOKEN_SECRET=Keep the real files out of git and the template in:
.env.*
!.env.exampleThen a query:
NS_ENV=sandbox node tools/netsuite/ns.js suiteql "SELECT id, itemid FROM item WHERE ROWNUM <= 5"The rows go to stdout as JSON, or CSV with --csv, and a row count goes to stderr.
What the signing has to get right
Most of the script is plumbing. A few lines in loadEnv and authHeader are where a 401 comes from.
Realm and hostname spell the account differently. The realm in the Authorization header is the account ID as NetSuite writes it, such as 1234567_SB1. Oracle’s Postman setup asks for that exact spelling of a sandbox ID. In the hostname, the underscore becomes a hyphen and the letters go lower case: 1234567-sb1.suitetalk.api.netsuite.com. Oracle says not to build that hostname yourself, and to take it from the Company URLs subtab of your company information instead. The script derives it, so check the two match once.
HMAC-SHA256 only. Support for HMAC-SHA1 ended in 2023.1. The signing key is the consumer secret and the token secret, each percent-encoded, joined by &.
Query parameters are signed. SuiteQL pages with limit and offset in the URL, and those go into the signature base string with the OAuth parameters, sorted by name. Oracle’s RESTlet signing page is the one that spells this out. The script signs them, and paged requests go through.
Escaping is RFC 3986. JavaScript’s encodeURIComponent leaves ! ' ( ) * alone, and OAuth wants them escaped. That’s the one-line enc function.
SuiteQL over REST
The query goes to POST /services/rest/query/v1/suiteql with the SQL in a q field and a Prefer: transient header, which Oracle says is required. Results come back 1,000 to a page by default, the script follows hasMore until it has them all, and one query can return at most 100,000 results.
Three things I’ve hit:
– Page with an ORDER BY on a unique column. Oracle asks for “a unique and unambiguous sorting order” to avoid duplicate or missing results. A check across about 9,700 File Cabinet folders once told me 22 files were missing. They were all there. The query paged without an ORDER BY, and rows moved between pages. Walked again with a sort, it found every file. – Null fields are left out of each row. Rows from one query can have different keys. The CSV writer takes every key it sees and leaves gaps blank. – Limiting rows. Oracle’s examples use TOP. WHERE ROWNUM <= 5 works too, and FETCH FIRST 5 ROWS ONLY worked on a sandbox when I tested it in November 2026.
Let Claude Code run queries without asking
Put the rules in .claude/settings.local.json at the root of the repo. The query command is allowed, anything that reads one record or writes asks, and the script’s folder is off limits for reading the token files or editing the script:
{
"permissions": {
"allow": [
"Bash(NS_ENV=sandbox node tools/netsuite/ns.js suiteql *)",
"Bash(NS_ENV=production node tools/netsuite/ns.js suiteql *)"
],
"ask": [
"Bash(node tools/netsuite/ns.js get *)",
"Bash(node tools/netsuite/ns.js post *)",
"Bash(node tools/netsuite/ns.js patch *)"
],
"deny": [
"Read(./tools/netsuite/.env.*)",
"Edit(./tools/netsuite/**)"
]
}
}I tested these rules for this post by running Claude Code non-interactively against a stub script, in auto mode and in Manual mode. In a non-interactive run, anything that needs approval is refused instead of prompting, so a refusal stands in for a prompt.
– The ask rules are what hold in auto mode. Auto mode is now the starting mode for interactive sessions, and a classifier approves commands in your place. With only the two allow rules, the classifier let a production patch run without asking, along with a get and two edits to the script. With the ask rules in, the patch and the get both stopped for approval. An ask rule matches past a leading variable assignment, so one rule covers both accounts. – The Edit deny protects the script the allow rule trusts. Without it, auto mode changed ns.js with the Edit tool and with a shell >>. With it, both were refused. Take it out when you want help changing the script. – The space before *. The space is part of the rule. suiteql * matches the query command with anything after it. suiteql* would also match any command that only starts with those letters, and in the test suiteqlx was refused. – The NS_ENV= prefix belongs in the allow rules. Claude Code strips a leading variable assignment only for some known-safe variables, and an allow rule won’t match past any other. With the prefix written in, both queries ran. – Chaining doesn’t widen it. suiteql "SELECT 1" && touch INJECTED was refused, and the file never appeared. Every command in a chain has to be allowed on its own, by a rule or by being one of Claude Code’s built-in read-only commands. – The Read deny keeps the token files away from the Read tool and from commands that name them, such as cat. Both were refused. It doesn’t cover a command that reads files without naming them. In Manual mode, grep -r NS_TOKEN_SECRET . ran without asking, because grep is one of the read-only commands, and its output would carry the token line. Auto mode’s classifier refused the same command. It also can’t stop the script reading its own env file, which is the point, or any program that opens files itself. Claude Code’s sandbox is the tool for that.
get only reads, but it returns a whole record, so it asks too. Move it to the allow list if you’d rather it didn’t.
Deny rules win over allow rules in every settings file and every mode. Claude Code keeps settings.local.json out of git when it creates the file, but if you create it by hand, add it to .gitignore yourself.
After a sandbox refresh
A refresh deletes the sandbox’s tokens. It also removes any integration record that existed only in the sandbox and copies production’s across, consumer key and secret included. Put production’s consumer key and secret in .env.sandbox if they aren’t there already, then issue a new token in the sandbox and add its ID and secret. The rest of what a refresh resets is in what to redo after a NetSuite sandbox refresh.
This post is part of the AI-Assisted NetSuite Dev cluster. The SuiteCommerce developer tools use token-based authentication too, set up in my production and sandbox guide. The AI tools I use are on the resources page.