@shop-on/theme-cli 0.10.0 → 0.11.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.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { createRpcClient } from "../../../contract-kit/src/client.mjs";
3
+ // ../api-contract/src/merchant/client.ts
4
+ function createMerchantClient(options) {
5
+ return createRpcClient("merchant", "include", options);
6
+ }
7
+ export { createMerchantClient };
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { createRpcClient } from "../../../contract-kit/src/client.mjs";
3
+ // ../api-contract/src/storefront/client.ts
4
+ function createStorefrontClient(options) {
5
+ return createRpcClient("storefront", "omit", options);
6
+ }
7
+ export { createStorefrontClient };
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // ../api-contract/src/theme-cli.ts
3
+ /** The resource a theme CLI token is issued for. */
4
+ const THEME_CLI_RESOURCE = "urn:shop-on:theme-cli";
5
+ export { THEME_CLI_RESOURCE };
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { MissingEnvError, loadThemeEnv } from "./env.mjs";
3
3
  import { openBrowser } from "./lighthouse.mjs";
4
- import { average, pageScore, verdict } from "./score.mjs";
5
4
  import { BAR, formatReport } from "./report.mjs";
6
5
  import { auditRoutes, checkRoutes } from "./routes.mjs";
6
+ import { average, pageScore, verdict } from "./score.mjs";
7
7
  import { startBuiltServer } from "./server.mjs";
8
8
  import { fetchStoreData, storeProblems } from "./store.mjs";
9
9
  import { runThemeBuild } from "../theme/build.mjs";
10
10
  import { existsSync } from "node:fs";
11
11
  import path from "node:path";
12
12
  import { parseArgs, styleText } from "node:util";
13
- //#region src/audit/command.ts
13
+ // src/audit/command.ts
14
14
  const USAGE = `usage: shop-on theme audit [--theme <dir>] [--runs 3] [--json] [--skip-build]
15
15
 
16
16
  --theme <dir> the theme to audit (default: the current directory)
@@ -181,5 +181,4 @@ async function runAudit({ argv, cwd = process.cwd(), io = processIo, deps: overr
181
181
  await cleanUp();
182
182
  }
183
183
  }
184
- //#endregion
185
184
  export { USAGE, processIo, runAudit };
@@ -2,12 +2,11 @@
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { parseEnv } from "node:util";
5
- //#region src/audit/env.ts
5
+ // src/audit/env.ts
6
6
  /** What the theme server reads from its environment — the starter's `.env.example`. */
7
7
  const THEME_ENV_KEYS = [
8
8
  "STOREFRONT_API_URL",
9
- "STOREFRONT_CLIENT_ID",
10
- "STOREFRONT_CLIENT_SECRET",
9
+ "STOREFRONT_KEY",
11
10
  "STORE_SLUG",
12
11
  "STOREFRONT_CUSTOMER_SESSION_SECRET"
13
12
  ];
@@ -52,14 +51,9 @@ function loadThemeEnv(themeDir, processEnv = process.env) {
52
51
  }
53
52
  /** The values to scrub from anything a child process printed. */
54
53
  function secretValues(env) {
55
- return [
56
- env.STOREFRONT_CLIENT_ID,
57
- env.STOREFRONT_CLIENT_SECRET,
58
- env.STOREFRONT_CUSTOMER_SESSION_SECRET
59
- ];
54
+ return [env.STOREFRONT_KEY, env.STOREFRONT_CUSTOMER_SESSION_SECRET];
60
55
  }
61
56
  function redact(text, secrets) {
62
57
  return secrets.filter(Boolean).reduce((out, s) => out.split(s).join("[redacted]"), text);
63
58
  }
64
- //#endregion
65
59
  export { MissingEnvError, THEME_ENV_KEYS, loadThemeEnv, redact, secretValues, themeEnvFiles };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- //#region src/audit/lighthouse.ts
2
+ // src/audit/lighthouse.ts
3
3
  /**
4
4
  * Headless Chrome plus Lighthouse, both loaded on first use so the rest of the
5
5
  * CLI never pays for them. Chrome is launched once; Lighthouse resets storage
@@ -63,5 +63,4 @@ function scoresOf(lhr, formFactor) {
63
63
  accessibility: score("accessibility")
64
64
  };
65
65
  }
66
- //#endregion
67
66
  export { openBrowser, scoresOf };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { display } from "./score.mjs";
3
3
  import { styleText } from "node:util";
4
- //#region src/audit/report.ts
4
+ // src/audit/report.ts
5
5
  const BAR = {
6
6
  performance: 60,
7
7
  accessibility: 90
@@ -33,5 +33,4 @@ function formatReport(report) {
33
33
  }
34
34
  return out.join("\n");
35
35
  }
36
- //#endregion
37
36
  export { BAR, formatReport };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- //#region src/audit/routes.ts
2
+ // src/audit/routes.ts
3
3
  /** An unknown path, so a theme that answers 200 for everything is caught. */
4
4
  const UNKNOWN_PATH = "/shop-on-audit-no-such-page";
5
5
  /**
@@ -87,5 +87,4 @@ async function checkRoutes(baseUrl, routes, fetchImpl = fetch) {
87
87
  }
88
88
  return results;
89
89
  }
90
- //#endregion
91
90
  export { UNKNOWN_PATH, auditRoutes, checkRoutes, evaluateRoute };
@@ -38,5 +38,4 @@ function verdict(avg) {
38
38
  * print as a passing 60. The verdict compares the exact mean.
39
39
  */
40
40
  const display = (n) => Math.floor(n * 10 + 1e-9) / 10;
41
- //#endregion
42
41
  export { average, display, median, pageScore, verdict };
@@ -8,7 +8,7 @@ import net from "node:net";
8
8
  import os from "node:os";
9
9
  import { currentPresetHandle } from "@shop-on/theme-contract/preset-listing";
10
10
  import { materializePreset } from "@shop-on/theme-contract/preset-materializer";
11
- //#region src/audit/server.ts
11
+ // src/audit/server.ts
12
12
  const STOP_GRACE_MS = 5e3;
13
13
  async function freePort() {
14
14
  return new Promise((resolve, reject) => {
@@ -205,5 +205,4 @@ async function startBuiltServer(themeDir, env) {
205
205
  throw err;
206
206
  }
207
207
  }
208
- //#endregion
209
208
  export { freePort, stageConfig, startBuiltServer, startServer };
@@ -1,85 +1,62 @@
1
1
  #!/usr/bin/env node
2
- //#region src/audit/store.ts
3
- const QUERY = `query ShopOnAudit {
4
- products(first: 1) { nodes { handle } }
5
- collections(first: 1) { nodes { handle } }
6
- pages(first: 1) { nodes { handle } }
7
- articles(first: 1) { nodes { handle blog { handle } } }
8
- shop { shopPolicies { handle } passwordProtection { enabled } }
9
- }`;
10
- /** A storefront access token from the theme's own credentials: the same
11
- * client_credentials mint and scope theme-server uses. Errors carry the HTTP
12
- * status, never a credential or a response body. */
13
- async function mintStorefrontToken(env, fetchImpl = fetch) {
14
- const api = env.STOREFRONT_API_URL.replace(/\/$/, "");
15
- const tokenRes = await fetchImpl(`${api}/oauth/token`, {
16
- method: "POST",
17
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
18
- body: new URLSearchParams({
19
- grant_type: "client_credentials",
20
- client_id: env.STOREFRONT_CLIENT_ID,
21
- client_secret: env.STOREFRONT_CLIENT_SECRET,
22
- scope: "storefront public"
23
- })
24
- }).catch((err) => {
25
- throw new Error(`the storefront API at ${api} is unreachable: ${err.message}`);
2
+ import { createStorefrontClient } from "../api-contract/src/storefront/client.mjs";
3
+ // src/audit/store.ts
4
+ /** How long one storefront call may take before it fails DEADLINE_EXCEEDED. */
5
+ const STOREFRONT_TIMEOUT_MS = 3e4;
6
+ /** The storefront client for the theme's store, under its own key. */
7
+ function storefrontClient(env, fetchImpl = (request) => fetch(request)) {
8
+ return createStorefrontClient({
9
+ baseUrl: env.STOREFRONT_API_URL.replace(/\/+$/, ""),
10
+ fetch: fetchImpl,
11
+ timeoutMs: STOREFRONT_TIMEOUT_MS,
12
+ headers: () => ({ authorization: `Bearer ${env.STOREFRONT_KEY}` })
26
13
  });
27
- if (!tokenRes.ok) throw new Error(`storefront token exchange at ${api} failed (${tokenRes.status}): check STOREFRONT_CLIENT_ID / STOREFRONT_CLIENT_SECRET`);
28
- const { access_token: token, expires_in: expiresIn } = await tokenRes.json();
29
- if (!token) throw new Error(`storefront token exchange at ${api} returned no access_token`);
30
- return {
31
- token,
32
- expiresAt: Date.now() + (expiresIn ?? 0) * 1e3
33
- };
34
14
  }
35
- /** One storefront GraphQL query under `token`. */
36
- async function storefrontQuery(env, token, query, variables = {}, fetchImpl = fetch) {
37
- const res = await fetchImpl(`${env.STOREFRONT_API_URL.replace(/\/$/, "")}/graphql`, {
38
- method: "POST",
39
- headers: {
40
- "Content-Type": "application/json",
41
- Authorization: `Bearer ${token}`
42
- },
43
- body: JSON.stringify({
44
- query,
45
- variables
46
- })
47
- });
48
- const body = await res.json().catch(() => null);
49
- if (!res.ok || !body?.data) {
50
- const reason = body?.errors?.map((e) => e.message).join("; ") ?? `HTTP ${res.status}`;
51
- throw new Error(`storefront query failed: ${reason}`);
15
+ /** `call`, its contract error turned into one that names the api and the code. */
16
+ async function storefrontCall(env, call) {
17
+ try {
18
+ return await call;
19
+ } catch (err) {
20
+ const code = err?.code;
21
+ if (code === "UNAUTHENTICATED") throw new Error(`the storefront api at ${env.STOREFRONT_API_URL} refused STOREFRONT_KEY`);
22
+ if (typeof code === "string") throw new Error(`the storefront api at ${env.STOREFRONT_API_URL} answered ${code}`);
23
+ throw err;
52
24
  }
53
- return body.data;
54
25
  }
55
- /** Reads the handles the audit needs with the theme's own storefront credentials. */
56
- async function fetchStoreData(env, fetchImpl = fetch) {
57
- const { token } = await mintStorefrontToken(env, fetchImpl);
58
- const d = await storefrontQuery(env, token, QUERY, {}, fetchImpl);
59
- const article = d.articles.nodes[0];
26
+ /**
27
+ * Reads the handles the audit needs. No storefront procedure lists pages,
28
+ * blogs or articles (`pages.get` and `blogs.get` read one by handle), so
29
+ * those routes are skipped.
30
+ */
31
+ async function fetchStoreData(env, fetchImpl) {
32
+ const api = storefrontClient(env, fetchImpl);
33
+ const [products, collections, policies, shop] = await storefrontCall(env, Promise.all([
34
+ api.products.list({ limit: 1 }),
35
+ api.collections.list({ limit: 1 }),
36
+ api.policies.list({}),
37
+ api.shop.get()
38
+ ]));
60
39
  return {
61
- product: d.products.nodes[0]?.handle ?? null,
62
- collection: d.collections.nodes[0]?.handle ?? null,
63
- page: d.pages.nodes[0]?.handle ?? null,
64
- blog: article?.blog.handle ?? null,
65
- article: article?.handle ?? null,
66
- policy: d.shop.shopPolicies[0]?.handle ?? null,
67
- passwordProtected: d.shop.passwordProtection?.enabled ?? false
40
+ product: products.items[0]?.handle ?? null,
41
+ collection: collections.items[0]?.handle ?? null,
42
+ page: null,
43
+ blog: null,
44
+ article: null,
45
+ policy: policies.items[0]?.handle ?? null,
46
+ passwordProtected: shop.passwordProtection.enabled
68
47
  };
69
48
  }
70
49
  /**
71
50
  * What stops the audit before it builds anything. Home, product and collection
72
- * are the Lighthouse pages and the article route needs an article, so an empty
73
- * store would measure empty templates and pass them. A page and a policy are
74
- * optional: their routes are skipped instead.
51
+ * are the Lighthouse pages, so an empty store would measure empty templates
52
+ * and pass them. The other routes are skipped when the store has nothing for
53
+ * them.
75
54
  */
76
55
  function storeProblems(data) {
77
56
  const problems = [];
78
57
  if (!data.product) problems.push("no product");
79
58
  if (!data.collection) problems.push("no collection");
80
- if (!data.article) problems.push("no blog article");
81
59
  if (data.passwordProtected) problems.push("the storefront is password-protected, so every page redirects to /password: turn protection off while auditing");
82
60
  return problems;
83
61
  }
84
- //#endregion
85
- export { fetchStoreData, mintStorefrontToken, storeProblems, storefrontQuery };
62
+ export { fetchStoreData, storeProblems, storefrontCall, storefrontClient };
package/dist/auth/api.mjs CHANGED
@@ -1,9 +1,14 @@
1
1
  #!/usr/bin/env node
2
+ import { createMerchantClient } from "../api-contract/src/merchant/client.mjs";
2
3
  import { readSession } from "./credentials.mjs";
3
4
  import { LoginRequiredError, refreshSession } from "./oauth.mjs";
4
- //#region src/auth/api.ts
5
+ // src/auth/api.ts
5
6
  const EXPIRY_MARGIN_MS = 6e4;
6
- async function graphql({ apiUrl, configDir }, query, variables = {}) {
7
+ /** How long one merchant call may take before it fails DEADLINE_EXCEEDED. */
8
+ const MERCHANT_TIMEOUT_MS = 3e4;
9
+ /** Runs `send` with the session's access token, refreshing it first when it is
10
+ * about to expire, and once more when `send` says the api refused it. */
11
+ async function withAccessToken({ apiUrl, configDir }, send) {
7
12
  let session = readSession(configDir, apiUrl);
8
13
  if (!session) throw new LoginRequiredError(apiUrl);
9
14
  if (session.expiresAt - EXPIRY_MARGIN_MS <= Date.now()) session = await refreshSession({
@@ -11,34 +16,57 @@ async function graphql({ apiUrl, configDir }, query, variables = {}) {
11
16
  configDir,
12
17
  staleAccessToken: session.accessToken
13
18
  });
14
- const send = (token) => fetch(`${apiUrl}/graphql`, {
15
- method: "POST",
16
- headers: {
17
- "Content-Type": "application/json",
18
- Authorization: `Bearer ${token}`
19
- },
20
- body: JSON.stringify({
21
- query,
22
- variables
23
- })
24
- }).catch((err) => {
25
- throw new Error(`the api at ${apiUrl} is unreachable: ${err.message}`);
26
- });
27
- let res = await send(session.accessToken);
28
- if (res.status === 401) {
19
+ let answer = await send(session.accessToken);
20
+ if (answer.refused) {
29
21
  session = await refreshSession({
30
22
  apiUrl,
31
23
  configDir,
32
24
  staleAccessToken: session.accessToken
33
25
  });
34
- res = await send(session.accessToken);
26
+ answer = await send(session.accessToken);
27
+ }
28
+ if (answer.refused) throw new LoginRequiredError(apiUrl, `${apiUrl} refused the session`);
29
+ return answer.value;
30
+ }
31
+ /**
32
+ * A merchant call the api answered with one of the contract's codes. The
33
+ * message is the CLI's own (the api's is for its logs); a caller that knows
34
+ * what a code means for its command says so instead.
35
+ */
36
+ var MerchantCallError = class extends Error {
37
+ code;
38
+ data;
39
+ constructor(apiUrl, code, data) {
40
+ super(`${apiUrl} answered ${code}`);
41
+ this.code = code;
42
+ this.data = data;
43
+ this.name = "MerchantCallError";
35
44
  }
36
- if (res.status === 401) throw new LoginRequiredError(apiUrl, `${apiUrl} refused the session`);
37
- if (!res.ok) throw new Error(`${apiUrl}/graphql answered ${res.status}`);
38
- const body = await res.json();
39
- if (body.errors?.length) throw new Error(body.errors.map((e) => e.message).join("; "));
40
- if (!body.data) throw new Error(`${apiUrl}/graphql returned no data`);
41
- return body.data;
45
+ };
46
+ const errorCode = (err) => {
47
+ const code = err?.code;
48
+ return typeof code === "string" ? code : null;
49
+ };
50
+ /** One merchant procedure call as the logged-in developer. The token is bound
51
+ * to the store they picked on the consent page, so no shop is named. */
52
+ function merchant(ctx, call) {
53
+ return withAccessToken(ctx, async (token) => {
54
+ const client = createMerchantClient({
55
+ baseUrl: ctx.apiUrl,
56
+ timeoutMs: MERCHANT_TIMEOUT_MS,
57
+ headers: () => ({ authorization: `Bearer ${token}` })
58
+ });
59
+ try {
60
+ return {
61
+ refused: false,
62
+ value: await call(client)
63
+ };
64
+ } catch (err) {
65
+ const code = errorCode(err);
66
+ if (code === "UNAUTHENTICATED") return { refused: true };
67
+ if (code) throw new MerchantCallError(ctx.apiUrl, code, err.data);
68
+ throw err;
69
+ }
70
+ });
42
71
  }
43
- //#endregion
44
- export { graphql };
72
+ export { MerchantCallError, merchant };
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import os from "node:os";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { setTimeout } from "node:timers/promises";
7
- //#region src/auth/credentials.ts
7
+ // src/auth/credentials.ts
8
8
  const defaultConfigDir = () => path.join(os.homedir(), ".config", "shop-on");
9
9
  const credentialsFile = (dir) => path.join(dir, "credentials.json");
10
10
  function readAll(dir) {
@@ -100,5 +100,4 @@ async function withCredentialsLock(dir, fn) {
100
100
  if (readLock(lock) === mine) rmSync(lock, { force: true });
101
101
  }
102
102
  }
103
- //#endregion
104
103
  export { defaultConfigDir, readSession, withCredentialsLock, writeSession };
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import { THEME_CLI_RESOURCE } from "../api-contract/src/theme-cli.mjs";
2
3
  import { readSession, withCredentialsLock, writeSession } from "./credentials.mjs";
3
4
  import { createHash, randomBytes } from "node:crypto";
4
5
  import http from "node:http";
5
- //#region src/auth/oauth.ts
6
- const CLIENT_ID = "shop-on-cli";
7
- const SCOPE = "write_themes";
6
+ // src/auth/oauth.ts
7
+ /** A refresh token comes only with `offline_access`. */
8
+ const SCOPE = "offline_access";
9
+ const CLIENT_NAME = "Shop On theme CLI";
8
10
  const DEFAULT_API_URL = "https://api.shopon.mn";
9
11
  const LOGIN_TIMEOUT_MS = 3e5;
10
12
  /** The `--api` a printed command needs to reach `apiUrl`: none for production. */
@@ -18,23 +20,44 @@ var LoginRequiredError = class extends Error {
18
20
  };
19
21
  /** `--api`, then `SHOP_ON_API_URL`, then production; never a trailing slash. */
20
22
  const resolveApiUrl = (flag, env = process.env) => (flag || env.SHOP_ON_API_URL || "https://api.shopon.mn").replace(/\/+$/, "");
23
+ /** The OAuth server's metadata (RFC 8414): its issuer is `<api>/auth`. */
21
24
  async function discover(apiUrl) {
22
- const url = `${apiUrl}/.well-known/oauth-authorization-server`;
25
+ const url = `${apiUrl}/.well-known/oauth-authorization-server/auth`;
23
26
  const res = await fetch(url).catch((err) => {
24
27
  throw new Error(`the api at ${apiUrl} is unreachable: ${err.message}`);
25
28
  });
26
29
  if (!res.ok) throw new Error(`${url} answered ${res.status}`);
27
30
  return await res.json();
28
31
  }
29
- /** Admin's origin: the consent page the discovery document names lives there. */
30
- const adminOrigin = (discovery) => new URL(discovery.authorization_endpoint).origin;
31
32
  var TokenRefusedError = class extends Error {};
32
- async function tokenRequest(endpoint, params) {
33
+ /** Registers this login's client: public, for the CLI's resource and `redirectUri`. */
34
+ async function register(discovery, redirectUri) {
35
+ const endpoint = discovery.registration_endpoint;
36
+ if (!endpoint) throw new Error("the api's OAuth server offers no client registration");
37
+ const res = await fetch(endpoint, {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json" },
40
+ body: JSON.stringify({
41
+ client_name: CLIENT_NAME,
42
+ redirect_uris: [redirectUri],
43
+ token_endpoint_auth_method: "none",
44
+ grant_types: ["authorization_code", "refresh_token"],
45
+ response_types: ["code"],
46
+ scope: SCOPE,
47
+ resources: [THEME_CLI_RESOURCE]
48
+ })
49
+ });
50
+ const body = await res.json().catch(() => ({}));
51
+ if (!res.ok || !body.client_id) throw new Error(`the client registration endpoint answered ${res.status}`);
52
+ return body.client_id;
53
+ }
54
+ async function tokenRequest(endpoint, clientId, params) {
33
55
  const res = await fetch(endpoint, {
34
56
  method: "POST",
35
57
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
36
58
  body: new URLSearchParams({
37
- client_id: CLIENT_ID,
59
+ client_id: clientId,
60
+ resource: THEME_CLI_RESOURCE,
38
61
  ...params
39
62
  })
40
63
  });
@@ -42,15 +65,15 @@ async function tokenRequest(endpoint, params) {
42
65
  if (res.status === 400 || res.status === 401) throw new TokenRefusedError(body.error_description ?? body.error ?? `refused (${res.status})`);
43
66
  if (!res.ok || !body.access_token || !body.refresh_token) throw new Error(`the token endpoint answered ${res.status}`);
44
67
  return {
68
+ clientId,
45
69
  accessToken: body.access_token,
46
70
  refreshToken: body.refresh_token,
47
71
  expiresAt: Date.now() + (body.expires_in ?? 0) * 1e3
48
72
  };
49
73
  }
50
74
  /**
51
- * Ends the api session `session` was minted under (RFC 7009): the api revokes
52
- * the whole session for either of its tokens. Best-effort: a failure is
53
- * printed, never thrown.
75
+ * Ends the session `session` was minted under (RFC 7009), by its refresh
76
+ * token. Best-effort: a failure is printed, never thrown.
54
77
  */
55
78
  async function revokeSession(endpoint, session, io) {
56
79
  try {
@@ -58,7 +81,7 @@ async function revokeSession(endpoint, session, io) {
58
81
  method: "POST",
59
82
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
60
83
  body: new URLSearchParams({
61
- client_id: CLIENT_ID,
84
+ client_id: session.clientId,
62
85
  token: session.refreshToken,
63
86
  token_type_hint: "refresh_token"
64
87
  })
@@ -109,29 +132,31 @@ async function awaitCallback(state, timeoutMs) {
109
132
  };
110
133
  }
111
134
  /**
112
- * The loopback PKCE flow: opens admin's consent page, waits for its redirect,
113
- * redeems the code, and saves the session for `apiUrl`, ending the one it
114
- * replaces.
135
+ * The loopback PKCE flow: registers this login's client, opens the consent
136
+ * page, waits for its redirect, redeems the code, and saves the session for
137
+ * `apiUrl`, ending the one it replaces.
115
138
  */
116
139
  async function login({ apiUrl, configDir, io, openUrl, timeoutMs = LOGIN_TIMEOUT_MS }) {
117
140
  const discovery = await discover(apiUrl);
118
141
  const verifier = base64url(randomBytes(32));
119
142
  const state = base64url(randomBytes(16));
120
143
  const callback = await awaitCallback(state, timeoutMs);
144
+ const clientId = await register(discovery, callback.redirectUri);
121
145
  const authorize = new URL(discovery.authorization_endpoint);
122
146
  authorize.search = new URLSearchParams({
123
147
  response_type: "code",
124
- client_id: CLIENT_ID,
148
+ client_id: clientId,
125
149
  redirect_uri: callback.redirectUri,
126
150
  scope: SCOPE,
127
151
  state,
128
152
  code_challenge: base64url(createHash("sha256").update(verifier).digest()),
129
- code_challenge_method: "S256"
153
+ code_challenge_method: "S256",
154
+ resource: THEME_CLI_RESOURCE
130
155
  }).toString();
131
156
  io.err(`Opening your browser to approve the CLI. If it doesn't open, visit:\n\n ${authorize.href}\n`);
132
157
  openUrl(authorize.href);
133
158
  const code = await callback.code;
134
- const session = await tokenRequest(discovery.token_endpoint, {
159
+ const session = await tokenRequest(discovery.token_endpoint, clientId, {
135
160
  grant_type: "authorization_code",
136
161
  code,
137
162
  redirect_uri: callback.redirectUri,
@@ -160,7 +185,7 @@ async function refreshSession({ apiUrl, configDir, staleAccessToken }) {
160
185
  if (current.accessToken !== staleAccessToken) return current;
161
186
  const { token_endpoint } = await discover(apiUrl);
162
187
  try {
163
- const session = await tokenRequest(token_endpoint, {
188
+ const session = await tokenRequest(token_endpoint, current.clientId, {
164
189
  grant_type: "refresh_token",
165
190
  refresh_token: current.refreshToken
166
191
  });
@@ -177,5 +202,4 @@ async function refreshSession({ apiUrl, configDir, staleAccessToken }) {
177
202
  async function ensureLoggedIn(options) {
178
203
  if (!readSession(options.configDir, options.apiUrl)) await login(options);
179
204
  }
180
- //#endregion
181
- export { CLIENT_ID, DEFAULT_API_URL, LoginRequiredError, SCOPE, adminOrigin, apiFlag, discover, ensureLoggedIn, login, refreshSession, resolveApiUrl };
205
+ export { DEFAULT_API_URL, LoginRequiredError, SCOPE, apiFlag, discover, ensureLoggedIn, login, refreshSession, resolveApiUrl };