@inferencebureau/apps-sdk 0.16.7 → 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;
@@ -905,6 +911,28 @@ export type Api = ModelClients & {
905
911
  * request's `api` already are.
906
912
  */
907
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>;
908
936
  /** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
909
937
  shopifySync: ShopifySync;
910
938
  /**
@@ -914,6 +942,13 @@ export type Api = ModelClients & {
914
942
  */
915
943
  files: FilesClient;
916
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
+ }
917
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. */
918
953
  export interface StorageFile {
919
954
  path: string;
@@ -1082,6 +1117,10 @@ export interface ClientOptions {
1082
1117
  /** Holds every call to a role in permissions.ib.ts, or to several roles' grants together (see `Api.asRole`). */
1083
1118
  role?: string | string[];
1084
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;
1085
1124
  }
1086
1125
  /** The app's API. In an app's deployment every option comes from its environment variables. */
1087
1126
  export declare function createClient(o?: ClientOptions): Api;
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.7",
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": [