@renterra/sdk 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -0
- package/dist/browser-oauth.d.ts +11 -0
- package/dist/browser-oauth.js +169 -0
- package/dist/debug.d.ts +11 -0
- package/dist/debug.js +69 -0
- package/dist/generated/contracts.d.ts +607 -0
- package/dist/generated/contracts.js +1 -0
- package/dist/generated/resources.d.ts +1014 -0
- package/dist/generated/resources.js +87 -0
- package/dist/generated/rest.d.ts +2744 -0
- package/dist/generated/rest.js +1 -0
- package/dist/generated/schemas.d.ts +6 -0
- package/dist/generated/schemas.js +2728 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/mcp.d.ts +456 -0
- package/dist/mcp.js +185 -0
- package/dist/rest.d.ts +1296 -0
- package/dist/rest.js +47 -0
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +39 -0
- package/package.json +52 -0
package/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Renterra SDK
|
|
2
|
+
|
|
3
|
+
Typed access to the complete Renterra REST API. The server enforces the authorized user's current organization membership and permissions. Installing the package does not grant access.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { connectRenterra } from "@renterra/sdk"
|
|
7
|
+
|
|
8
|
+
const renterra = await connectRenterra()
|
|
9
|
+
const customers = await renterra.customers.list({ query: "Acme" })
|
|
10
|
+
const branches = await renterra.branches.list()
|
|
11
|
+
const task = await renterra.tasks.create({ title: "Call Acme" })
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The SDK is a private, general-purpose Renterra client for first-party surfaces, standalone apps, and artifacts. Artifact authoring and publication procedures belong to the internal `renterra-artifacts` and `renterra-artifacts-publish` skills, not to the npm release workflow. Installing the SDK does not create, upload, or publish an artifact.
|
|
15
|
+
|
|
16
|
+
## Inside Renterra
|
|
17
|
+
|
|
18
|
+
Artifacts served under `/beta/artifact-file/` automatically use the host session. Requests go to same-origin `/v1/app/...`, which web rewrites to the public API's `/v1/...` routes. No OAuth redirects, token endpoint calls, or client-side token storage occur. Other trusted Renterra surfaces can explicitly pass `{ mode: "session" }`.
|
|
19
|
+
|
|
20
|
+
Web requires `RENTERRA_API_ORIGIN` pointing to its matching API deployment. API requires `RENTERRA_OAUTH_ISSUER_ORIGIN` pointing to the web deployment that owns the session. API validates sessions without refreshing them and checks current membership and permissions on each request. Session writes require the configured issuer origin or an approved Renterra app/preview origin. Unrecognized origins and missing origins are rejected for session writes.
|
|
21
|
+
|
|
22
|
+
## Standalone development
|
|
23
|
+
|
|
24
|
+
Outside the artifact host, the SDK uses `https://api.getrenterra.com` and web's OAuth authorization-code flow with PKCE. The first API call redirects to Renterra for sign-in, organization selection, and consent. Reload the same app on the callback; the next API call completes authorization. The SDK validates state, exchanges the code, and refreshes expiring credentials. Browser credentials are omitted from public API and OAuth requests.
|
|
25
|
+
|
|
26
|
+
OAuth state, verifier, and tokens are scoped to the issuer/resource in `sessionStorage`, not shared across tabs. Use `renterra.signOut()` to clear this app's local authorization; this does not sign out of Renterra or revoke the server grant.
|
|
27
|
+
|
|
28
|
+
Dynamic registration accepts approved Renterra origins and localhost/loopback redirect URIs for `api:access`. A separately hosted production app needs an explicitly registered OAuth client with its exact redirect URI and the `api:access` scope. Pass its public `clientId`; never embed a client secret or organization API key in browser code.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
const renterra = await connectRenterra({
|
|
32
|
+
mode: "oauth",
|
|
33
|
+
clientId: "your-registered-public-client",
|
|
34
|
+
redirectUri: "https://your-app.example/oauth/callback",
|
|
35
|
+
})
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For staging, set both `apiOrigin` and `issuer` (the web origin plus `/api/auth`). API can set `RENTERRA_API_RESOURCE_URL` to its canonical REST audience; it defaults to `/v1` on the configured `RENTERRA_MCP_RESOURCE_URL` origin. Web advertises `/v1` on its configured `RENTERRA_API_ORIGIN`. These URLs must match. REST tokens require `api:access`; MCP tokens with only `mcp:read` do not authorize REST requests. Non-browser clients may provide an `accessToken` callback that owns their OAuth flow.
|
|
39
|
+
|
|
40
|
+
## Resource methods
|
|
41
|
+
|
|
42
|
+
Every REST operation has a generated resource method. The same methods, inputs, returned data, and errors apply inside Renterra and in standalone apps. HTTP verbs, URLs, and API versions are private implementation details; there is no raw HTTP client on the SDK.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
await renterra.customers.list({ query: "Acme", page: 0 })
|
|
46
|
+
await renterra.customers.get(customerId)
|
|
47
|
+
await renterra.customers.update(customerId, { name: "Acme Rentals" })
|
|
48
|
+
await renterra.tasks.create({ title: "Call Acme" }, { idempotencyKey: "follow-up-1" })
|
|
49
|
+
await renterra.tasks.update(taskId, { title: "Call Acme tomorrow" })
|
|
50
|
+
await renterra.tasks.delete(taskId)
|
|
51
|
+
await renterra.inventory.items.list()
|
|
52
|
+
await renterra.inventory.kits.list()
|
|
53
|
+
await renterra.inventory.orders.list({ order_id: orderId })
|
|
54
|
+
await renterra.orders.billingSummary(orderId)
|
|
55
|
+
await renterra.orders.contracts.list(orderId)
|
|
56
|
+
const pdf = await renterra.orders.contracts.download(orderId, contractId)
|
|
57
|
+
await renterra.accounting.chart.list()
|
|
58
|
+
await renterra.accounting.ledger.list()
|
|
59
|
+
await renterra.maintenance.workOrders.list()
|
|
60
|
+
await renterra.maintenance.serviceOrders.list()
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
List methods take query filters; detail methods take IDs; create/update methods take a typed input object after any IDs. Methods return response data directly, including each operation's pagination. Contract downloads return a `Blob`; task deletion returns `void`. Draft and not-yet-implemented operations retain their server behavior; SDK coverage does not make them available.
|
|
64
|
+
|
|
65
|
+
All methods throw `RenterraError` with `status` and `code` on HTTP errors. Network and OAuth failures may be ordinary errors. Calls accept trailing `{ signal, timeout, idempotencyKey }` options. An idempotency key is useful only where the server supports it, such as customer and task creation. No automatic API retries are performed, especially for writes.
|
|
66
|
+
|
|
67
|
+
## Package rename
|
|
68
|
+
|
|
69
|
+
Replace `@renterra/artifacts` with `@renterra/sdk` and `connectArtifacts()` with `connectRenterra()`. The public types are now `RenterraSdk`, `ConnectRenterraOptions`, and `RenterraCallOptions`; HTTP errors use `RenterraError`. The MCP entry point is `@renterra/sdk/mcp`, with `McpInput`, `McpOutput`, and `renterraSdkDebug` for MCP-specific integrations. Resource methods and authentication behavior are unchanged. Existing releases of the old package are not removed or republished by this rename.
|
|
70
|
+
|
|
71
|
+
## Migrating from 0.1
|
|
72
|
+
|
|
73
|
+
The default export surface now uses REST, not MCP. Remove `url`, `authProvider`, `tokenEndpoint`, and `authorizationCode` options. OAuth is handled by the standalone adapter; host sessions require no token provider. Replace `search` with `list`, `inventoryItems` with `inventory.items`, `inventoryOnOrders` with `inventory.orders`, and `orders.listContracts(id)` with `orders.contracts.list(id)`. Root SDK clients do not expose `api`, `close`, or the MCP debug controller. The legacy MCP transport remains available through `@renterra/sdk/mcp`. The MCP server, hosted session-token endpoint, and token validation are unchanged.
|
|
74
|
+
|
|
75
|
+
SDK resource methods and types are generated from the entire API contract, including draft operations, rather than the MCP tool list. Generation fails if an operation cannot be represented or mapped to a resource method. Run `pnpm exec turbo run generate --filter=@renterra/sdk` after contract changes. OpenAPI code generation requires the TypeScript 5 compiler API, so this package pins TypeScript 5.9 while the rest of the repository uses its catalog version.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type BrowserOAuthOptions = {
|
|
2
|
+
issuer: string;
|
|
3
|
+
resource: string;
|
|
4
|
+
redirectUri?: string;
|
|
5
|
+
clientId?: string;
|
|
6
|
+
fetch?: typeof globalThis.fetch;
|
|
7
|
+
};
|
|
8
|
+
export declare function createBrowserOAuth(options: BrowserOAuthOptions): {
|
|
9
|
+
accessToken(): Promise<string>;
|
|
10
|
+
clear: () => void;
|
|
11
|
+
};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
function randomValue() {
|
|
2
|
+
return base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
3
|
+
}
|
|
4
|
+
function base64url(bytes) {
|
|
5
|
+
return btoa(String.fromCharCode(...bytes))
|
|
6
|
+
.replace(/\+/g, "-")
|
|
7
|
+
.replace(/\//g, "_")
|
|
8
|
+
.replace(/=+$/, "");
|
|
9
|
+
}
|
|
10
|
+
class OAuthResponseError extends Error {
|
|
11
|
+
status;
|
|
12
|
+
code;
|
|
13
|
+
constructor(status, code) {
|
|
14
|
+
super(`OAuth request failed (${status})`);
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async function responseObject(response) {
|
|
20
|
+
const text = await response.text();
|
|
21
|
+
let body;
|
|
22
|
+
try {
|
|
23
|
+
body = JSON.parse(text);
|
|
24
|
+
}
|
|
25
|
+
catch (cause) {
|
|
26
|
+
if (response.ok)
|
|
27
|
+
throw new Error("Invalid OAuth response", { cause });
|
|
28
|
+
}
|
|
29
|
+
if (!response.ok)
|
|
30
|
+
throw new OAuthResponseError(response.status, body && typeof body === "object" && "error" in body && typeof body.error === "string"
|
|
31
|
+
? body.error
|
|
32
|
+
: undefined);
|
|
33
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
34
|
+
throw new Error("Invalid OAuth response");
|
|
35
|
+
return body;
|
|
36
|
+
}
|
|
37
|
+
export function createBrowserOAuth(options) {
|
|
38
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
39
|
+
const issuer = new URL(options.issuer);
|
|
40
|
+
const key = `renterra:api-oauth:${issuer.href}:${options.resource}`;
|
|
41
|
+
let tokens;
|
|
42
|
+
let pendingToken;
|
|
43
|
+
function clear() {
|
|
44
|
+
tokens = undefined;
|
|
45
|
+
sessionStorage.removeItem(`${key}:tokens`);
|
|
46
|
+
sessionStorage.removeItem(`${key}:authorization`);
|
|
47
|
+
}
|
|
48
|
+
async function exchange(params, clientId) {
|
|
49
|
+
params.set("client_id", clientId);
|
|
50
|
+
params.set("resource", options.resource);
|
|
51
|
+
const body = await responseObject(await fetchFn(new URL("oauth2/token", `${issuer.href.replace(/\/$/, "")}/`), {
|
|
52
|
+
method: "POST",
|
|
53
|
+
credentials: "omit",
|
|
54
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
55
|
+
body: params,
|
|
56
|
+
}));
|
|
57
|
+
if (typeof body.access_token !== "string" ||
|
|
58
|
+
typeof body.expires_in !== "number" ||
|
|
59
|
+
body.token_type?.toString().toLowerCase() !== "bearer")
|
|
60
|
+
throw new Error("Invalid OAuth token response");
|
|
61
|
+
tokens = {
|
|
62
|
+
accessToken: body.access_token,
|
|
63
|
+
refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : tokens?.refreshToken,
|
|
64
|
+
expiresAt: Date.now() + body.expires_in * 1000,
|
|
65
|
+
clientId,
|
|
66
|
+
};
|
|
67
|
+
sessionStorage.setItem(`${key}:tokens`, JSON.stringify(tokens));
|
|
68
|
+
return tokens.accessToken;
|
|
69
|
+
}
|
|
70
|
+
async function getToken() {
|
|
71
|
+
if (typeof window === "undefined")
|
|
72
|
+
throw new Error("Standalone OAuth requires a browser");
|
|
73
|
+
if (!tokens) {
|
|
74
|
+
const stored = sessionStorage.getItem(`${key}:tokens`);
|
|
75
|
+
if (stored)
|
|
76
|
+
tokens = JSON.parse(stored);
|
|
77
|
+
}
|
|
78
|
+
if (tokens && tokens.expiresAt > Date.now() + 30_000)
|
|
79
|
+
return tokens.accessToken;
|
|
80
|
+
if (tokens?.refreshToken) {
|
|
81
|
+
try {
|
|
82
|
+
return await exchange(new URLSearchParams({ grant_type: "refresh_token", refresh_token: tokens.refreshToken }), tokens.clientId);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof OAuthResponseError &&
|
|
86
|
+
error.status === 400 &&
|
|
87
|
+
error.code === "invalid_grant")
|
|
88
|
+
clear();
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const current = new URL(window.location.href);
|
|
93
|
+
const code = current.searchParams.get("code");
|
|
94
|
+
const saved = sessionStorage.getItem(`${key}:authorization`);
|
|
95
|
+
if (saved && (code || current.searchParams.has("error"))) {
|
|
96
|
+
const authorization = JSON.parse(saved);
|
|
97
|
+
sessionStorage.removeItem(`${key}:authorization`);
|
|
98
|
+
if (current.searchParams.get("state") !== authorization.state ||
|
|
99
|
+
Date.now() - authorization.createdAt > 600_000)
|
|
100
|
+
throw new Error("Invalid or expired OAuth state");
|
|
101
|
+
if (!code)
|
|
102
|
+
throw new Error("OAuth authorization was denied");
|
|
103
|
+
const token = await exchange(new URLSearchParams({
|
|
104
|
+
grant_type: "authorization_code",
|
|
105
|
+
code,
|
|
106
|
+
code_verifier: authorization.verifier,
|
|
107
|
+
redirect_uri: authorization.redirectUri,
|
|
108
|
+
}), authorization.clientId);
|
|
109
|
+
for (const parameter of ["code", "state", "iss", "error", "error_description"])
|
|
110
|
+
current.searchParams.delete(parameter);
|
|
111
|
+
window.history.replaceState(null, "", current);
|
|
112
|
+
return token;
|
|
113
|
+
}
|
|
114
|
+
const redirectUri = options.redirectUri ?? `${current.origin}${current.pathname}`;
|
|
115
|
+
let clientId = options.clientId;
|
|
116
|
+
if (!clientId) {
|
|
117
|
+
const registered = await responseObject(await fetchFn(new URL("oauth2/register", `${issuer.href.replace(/\/$/, "")}/`), {
|
|
118
|
+
method: "POST",
|
|
119
|
+
credentials: "omit",
|
|
120
|
+
headers: { "content-type": "application/json" },
|
|
121
|
+
body: JSON.stringify({
|
|
122
|
+
client_name: "Renterra SDK app",
|
|
123
|
+
redirect_uris: [redirectUri],
|
|
124
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
125
|
+
response_types: ["code"],
|
|
126
|
+
token_endpoint_auth_method: "none",
|
|
127
|
+
scope: "openid offline_access api:access",
|
|
128
|
+
}),
|
|
129
|
+
}));
|
|
130
|
+
if (typeof registered.client_id !== "string")
|
|
131
|
+
throw new Error("Invalid OAuth client registration");
|
|
132
|
+
clientId = registered.client_id;
|
|
133
|
+
}
|
|
134
|
+
const verifier = randomValue();
|
|
135
|
+
const state = randomValue();
|
|
136
|
+
const challenge = base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
137
|
+
const authorization = {
|
|
138
|
+
clientId,
|
|
139
|
+
verifier,
|
|
140
|
+
state,
|
|
141
|
+
redirectUri,
|
|
142
|
+
createdAt: Date.now(),
|
|
143
|
+
};
|
|
144
|
+
sessionStorage.setItem(`${key}:authorization`, JSON.stringify(authorization));
|
|
145
|
+
const url = new URL("oauth2/authorize", `${issuer.href.replace(/\/$/, "")}/`);
|
|
146
|
+
url.search = new URLSearchParams({
|
|
147
|
+
client_id: clientId,
|
|
148
|
+
redirect_uri: redirectUri,
|
|
149
|
+
response_type: "code",
|
|
150
|
+
scope: "openid offline_access api:access",
|
|
151
|
+
resource: options.resource,
|
|
152
|
+
state,
|
|
153
|
+
code_challenge: challenge,
|
|
154
|
+
code_challenge_method: "S256",
|
|
155
|
+
}).toString();
|
|
156
|
+
window.location.assign(url);
|
|
157
|
+
throw new Error("Redirecting to Renterra authorization");
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
accessToken() {
|
|
161
|
+
if (!pendingToken)
|
|
162
|
+
pendingToken = getToken().finally(() => {
|
|
163
|
+
pendingToken = undefined;
|
|
164
|
+
});
|
|
165
|
+
return pendingToken;
|
|
166
|
+
},
|
|
167
|
+
clear,
|
|
168
|
+
};
|
|
169
|
+
}
|
package/dist/debug.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const renterraSdkDebug: {
|
|
2
|
+
enable: () => void;
|
|
3
|
+
disable: () => void;
|
|
4
|
+
};
|
|
5
|
+
declare global {
|
|
6
|
+
interface Window {
|
|
7
|
+
renterraSdkDebug?: typeof renterraSdkDebug;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export declare function sdkDebug(event: string, details?: Record<string, unknown>): void;
|
|
11
|
+
export declare function debugHttpFailure(response: Response): Promise<void>;
|
package/dist/debug.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
let enabled = false;
|
|
2
|
+
export const renterraSdkDebug = {
|
|
3
|
+
enable: () => {
|
|
4
|
+
enabled = true;
|
|
5
|
+
},
|
|
6
|
+
disable: () => {
|
|
7
|
+
enabled = false;
|
|
8
|
+
},
|
|
9
|
+
};
|
|
10
|
+
if (typeof window !== "undefined" && !("renterraSdkDebug" in window)) {
|
|
11
|
+
window.renterraSdkDebug = renterraSdkDebug;
|
|
12
|
+
}
|
|
13
|
+
const sensitiveKey = /authorization|auth[_-]?provider|cookie|token|secret|password|credential|api[_-]?key|code[_-]?verifier/i;
|
|
14
|
+
// biome-ignore lint/plugin: Diagnostic redaction must accept unvalidated caller payloads before input validation.
|
|
15
|
+
function redact(value, seen = new WeakSet()) {
|
|
16
|
+
if (typeof value === "string") {
|
|
17
|
+
return value
|
|
18
|
+
.replace(/\bBearer\s+\S+/gi, "[REDACTED]")
|
|
19
|
+
.replace(/\beyJ[\w-]*\.[\w-]+\.[\w-]+\b/g, "[REDACTED]")
|
|
20
|
+
.replace(/https?:\/\/[^\s]+/gi, "[REDACTED URL]")
|
|
21
|
+
.replace(/\b(authorization|cookie|token|secret|password|credential|api[_-]?key)\s*[:=]\s*\S+/gi, "[REDACTED]");
|
|
22
|
+
}
|
|
23
|
+
if (value === null || typeof value === "number" || typeof value === "boolean")
|
|
24
|
+
return value;
|
|
25
|
+
if (typeof value !== "object")
|
|
26
|
+
return undefined;
|
|
27
|
+
if (seen.has(value))
|
|
28
|
+
return "[Circular]";
|
|
29
|
+
seen.add(value);
|
|
30
|
+
if (Array.isArray(value))
|
|
31
|
+
return value.map((item) => redact(item, seen));
|
|
32
|
+
return Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(([key, descriptor]) => "value" in descriptor
|
|
33
|
+
? [[key, sensitiveKey.test(key) ? "[REDACTED]" : redact(descriptor.value, seen)]]
|
|
34
|
+
: []));
|
|
35
|
+
}
|
|
36
|
+
export function sdkDebug(event, details = {}) {
|
|
37
|
+
if (!enabled)
|
|
38
|
+
return;
|
|
39
|
+
try {
|
|
40
|
+
console.warn(`[renterra/sdk] ${event}`, redact(details));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Diagnostics must not change SDK behavior, including for non-JSON caller inputs.
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export async function debugHttpFailure(response) {
|
|
47
|
+
if (!enabled)
|
|
48
|
+
return;
|
|
49
|
+
let apiCode;
|
|
50
|
+
try {
|
|
51
|
+
const body = await response.clone().json();
|
|
52
|
+
if (body && typeof body === "object") {
|
|
53
|
+
const error = "error" in body ? body.error : body;
|
|
54
|
+
const code = typeof error === "string"
|
|
55
|
+
? error
|
|
56
|
+
: error && typeof error === "object" && "code" in error
|
|
57
|
+
? error.code
|
|
58
|
+
: undefined;
|
|
59
|
+
if (typeof code === "string" && /^[a-z][a-z_]{0,63}$/.test(code))
|
|
60
|
+
apiCode = code;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch { }
|
|
64
|
+
sdkDebug("mcp.http.error", {
|
|
65
|
+
status: response.status,
|
|
66
|
+
apiCode,
|
|
67
|
+
message: apiCode === "subscription_required" ? "An active subscription is required." : undefined,
|
|
68
|
+
});
|
|
69
|
+
}
|