@inferencebureau/apps-sdk 0.16.6 → 0.16.8

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/dist/index.d.ts CHANGED
@@ -72,6 +72,12 @@ export interface FieldDef {
72
72
  parent?: {
73
73
  model: string;
74
74
  };
75
+ /**
76
+ * A belongsTo's: what happens to this record when the record it points at is deleted. `"cascade"` deletes it too,
77
+ * `"setNull"` empties the field, `"restrict"` refuses the delete while a record still points at it. Unset, the field
78
+ * keeps the id of a record that's gone. Applied in the delete's own transaction, without running the model's delete action.
79
+ */
80
+ onDelete?: "cascade" | "setNull" | "restrict";
75
81
  child?: {
76
82
  model: string;
77
83
  belongsToField?: string;
@@ -151,8 +157,45 @@ export interface AppSettings {
151
157
  integrations?: IntegrationSetting[];
152
158
  /** Whether the team is emailed when production fails. On unless `{ failures: false }`. */
153
159
  alerts?: AlertSetting;
160
+ /**
161
+ * The app's MCP server for its own users, at `<app address>/mcp`: people add it in Claude or ChatGPT and sign in as
162
+ * one of the app's users. Its tools are the actions that export `mcp` (ActionMcp). Left out, the endpoint is off.
163
+ */
164
+ mcp?: McpSetting | true;
154
165
  [key: string]: unknown;
155
166
  }
167
+ /** What MCP clients and the sign-in's consent page call the app's MCP server. */
168
+ export interface McpSetting {
169
+ /** At most 60 characters; the app's name when left out. */
170
+ name?: string;
171
+ /** At most 500 characters. */
172
+ description?: string;
173
+ }
174
+ /**
175
+ * An action as a tool on the app's MCP server (settings.ib.ts `mcp`): `export const mcp: ActionMcp = { … }` beside
176
+ * `options`. It runs as the signed-in user, held to their roles in permissions.ib.ts like the app's own pages; its
177
+ * input is the action's params. A user whose roles can't run it doesn't see it.
178
+ */
179
+ export interface ActionMcp {
180
+ /** The tool's name in a client's list, at most 60 characters. */
181
+ title: string;
182
+ /** What it does, what it changes and its limits, for the person and the model. At most 1000 characters. */
183
+ description: string;
184
+ /** It changes nothing (needs the read scope only). False unless set. */
185
+ readOnly?: boolean;
186
+ /** It deletes, overwrites, sends something outside or spends money: clients ask before each call. True for a write unless set false. */
187
+ destructive?: boolean;
188
+ /** Running it again with the same input changes nothing more. */
189
+ idempotent?: boolean;
190
+ /** It reaches services outside the app (email, payments, other APIs). */
191
+ openWorld?: boolean;
192
+ /**
193
+ * The widget that shows its answers in Claude and ChatGPT (MCP Apps): `widgets/<name>.html`, one self-contained
194
+ * page (inline scripts and styles, no outside requests) that gets the answer from the client by postMessage.
195
+ * Lowercase letters, digits and dashes.
196
+ */
197
+ widget?: string;
198
+ }
156
199
  /**
157
200
  * Failure emails: when an action, job, deploy, release or request fails in production, the team's owners, admins and
158
201
  * the members who can see the app get an email naming what failed, at most one every 12 hours per app (failures in
@@ -787,8 +830,9 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
787
830
  build(values?: M["input"]): M["record"];
788
831
  /**
789
832
  * Whether `password` is the one stored in the record's password field (`password` unless named). Hashes are never
790
- * returned. Failures are counted per `email` (the record without one) and per visitor `ip`; past the limit it throws
791
- * an ApiError with status 429 and a message to show, without checking.
833
+ * returned. Every check is counted before the password is: per record, per `email` and per visitor `ip`; past a limit
834
+ * it throws an ApiError with status 429 and a message to show, without checking. A correct password clears the
835
+ * record's and the email's counts.
792
836
  */
793
837
  checkPassword(id: string, password: string, field?: M["passwords"] | (CheckPasswordOptions & {
794
838
  field?: M["passwords"];
@@ -867,6 +911,28 @@ export type Api = ModelClients & {
867
911
  * request's `api` already are.
868
912
  */
869
913
  asRole(role: string | string[], session?: CallerSession): Api;
914
+ /**
915
+ * The same API with its calls counted against one caller's own limit (20 a second, bursts of 300), so one caller
916
+ * can't use up the app's: `key` is whatever tells callers apart, an API customer's id or a device. Calls for a
917
+ * signed-in user or a customer (`asRole(role, { userId })`) are already counted per person, and the app's records
918
+ * route (`serveRecords`) counts signed-out visitors by IP; name a key where neither fits. Past the limit a call
919
+ * throws ApiError 429 `rate_limit_exceeded`.
920
+ */
921
+ asCaller(key: string): Api;
922
+ /**
923
+ * A limit of the app's own: counts one call against `key` and answers whether it's within `limit` per
924
+ * `windowSeconds` (up to a day). For what the app decides to limit, in a page, a route or an action:
925
+ *
926
+ * const gate = await api.rateLimit(`contact:${ip}`, { limit: 5, windowSeconds: 3600 });
927
+ * if (!gate.allowed) return { error: `Too many messages. Try again in ${Math.ceil(gate.resetAfter / 60)} minutes.` };
928
+ *
929
+ * The call is counted either way, before it answers, so calls sent at once can't all pass. Keys are the
930
+ * environment's own; put what the limit is for in the key (`"contact:"`), so two limits never share a count.
931
+ */
932
+ rateLimit(key: string, o: {
933
+ limit: number;
934
+ windowSeconds: number;
935
+ }): Promise<RateLimit>;
870
936
  /** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
871
937
  shopifySync: ShopifySync;
872
938
  /**
@@ -876,6 +942,13 @@ export type Api = ModelClients & {
876
942
  */
877
943
  files: FilesClient;
878
944
  };
945
+ /** What `api.rateLimit` answers: whether the call is within the limit, how many are left in the window, and the seconds until it ends. */
946
+ export interface RateLimit {
947
+ allowed: boolean;
948
+ limit: number;
949
+ remaining: number;
950
+ resetAfter: number;
951
+ }
879
952
  /** A file in the app's storage. `url` is the CDN's for a public file and signed for an hour for a private one. */
880
953
  export interface StorageFile {
881
954
  path: string;
@@ -1044,6 +1117,10 @@ export interface ClientOptions {
1044
1117
  /** Holds every call to a role in permissions.ib.ts, or to several roles' grants together (see `Api.asRole`). */
1045
1118
  role?: string | string[];
1046
1119
  session?: CallerSession;
1120
+ /** Counts every call against this caller's own limit (see `Api.asCaller`). */
1121
+ caller?: string;
1122
+ /** The visitor's IP, which calls are counted by when they're for no user, customer or named caller (`serveRecords` sets it). */
1123
+ callerIp?: string;
1047
1124
  }
1048
1125
  /** The app's API. In an app's deployment every option comes from its environment variables. */
1049
1126
  export declare function createClient(o?: ClientOptions): Api;
@@ -1594,6 +1671,8 @@ export interface ActionCaller {
1594
1671
  /** A storefront customer's Shopify id (numeric), and their shopifyCustomer record's id when the app syncs customers. */
1595
1672
  customerId?: string | null;
1596
1673
  customerRecordId?: string | null;
1674
+ /** The account a web app's signed-in user acts in (`$session: "accountId"`). */
1675
+ accountId?: string | null;
1597
1676
  }
1598
1677
  export type ActionRun<P = Record<string, unknown>> = (ctx: ActionContext<P>) => unknown | Promise<unknown>;
1599
1678
  export type ActionOnSuccess<P = Record<string, unknown>> = (ctx: ActionContext<P>) => void | Promise<void>;
package/dist/index.js CHANGED
@@ -150,6 +150,8 @@ export function createClient(o = {}) {
150
150
  const scope = {
151
151
  ...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(role ? { "x-ib-role": role } : {}),
152
152
  ...(role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}), ...(o.session.accountId ? { accountId: o.session.accountId } : {}) }) } : {}),
153
+ // Who the calls are for, so they count against that caller's own limit (#285).
154
+ ...(o.caller ? { "x-ib-caller": o.caller } : {}), ...(o.callerIp ? { "x-ib-caller-ip": o.callerIp } : {}),
153
155
  };
154
156
  /**
155
157
  * A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
@@ -296,8 +298,16 @@ export function createClient(o = {}) {
296
298
  };
297
299
  const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
298
300
  const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
301
+ const asCaller = (caller) => createClient({ ...o, url, token, app, environment, fetch: f, caller });
302
+ const rateLimit = (key, q) => call("POST", "/rate-limit", { key, limit: q.limit, windowSeconds: q.windowSeconds });
299
303
  return new Proxy({}, {
300
304
  get(_t, prop) {
305
+ if (prop === "asCaller")
306
+ return asCaller;
307
+ if (prop === "rateLimit")
308
+ return rateLimit;
309
+ if (prop === CALLER_IP)
310
+ return (ip) => (o.callerIp === ip ? undefined : createClient({ ...o, url, token, app, environment, fetch: f, callerIp: ip }));
301
311
  if (prop === "$global")
302
312
  return $global;
303
313
  if (prop === "$changes")
@@ -322,6 +332,9 @@ export function createClient(o = {}) {
322
332
  },
323
333
  });
324
334
  }
335
+ // ---- the records route ----
336
+ /** How serveRecords hands a client the visitor's IP; not part of the Api's surface. */
337
+ const CALLER_IP = Symbol.for("ib.callerIp");
325
338
  const errorBody = (status, code, message, problems = []) => Response.json({ error: { code, message, ...(problems.length ? { problems } : {}) } }, { status });
326
339
  /**
327
340
  * The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
@@ -340,6 +353,11 @@ export async function serveRecords(request, api, o = {}) {
340
353
  return errorBody(401, "unauthorized", "Sign in to see this.");
341
354
  if (request.method !== "POST")
342
355
  return errorBody(405, "method_not_allowed", "The records route takes POST.");
356
+ // The visitor's IP, as Inference Bureau's router sets it, so a signed-out visitor's calls count against their own
357
+ // limit and not only the app's (#285). Not on a Shopify proxy request: that one comes from Shopify's servers.
358
+ const ip = request.headers.get("x-ib-proxy-signature") ? null : request.headers.get("x-ib-client-ip");
359
+ if (ip)
360
+ api = api[CALLER_IP]?.(ip) ?? api;
343
361
  let body;
344
362
  try {
345
363
  body = (await request.json());
package/dist/test.js CHANGED
@@ -2808,6 +2808,22 @@ export function createTestApp(o = {}) {
2808
2808
  };
2809
2809
  const syncRuns = [];
2810
2810
  const apis = new Map();
2811
+ // The app's own rate limits, counted as the API does: per key, in fixed windows from the epoch on the harness's clock.
2812
+ const limitCounts = new Map();
2813
+ const rateLimit = async (key, q) => {
2814
+ const whole = (n, max) => typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= max;
2815
+ if (typeof key !== "string" || !key.trim() || key.length > 200)
2816
+ throw new ApiError("key is text of 1 to 200 characters", 400, "invalid_request");
2817
+ if (!whole(q?.limit, 1_000_000))
2818
+ throw new ApiError("limit is a whole number from 1 to 1,000,000", 400, "invalid_request");
2819
+ if (!whole(q?.windowSeconds, 86_400))
2820
+ throw new ApiError("windowSeconds is a whole number from 1 to 86,400 (a day)", 400, "invalid_request");
2821
+ const now = (o.now ?? Date.now)(), span = q.windowSeconds * 1000, window = Math.floor(now / span);
2822
+ const at = `${key}\n${q.windowSeconds}\n${window}`;
2823
+ const n = (limitCounts.get(at) ?? 0) + 1;
2824
+ limitCounts.set(at, n);
2825
+ return { allowed: n <= q.limit, limit: q.limit, remaining: Math.max(0, q.limit - n), resetAfter: Math.max(1, Math.ceil(((window + 1) * span - now) / 1000)) };
2826
+ };
2811
2827
  /** A role's name as the API takes it; a malformed one is refused, never ignored (ignoring it would widen the call). */
2812
2828
  const roleOf = (role) => {
2813
2829
  const names = [...new Set((Array.isArray(role) ? role : role.split(",")).map((r) => r.trim()).filter(Boolean))];
@@ -2891,6 +2907,11 @@ export function createTestApp(o = {}) {
2891
2907
  return (s) => apiFor({ ...scope, shop: s });
2892
2908
  if (prop === "asRole")
2893
2909
  return (role, session) => apiFor({ ...scope, role: roleOf(role), session: session ? sessionOf(session) : scope.session });
2910
+ // A caller's own limit is the API's to keep; under test the calls go through as they are.
2911
+ if (prop === "asCaller")
2912
+ return () => made;
2913
+ if (prop === "rateLimit")
2914
+ return rateLimit;
2894
2915
  if (prop === "shopifySync")
2895
2916
  return shopifySync(scope);
2896
2917
  if (prop === "files")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.16.6",
3
+ "version": "0.16.8",
4
4
  "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [