@inferencebureau/apps-sdk 0.4.0 → 0.4.1

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 CHANGED
@@ -74,12 +74,12 @@ with a key linked to the app.
74
74
  Entry points:
75
75
 
76
76
  - `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
77
- `verifyShopifySession`, `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
77
+ `verifyShopifySession` (and `scopesRequired` for optional scopes), `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
78
78
  `activeSubscriptions`, `recordUsage`, `cancelSubscription`, `managedPricingUrl`), and the errors they throw
79
79
  (`ApiError`, `ShopifyError`, `ShopifyBillingError`).
80
80
  - `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
81
81
  - `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
82
- `shopifySessionToken`, `isPreview`, `previewSession`.
82
+ `shopifySessionToken`, `isPreview`, `previewSession`, `requestScopes`.
83
83
  - `@inferencebureau/apps-sdk/test`: for the app's tests: `loadApp` (or `createTestApp`) runs actions against
84
84
  in-memory records with the records engine's rules, mocks the Shopify Admin API, delivers webhooks and installs,
85
85
  and runs queued jobs; `fixtures` has Shopify's webhook payloads. Node only, under Vitest with this package inlined:
package/dist/browser.d.ts CHANGED
@@ -13,5 +13,15 @@ export declare function previewSession(): string | null;
13
13
  export declare const isPreview: () => boolean;
14
14
  /** The session token for the page's requests: the preview's, else App Bridge's, else null (not in the admin). */
15
15
  export declare function shopifySessionToken(): Promise<string | null>;
16
- /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
16
+ /**
17
+ * Asks the merchant to grant optional scopes (settings.ib.ts `shopify.optionalScopes`) with Shopify's approval
18
+ * (App Bridge's `shopify.scopes.request`). True once every one is granted; false when the merchant declines, or the
19
+ * page isn't in the Shopify admin (the preview has no App Bridge to ask with).
20
+ */
21
+ export declare function requestScopes(scopes: string[]): Promise<boolean>;
22
+ /**
23
+ * `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. A route that answers
24
+ * `scopesRequired(...)` gets Shopify's approval for those scopes shown to the merchant, and the request is sent once
25
+ * more if they grant them; otherwise its 403 comes back as it was.
26
+ */
17
27
  export declare function sessionFetch(input: string | URL, init?: RequestInit): Promise<Response>;
package/dist/browser.js CHANGED
@@ -8,6 +8,10 @@
8
8
  * the tab (sessionStorage) so the page's own navigation keeps it, and taken off the address bar.
9
9
  */
10
10
  const KEY = "ib_preview";
11
+ /** The header `scopesRequired` (the SDK's server side) names missing scopes in. */
12
+ const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
13
+ /** The header a request sent again after the merchant granted scopes carries, for `verifyShopifySession`. */
14
+ const REFRESH_SCOPES_HEADER = "x-ib-refresh-scopes";
11
15
  function storage() {
12
16
  try {
13
17
  return window.sessionStorage;
@@ -84,12 +88,45 @@ function plainRequest(input, init, headers) {
84
88
  xhr.send((init.body ?? null));
85
89
  });
86
90
  }
87
- /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
91
+ /**
92
+ * Asks the merchant to grant optional scopes (settings.ib.ts `shopify.optionalScopes`) with Shopify's approval
93
+ * (App Bridge's `shopify.scopes.request`). True once every one is granted; false when the merchant declines, or the
94
+ * page isn't in the Shopify admin (the preview has no App Bridge to ask with).
95
+ */
96
+ export async function requestScopes(scopes) {
97
+ const bridge = globalThis.shopify;
98
+ if (!scopes.length)
99
+ return true;
100
+ if (isPreview() || !bridge?.scopes?.request)
101
+ return false;
102
+ try {
103
+ const r = await bridge.scopes.request(scopes);
104
+ return r.result === "granted-all" || scopes.every((s) => r.detail?.granted?.includes(s));
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ }
110
+ /**
111
+ * `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. A route that answers
112
+ * `scopesRequired(...)` gets Shopify's approval for those scopes shown to the merchant, and the request is sent once
113
+ * more if they grant them; otherwise its 403 comes back as it was.
114
+ */
88
115
  export async function sessionFetch(input, init = {}) {
89
116
  const preview = previewSession();
90
- const token = preview ?? (await shopifySessionToken());
91
- const headers = new Headers(init.headers);
92
- if (token)
93
- headers.set("authorization", `Bearer ${token}`);
94
- return preview ? plainRequest(input, init, headers) : fetch(input, { ...init, headers });
117
+ const send = async (granted = false) => {
118
+ const token = preview ?? (await shopifySessionToken());
119
+ const headers = new Headers(init.headers);
120
+ if (token)
121
+ headers.set("authorization", `Bearer ${token}`);
122
+ // The route's session check reads the store's grant again, so it sees what was just granted.
123
+ if (granted)
124
+ headers.set(REFRESH_SCOPES_HEADER, "1");
125
+ return preview ? plainRequest(input, init, headers) : fetch(input, { ...init, headers });
126
+ };
127
+ const res = await send();
128
+ const missing = res.status === 403 ? (res.headers.get(MISSING_SCOPES_HEADER) ?? "").split(",").map((s) => s.trim()).filter(Boolean) : [];
129
+ // A body that's a stream can't be sent twice.
130
+ const resendable = init.body == null || typeof init.body === "string" || init.body instanceof URLSearchParams || init.body instanceof FormData || init.body instanceof Blob;
131
+ return missing.length && resendable && (await requestScopes(missing)) ? send(true) : res;
95
132
  }
package/dist/index.d.ts CHANGED
@@ -78,8 +78,19 @@ export interface AppSettings {
78
78
  webhooks?: WebhookSetting[];
79
79
  /** Actions queued on a cron schedule, `params.scheduledAt` the time it was due. */
80
80
  schedules?: ScheduleSetting[];
81
+ /** How the Shopify app installs, and the scopes it asks for later. */
82
+ shopify?: ShopifyInstallSettings;
81
83
  [key: string]: unknown;
82
84
  }
85
+ export interface ShopifyInstallSettings {
86
+ /**
87
+ * `managed` (the default): Shopify installs the app with the scopes from the dashboard, and the app's first load in
88
+ * the admin records the store, with no redirect or second approval screen. `oauth`: the authorization redirect.
89
+ */
90
+ install?: "managed" | "oauth";
91
+ /** Scopes the app asks for once it needs them, in the admin: `requestScopes` from the browser helpers. */
92
+ optionalScopes?: string[];
93
+ }
83
94
  export interface WebhookSetting {
84
95
  /** A Shopify webhook topic, e.g. orders/create. The app's scopes must allow it. */
85
96
  topic: string;
@@ -611,6 +622,8 @@ export interface ShopifySession {
611
622
  preview?: {
612
623
  actor: string;
613
624
  };
625
+ /** The scopes the store has granted the app. */
626
+ scopes: string[];
614
627
  /** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
615
628
  api: Api;
616
629
  }
@@ -621,6 +634,17 @@ export interface ShopifySession {
621
634
  * Inference Bureau holds, so the check happens there; never trust a shop named any other way.
622
635
  */
623
636
  export declare function verifyShopifySession(request: Request | string, o?: ClientOptions): Promise<ShopifySession | null>;
637
+ /**
638
+ * The answer for a request that needs scopes the store hasn't granted (`session.scopes`), e.g. settings.ib.ts's
639
+ * `optionalScopes`: 403 naming them. The browser helpers' `sessionFetch` asks the merchant for them with Shopify's
640
+ * approval (App Bridge's `shopify.scopes.request`) and sends the request again once they're granted.
641
+ *
642
+ * const missing = ["read_orders"].filter((s) => !session.scopes.includes(s));
643
+ * if (missing.length) return scopesRequired(missing);
644
+ */
645
+ export declare function scopesRequired(scopes: string[]): Response;
646
+ /** The header `scopesRequired` names the missing scopes in, for the browser helpers. */
647
+ export declare const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
624
648
  export interface ProxyRequest {
625
649
  /** The store whose storefront made the request (x.myshopify.com). */
626
650
  shop: string;
package/dist/index.js CHANGED
@@ -465,11 +465,13 @@ export async function verifyShopifySession(request, o = {}) {
465
465
  const token = typeof request === "string" ? request : (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
466
466
  if (!token || token.split(".").length !== 3)
467
467
  return null;
468
+ // Sent again after the merchant granted scopes (the browser helpers' sessionFetch): the store's grant is read again.
469
+ const refresh = typeof request !== "string" && request.headers.get("x-ib-refresh-scopes") === "1";
468
470
  const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
469
471
  const app = o.app ?? envVar("IB_APP") ?? "";
470
472
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
471
473
  const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/session`, {
472
- method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token }),
474
+ method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token, ...(refresh ? { refresh: true } : {}) }),
473
475
  });
474
476
  const json = (await res.json().catch(() => ({})));
475
477
  // A refused session token is an answer (null); anything else, like the app's own token being refused, is an error.
@@ -478,8 +480,21 @@ export async function verifyShopifySession(request, o = {}) {
478
480
  if (!res.ok)
479
481
  throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
480
482
  const api = createClient({ ...o, shop: json.shop, role: "shopify-app-users", session: { userId: json.userId } });
481
- return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), api };
483
+ return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), scopes: json.scopes ?? [], api };
482
484
  }
485
+ /**
486
+ * The answer for a request that needs scopes the store hasn't granted (`session.scopes`), e.g. settings.ib.ts's
487
+ * `optionalScopes`: 403 naming them. The browser helpers' `sessionFetch` asks the merchant for them with Shopify's
488
+ * approval (App Bridge's `shopify.scopes.request`) and sends the request again once they're granted.
489
+ *
490
+ * const missing = ["read_orders"].filter((s) => !session.scopes.includes(s));
491
+ * if (missing.length) return scopesRequired(missing);
492
+ */
493
+ export function scopesRequired(scopes) {
494
+ return Response.json({ error: { code: "missing_scopes", message: `The store hasn't granted ${scopes.join(", ")}.`, scopes } }, { status: 403, headers: { [MISSING_SCOPES_HEADER]: scopes.join(",") } });
495
+ }
496
+ /** The header `scopesRequired` names the missing scopes in, for the browser helpers. */
497
+ export const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
483
498
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
484
499
  /**
485
500
  * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client and a test harness for its actions.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [