@sanity-labs/client-fake-for-test 0.23.0 → 0.25.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/dist/index.d.cts CHANGED
@@ -183,9 +183,23 @@ export declare interface CreateTestClientOptions {
183
183
  * more identities later with `addIdentity`.
184
184
  */
185
185
  identities?: Record<string, TestClientIdentity>;
186
+ /**
187
+ * The Content Lake's internal-token keys: RSA public key PEMs (SPKI or
188
+ * PKCS#1). A bearer that is not a registered identity, has a JWT's three
189
+ * segments and verifies as RS256 against any of these is an internal
190
+ * token, as a Sanity service mints one: identity `{ user: { id: i },
191
+ * grants: g }`, its `{ s, p }` grants checked like `identities` grants.
192
+ * The Content Lake answers a token that does not verify with 400
193
+ * `httpBadRequest` (`invalid JWT token "<token>": <reason>`) and one
194
+ * whose `x` (epoch seconds) has passed with 403 `permissionDeniedError`
195
+ * (`Token has expired (at <time>)`), as gradient does. Shared by the
196
+ * whole `withConfig` family.
197
+ */
198
+ internalTokenKeys?: string[];
186
199
  /**
187
200
  * Token the root handle is bound to — must name an entry in
188
- * `identities` (unknown tokens throw). Omit to leave the root handle
201
+ * `identities` (unknown tokens throw), or be a JWT when
202
+ * `internalTokenKeys` is set. Omit to leave the root handle
189
203
  * identity-free (a bare factory for token-bound siblings): its
190
204
  * `request` is undefined and its reads/writes are ungated. Mutually
191
205
  * exclusive with `accessControl`.
package/dist/index.d.ts CHANGED
@@ -183,9 +183,23 @@ export declare interface CreateTestClientOptions {
183
183
  * more identities later with `addIdentity`.
184
184
  */
185
185
  identities?: Record<string, TestClientIdentity>;
186
+ /**
187
+ * The Content Lake's internal-token keys: RSA public key PEMs (SPKI or
188
+ * PKCS#1). A bearer that is not a registered identity, has a JWT's three
189
+ * segments and verifies as RS256 against any of these is an internal
190
+ * token, as a Sanity service mints one: identity `{ user: { id: i },
191
+ * grants: g }`, its `{ s, p }` grants checked like `identities` grants.
192
+ * The Content Lake answers a token that does not verify with 400
193
+ * `httpBadRequest` (`invalid JWT token "<token>": <reason>`) and one
194
+ * whose `x` (epoch seconds) has passed with 403 `permissionDeniedError`
195
+ * (`Token has expired (at <time>)`), as gradient does. Shared by the
196
+ * whole `withConfig` family.
197
+ */
198
+ internalTokenKeys?: string[];
186
199
  /**
187
200
  * Token the root handle is bound to — must name an entry in
188
- * `identities` (unknown tokens throw). Omit to leave the root handle
201
+ * `identities` (unknown tokens throw), or be a JWT when
202
+ * `internalTokenKeys` is set. Omit to leave the root handle
189
203
  * identity-free (a bare factory for token-bound siblings): its
190
204
  * `request` is undefined and its reads/writes are ungated. Mutually
191
205
  * exclusive with `accessControl`.
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parse, evaluate } from "groq-js";
2
2
  import { ClientError, ServerError } from "@sanity/client";
3
+ import { createPublicKey, verify } from "node:crypto";
3
4
  const ERR_PREFIX = "[client-fake-for-test]";
4
5
  function fakeError(message) {
5
6
  return new Error(`${ERR_PREFIX} ${message}`);
@@ -410,13 +411,15 @@ function grantsError(grants) {
410
411
  }
411
412
  function refusedToken(request, grants) {
412
413
  const description = grantsError(grants);
413
- if (description !== void 0)
414
- return new PlatformHttpError({
415
- ...request,
416
- statusCode: 400,
417
- statusMessage: "Bad Request",
418
- body: { error: { description, type: "httpBadRequest" } }
419
- });
414
+ return description === void 0 ? void 0 : badRequest(request, description);
415
+ }
416
+ function badRequest(request, description) {
417
+ return new PlatformHttpError({
418
+ ...request,
419
+ statusCode: 400,
420
+ statusMessage: "Bad Request",
421
+ body: { error: { description, type: "httpBadRequest" } }
422
+ });
420
423
  }
421
424
  function createDocumentHistory() {
422
425
  const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
@@ -479,7 +482,7 @@ function createDocumentHistory() {
479
482
  function historyIds(list) {
480
483
  return list.split(",").map((id) => decodeURIComponent(id));
481
484
  }
482
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, PROJECT_API_PATHS = [
485
+ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
483
486
  /^\/users\/me$/,
484
487
  /^\/projects\/[^/]+$/,
485
488
  /^\/projects\/[^/]+\/users\/[^/]+$/,
@@ -522,6 +525,7 @@ async function servePlatformRequest(ctx, uri, request) {
522
525
  }
523
526
  const access = path.match(ACCESS_PATH);
524
527
  if (access !== null) {
528
+ if (ctx.apiVersion < ACCESS_API_SINCE) throw notMounted(request);
525
529
  const [, type, id, rest2] = access;
526
530
  return serveAccess({ ctx, request, type, id: decodeURIComponent(id), rest: rest2 ?? "", query });
527
531
  }
@@ -1757,6 +1761,169 @@ function encodeGroqQuery(query, params = {}) {
1757
1761
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1758
1762
  return `?${search}`;
1759
1763
  }
1764
+ const SIGNING_METHODS = /* @__PURE__ */ new Set([
1765
+ ...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
1766
+ "EdDSA",
1767
+ "none"
1768
+ ]), BASE64_URL = /^[A-Za-z0-9_-]$/, TIMED_CLAIMS = ["exp", "iat", "nbf"], UNMODELLED_CLAIMS = ["tokenType", "guid", "s", "z", "audit", "act"];
1769
+ function parseInternalTokenKeys(pems) {
1770
+ return pems.map((pem, index) => {
1771
+ let key;
1772
+ try {
1773
+ key = createPublicKey(pem);
1774
+ } catch {
1775
+ key = void 0;
1776
+ }
1777
+ if (key?.asymmetricKeyType !== "rsa")
1778
+ throw fakeError(
1779
+ `createTestClient(): \`internalTokenKeys[${index}]\` is not an RSA public key PEM.`
1780
+ );
1781
+ return key;
1782
+ });
1783
+ }
1784
+ function isJwtShaped(token) {
1785
+ return token.split(".").length === 3;
1786
+ }
1787
+ function decodeSegment(segment) {
1788
+ const bytes = Buffer.from(segment, "utf8");
1789
+ let digits = 0;
1790
+ for (const [index, byte] of bytes.entries()) {
1791
+ const char = String.fromCharCode(byte);
1792
+ if (!(char === `
1793
+ ` || char === "\r")) {
1794
+ if (!BASE64_URL.test(char)) return `illegal base64 data at input byte ${index}`;
1795
+ digits++;
1796
+ }
1797
+ }
1798
+ return digits % 4 === 1 ? `illegal base64 data at input byte ${bytes.length - 1}` : Buffer.from(segment.replace(/[\r\n]/g, ""), "base64url");
1799
+ }
1800
+ const NUMBER_SOURCES = /* @__PURE__ */ new WeakMap();
1801
+ function jsonObject(bytes, segment) {
1802
+ let value;
1803
+ try {
1804
+ value = JSON.parse(bytes.toString("utf8"), function(key, parsed, context) {
1805
+ if (typeof parsed == "number" && context?.source !== void 0) {
1806
+ const holder = this, sources = NUMBER_SOURCES.get(holder) ?? /* @__PURE__ */ new Map();
1807
+ sources.set(key, context.source), NUMBER_SOURCES.set(holder, sources);
1808
+ }
1809
+ return parsed;
1810
+ });
1811
+ } catch {
1812
+ value = void 0;
1813
+ }
1814
+ if (typeof value != "object" || value === null || Array.isArray(value))
1815
+ throw fakeError(
1816
+ `internal token: its ${segment} is not a JSON object. Gradient answers with Go's JSON decoder error there, which the fake does not model.`
1817
+ );
1818
+ return value;
1819
+ }
1820
+ function int64Of(source) {
1821
+ const failed = (reason) => `invalid expiry: expected int64: strconv.ParseInt: parsing ${quoted(source)}: ${reason}`;
1822
+ if (!/^[+-]?[0-9]+$/.test(source)) return failed("invalid syntax");
1823
+ const value = BigInt(source);
1824
+ return value > 2n ** 63n - 1n || value < -(2n ** 63n) ? failed("value out of range") : Number(value);
1825
+ }
1826
+ function signedByAny(signed, signature, keys) {
1827
+ return keys.some((key) => {
1828
+ try {
1829
+ return verify("RSA-SHA256", Buffer.from(signed), key, signature);
1830
+ } catch {
1831
+ return !1;
1832
+ }
1833
+ });
1834
+ }
1835
+ function jwtError(token, keys) {
1836
+ const [headerSegment, claimsSegment, signatureSegment] = token.split("."), headerBytes = decodeSegment(headerSegment);
1837
+ if (typeof headerBytes == "string")
1838
+ return {
1839
+ error: token.toLowerCase().startsWith("bearer ") ? "tokenstring should not contain 'bearer '" : headerBytes
1840
+ };
1841
+ const header = jsonObject(headerBytes, "header"), claimsBytes = decodeSegment(claimsSegment);
1842
+ if (typeof claimsBytes == "string") return { error: claimsBytes };
1843
+ const claims = jsonObject(claimsBytes, "claims segment"), alg = header.alg;
1844
+ if (typeof alg != "string") return { error: "signing method (alg) is unspecified." };
1845
+ if (!SIGNING_METHODS.has(alg)) return { error: "signing method (alg) is unavailable." };
1846
+ if (alg !== "RS256") return { error: `token uses algorithm ${quoted(alg)}, expected "RS256"` };
1847
+ const signature = decodeSegment(signatureSegment);
1848
+ if (typeof signature == "string") return { error: signature };
1849
+ if (!signedByAny(`${headerSegment}.${claimsSegment}`, signature, keys))
1850
+ return { error: "crypto/rsa: verification error" };
1851
+ const timed = TIMED_CLAIMS.filter((key) => key in claims);
1852
+ if (timed.length > 0)
1853
+ throw fakeError(
1854
+ `internal token: the fake does not model jwt-go's ${timed.map((key) => `"${key}"`).join(", ")} check(s); gradient's tokens expire through "x".`
1855
+ );
1856
+ return { claims };
1857
+ }
1858
+ function identityOf(claims) {
1859
+ const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
1860
+ if (unmodelledClaims.length > 0)
1861
+ throw fakeError(
1862
+ `internal token: the fake does not model the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s); it reads "i", "g" and "x".`
1863
+ );
1864
+ const { i: id, g: grantList = [], x: rawExpiry } = claims;
1865
+ let expiresAt;
1866
+ if (rawExpiry != null) {
1867
+ if (typeof rawExpiry != "number")
1868
+ throw fakeError(
1869
+ `internal token: "x" must be a number of epoch seconds; got ${JSON.stringify(rawExpiry)}. Gradient's answer names Go's type for it, which the fake does not model.`
1870
+ );
1871
+ const parsed = int64Of(NUMBER_SOURCES.get(claims)?.get("x") ?? String(rawExpiry));
1872
+ if (typeof parsed == "string") return { refused: parsed };
1873
+ expiresAt = parsed;
1874
+ }
1875
+ if (id != null && typeof id != "string")
1876
+ return { refused: 'token field "i" must be a string' };
1877
+ let unmodelled;
1878
+ if (typeof id != "string" || id === "" ? unmodelled = `internal token: "i" is ${JSON.stringify(id)}; the fake models a token with an identity only.` : id.startsWith("g") && id !== "god" && (unmodelled = `internal token: identity "${id}" starts with "g", which gradient resolves to a project user through its claims transfer; the fake does not model that.`), !Array.isArray(grantList))
1879
+ throw fakeError(
1880
+ `internal token: "g" must be a list of { s, p } grants; got ${JSON.stringify(grantList)}.`
1881
+ );
1882
+ const grants = grantList.map((entry) => {
1883
+ const { s: path, p: permissions } = entry ?? {};
1884
+ if (typeof path != "string" || !Array.isArray(permissions) || !permissions.every((permission) => typeof permission == "string"))
1885
+ throw fakeError(
1886
+ `internal token: each grant must be { s: string, p: string[] }; got ${JSON.stringify(entry)}.`
1887
+ );
1888
+ return { path, permissions };
1889
+ }), refused = grantsError(grants);
1890
+ return refused !== void 0 ? { refused } : {
1891
+ identity: { user: { id: typeof id == "string" ? id : "" }, grants },
1892
+ expiresAt,
1893
+ ...unmodelled !== void 0 ? { unmodelled } : {}
1894
+ };
1895
+ }
1896
+ function checkInternalToken(token, keys) {
1897
+ const parsed = jwtError(token, keys);
1898
+ return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
1899
+ }
1900
+ function goTime(epochSeconds) {
1901
+ const date = new Date(epochSeconds * 1e3);
1902
+ if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
1903
+ throw fakeError(
1904
+ `internal token: "x" ${epochSeconds} is before year 1000; Go's formatting of it is not modelled.`
1905
+ );
1906
+ const iso = date.toISOString();
1907
+ return `${iso.slice(0, 10)} ${iso.slice(11, 19)} +0000 UTC`;
1908
+ }
1909
+ function internalTokenRefusal(request, check) {
1910
+ if ("refused" in check) return badRequest(request, check.refused);
1911
+ if (check.expiresAt === void 0 || Date.now() < check.expiresAt * 1e3) {
1912
+ if (check.unmodelled !== void 0) throw fakeError(check.unmodelled);
1913
+ return;
1914
+ }
1915
+ return new PlatformHttpError({
1916
+ ...request,
1917
+ statusCode: 403,
1918
+ statusMessage: "Forbidden",
1919
+ body: {
1920
+ error: {
1921
+ description: `Token has expired (at ${goTime(check.expiresAt)})`,
1922
+ type: "permissionDeniedError"
1923
+ }
1924
+ }
1925
+ });
1926
+ }
1760
1927
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1761
1928
  "fetch",
1762
1929
  "getDocument",
@@ -1964,11 +2131,16 @@ function serializeWrite(backend, run) {
1964
2131
  }
1965
2132
  ), result;
1966
2133
  }
2134
+ function internalToken(backend, token) {
2135
+ if (backend.identities.has(token) || backend.internalTokenKeys.length === 0 || !isJwtShaped(token)) return;
2136
+ let check = backend.internalTokens.get(token);
2137
+ return check === void 0 && (check = checkInternalToken(token, backend.internalTokenKeys), backend.internalTokens.set(token, check)), check;
2138
+ }
1967
2139
  function requireIdentity(backend, token, site) {
1968
- if (backend.identities.has(token)) return;
2140
+ if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
1969
2141
  const known = [...backend.identities.keys()];
1970
2142
  throw fakeError(
1971
- `${site}: unknown token "${token}" \u2014 no identity is registered for it. ` + (known.length > 0 ? `Registered tokens: ${known.map((t) => `"${t}"`).join(", ")}. ` : "No identities are registered. ") + "Register identities via createTestClient({ identities }) or client.addIdentity(token, identity)."
2143
+ `${site}: unknown token "${token}" \u2014 no identity is registered for it. ` + (known.length > 0 ? `Registered tokens: ${known.map((t) => `"${t}"`).join(", ")}. ` : "No identities are registered. ") + "Register identities via createTestClient({ identities }) or client.addIdentity(token, identity)" + (backend.internalTokenKeys.length > 0 ? ", or pass a JWT for the internal-token keys." : ", or set createTestClient({ internalTokenKeys }) to verify JWTs.")
1972
2144
  );
1973
2145
  }
1974
2146
  function rejectAmbiguousIdentity(site, config) {
@@ -2019,6 +2191,8 @@ function createTestClient(options = {}) {
2019
2191
  concurrentEdits: /* @__PURE__ */ new Map(),
2020
2192
  identities: new Map(Object.entries(options.identities ?? {})),
2021
2193
  revoked: /* @__PURE__ */ new Set(),
2194
+ internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2195
+ internalTokens: /* @__PURE__ */ new Map(),
2022
2196
  outages: /* @__PURE__ */ new Set(),
2023
2197
  writeChain: Promise.resolve()
2024
2198
  }, registry = backend.registry;
@@ -2118,7 +2292,9 @@ function makeHandle(handleArgs) {
2118
2292
  configuredPerspective
2119
2293
  } = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
2120
2294
  if (token === void 0) return accessControl;
2121
- const identity = backend.identities.get(token);
2295
+ const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
2296
+ if (verified !== void 0 && "refused" in verified)
2297
+ return { currentUser: { id: "" }, grants: [] };
2122
2298
  if (identity === void 0)
2123
2299
  throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
2124
2300
  return {
@@ -2134,18 +2310,27 @@ function makeHandle(handleArgs) {
2134
2310
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2135
2311
  return access;
2136
2312
  }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2137
- if (token === void 0) return;
2313
+ if (token === void 0 || internal() !== void 0) return;
2138
2314
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2139
2315
  const tokenProjectId = backend.identities.get(token)?.projectId;
2140
2316
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2141
2317
  throw sessionHostMismatch(request);
2318
+ }, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
2319
+ const check = internal();
2320
+ if (check === void 0) return;
2321
+ const refusal = internalTokenRefusal(request, check);
2322
+ if (refusal !== void 0) throw refusal;
2142
2323
  }, withSession = (request) => async (opts) => {
2143
2324
  const sent = rawRequest(opts);
2325
+ if (internal() !== void 0 && servedByProjectApi(sent.path))
2326
+ throw fakeError(
2327
+ `request(): "${sent.path}" with an internal token. The project API (populus) verifies internal tokens with its own key and answers differently from the Content Lake; the fake does not model that. Use a registered identity's token there.`
2328
+ );
2144
2329
  if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2145
2330
  throw projectApiDown(sent);
2146
2331
  return request(opts);
2147
2332
  }, admitToLake = (request) => {
2148
- refuseSession(request);
2333
+ refuseSession(request), refuseInternalToken(request);
2149
2334
  const access = activeAccess();
2150
2335
  if (access === void 0) return;
2151
2336
  const refusal = refusedToken(request, access.grants);
@@ -2627,6 +2812,7 @@ function makeHandle(handleArgs) {
2627
2812
  listIdentities: members,
2628
2813
  platform: {
2629
2814
  projectId,
2815
+ apiVersion,
2630
2816
  organizationId: backend.organizationId,
2631
2817
  projectFeatures: backend.projectFeatures,
2632
2818
  own: (asked) => registryKey(asked) === registryKey(target) ? {
@@ -2708,6 +2894,10 @@ function makeHandle(handleArgs) {
2708
2894
  },
2709
2895
  identities: () => Object.fromEntries(backend.identities),
2710
2896
  revokeIdentity: (revokedToken) => {
2897
+ if (!backend.identities.has(revokedToken) && internalToken(backend, revokedToken) !== void 0)
2898
+ throw fakeError(
2899
+ "revokeIdentity(): an internal token has no session to revoke; mint one whose `x` has passed to get the Content Lake's expired-token answer."
2900
+ );
2711
2901
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2712
2902
  },
2713
2903
  simulateOutage: (component) => {