@sanity-labs/client-fake-for-test 0.23.0 → 0.24.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/README.md CHANGED
@@ -174,6 +174,34 @@ The refusal is the platform's answer, probed on staging and production, raised a
174
174
 
175
175
  The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
176
176
 
177
+ #### Internal tokens
178
+
179
+ A Sanity service can mint its own token: an RS256 JWT whose claims are `i` (the identity), `g` (grants as `{ s: path, p: permissions }`) and `x` (expiry, epoch seconds). The Content Lake verifies it against its public key instead of looking up a session. Give the fake that public key, and a test can hand it the token the code under test really mints:
180
+
181
+ ```ts
182
+ const client = createTestClient({
183
+ documents,
184
+ internalTokenKeys: [publicKeyPem], // RSA public key PEMs; shared by the whole withConfig family
185
+ });
186
+ const service = client.withConfig({ token: mintedJwt });
187
+ ```
188
+
189
+ A bearer that is not a registered identity, has a JWT's three segments and verifies against any of the keys acts as `{ user: { id: i }, grants: g }`. Each `{ s, p }` grant is the path grant `{ path: s, permissions: p }`, read and refused exactly as in [Token grants](#token-grants-filters-and-paths). The header's `kid` is not read: gradient holds one key. A token without `x` does not expire.
190
+
191
+ The Content Lake refuses the token on every request it serves (queries, documents, mutations, actions, the History API), as gradient does (`pkg/server/httpapi/middlewares/sessions/session.go`), each as a `PlatformHttpError`:
192
+
193
+ | Token | Answer |
194
+ | --- | --- |
195
+ | Signed by another key | 400 `{ error: { type: "httpBadRequest", description: 'invalid JWT token "<token>": crypto/rsa: verification error' } }` |
196
+ | `alg` other than `RS256` | 400, `invalid JWT token "<token>": token uses algorithm "<alg>", expected "RS256"` |
197
+ | A segment that is not base64url | 400, `invalid JWT token "<token>": illegal base64 data at input byte <n>` |
198
+ | A grant the Content Lake cannot parse | 400, the grant's own `description` (no `invalid JWT token` prefix) |
199
+ | `x` that is not an int64 (`1.0`, `4.1e9`, over 2^63 - 1) | 400, `invalid expiry: expected int64: strconv.ParseInt: parsing "<x>": <reason>` (`invalid syntax` / `value out of range`) |
200
+ | `i` that is not a string | 400, `token field "i" must be a string` |
201
+ | `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
202
+
203
+ A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake does not model that, so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. Claims the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`, `exp`, `iat`, `nbf`, or a claims segment that is not a JSON object) throw a fake error instead of a guessed answer. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
204
+
177
205
  #### Platform outages
178
206
 
179
207
  `client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
@@ -365,6 +393,7 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
365
393
  | `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
366
394
  | `client.identities()` | Snapshot of the registered token→identity entries |
367
395
  | `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
396
+ | `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
368
397
  | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
369
398
  | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
370
399
  | `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var groqJs = require("groq-js"), client = require("@sanity/client");
3
+ var groqJs = require("groq-js"), client = require("@sanity/client"), node_crypto = require("node:crypto");
4
4
  const ERR_PREFIX = "[client-fake-for-test]";
5
5
  function fakeError(message) {
6
6
  return new Error(`${ERR_PREFIX} ${message}`);
@@ -411,13 +411,15 @@ function grantsError(grants) {
411
411
  }
412
412
  function refusedToken(request, grants) {
413
413
  const description = grantsError(grants);
414
- if (description !== void 0)
415
- return new PlatformHttpError({
416
- ...request,
417
- statusCode: 400,
418
- statusMessage: "Bad Request",
419
- body: { error: { description, type: "httpBadRequest" } }
420
- });
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
+ });
421
423
  }
422
424
  function createDocumentHistory() {
423
425
  const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
@@ -1758,6 +1760,169 @@ function encodeGroqQuery(query, params = {}) {
1758
1760
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1759
1761
  return `?${search}`;
1760
1762
  }
1763
+ const SIGNING_METHODS = /* @__PURE__ */ new Set([
1764
+ ...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
1765
+ "EdDSA",
1766
+ "none"
1767
+ ]), BASE64_URL = /^[A-Za-z0-9_-]$/, TIMED_CLAIMS = ["exp", "iat", "nbf"], UNMODELLED_CLAIMS = ["tokenType", "guid", "s", "z", "audit", "act"];
1768
+ function parseInternalTokenKeys(pems) {
1769
+ return pems.map((pem, index) => {
1770
+ let key;
1771
+ try {
1772
+ key = node_crypto.createPublicKey(pem);
1773
+ } catch {
1774
+ key = void 0;
1775
+ }
1776
+ if (key?.asymmetricKeyType !== "rsa")
1777
+ throw fakeError(
1778
+ `createTestClient(): \`internalTokenKeys[${index}]\` is not an RSA public key PEM.`
1779
+ );
1780
+ return key;
1781
+ });
1782
+ }
1783
+ function isJwtShaped(token) {
1784
+ return token.split(".").length === 3;
1785
+ }
1786
+ function decodeSegment(segment) {
1787
+ const bytes = Buffer.from(segment, "utf8");
1788
+ let digits = 0;
1789
+ for (const [index, byte] of bytes.entries()) {
1790
+ const char = String.fromCharCode(byte);
1791
+ if (!(char === `
1792
+ ` || char === "\r")) {
1793
+ if (!BASE64_URL.test(char)) return `illegal base64 data at input byte ${index}`;
1794
+ digits++;
1795
+ }
1796
+ }
1797
+ return digits % 4 === 1 ? `illegal base64 data at input byte ${bytes.length - 1}` : Buffer.from(segment.replace(/[\r\n]/g, ""), "base64url");
1798
+ }
1799
+ const NUMBER_SOURCES = /* @__PURE__ */ new WeakMap();
1800
+ function jsonObject(bytes, segment) {
1801
+ let value;
1802
+ try {
1803
+ value = JSON.parse(bytes.toString("utf8"), function(key, parsed, context) {
1804
+ if (typeof parsed == "number" && context?.source !== void 0) {
1805
+ const holder = this, sources = NUMBER_SOURCES.get(holder) ?? /* @__PURE__ */ new Map();
1806
+ sources.set(key, context.source), NUMBER_SOURCES.set(holder, sources);
1807
+ }
1808
+ return parsed;
1809
+ });
1810
+ } catch {
1811
+ value = void 0;
1812
+ }
1813
+ if (typeof value != "object" || value === null || Array.isArray(value))
1814
+ throw fakeError(
1815
+ `internal token: its ${segment} is not a JSON object. Gradient answers with Go's JSON decoder error there, which the fake does not model.`
1816
+ );
1817
+ return value;
1818
+ }
1819
+ function int64Of(source) {
1820
+ const failed = (reason) => `invalid expiry: expected int64: strconv.ParseInt: parsing ${quoted(source)}: ${reason}`;
1821
+ if (!/^[+-]?[0-9]+$/.test(source)) return failed("invalid syntax");
1822
+ const value = BigInt(source);
1823
+ return value > 2n ** 63n - 1n || value < -(2n ** 63n) ? failed("value out of range") : Number(value);
1824
+ }
1825
+ function signedByAny(signed, signature, keys) {
1826
+ return keys.some((key) => {
1827
+ try {
1828
+ return node_crypto.verify("RSA-SHA256", Buffer.from(signed), key, signature);
1829
+ } catch {
1830
+ return !1;
1831
+ }
1832
+ });
1833
+ }
1834
+ function jwtError(token, keys) {
1835
+ const [headerSegment, claimsSegment, signatureSegment] = token.split("."), headerBytes = decodeSegment(headerSegment);
1836
+ if (typeof headerBytes == "string")
1837
+ return {
1838
+ error: token.toLowerCase().startsWith("bearer ") ? "tokenstring should not contain 'bearer '" : headerBytes
1839
+ };
1840
+ const header = jsonObject(headerBytes, "header"), claimsBytes = decodeSegment(claimsSegment);
1841
+ if (typeof claimsBytes == "string") return { error: claimsBytes };
1842
+ const claims = jsonObject(claimsBytes, "claims segment"), alg = header.alg;
1843
+ if (typeof alg != "string") return { error: "signing method (alg) is unspecified." };
1844
+ if (!SIGNING_METHODS.has(alg)) return { error: "signing method (alg) is unavailable." };
1845
+ if (alg !== "RS256") return { error: `token uses algorithm ${quoted(alg)}, expected "RS256"` };
1846
+ const signature = decodeSegment(signatureSegment);
1847
+ if (typeof signature == "string") return { error: signature };
1848
+ if (!signedByAny(`${headerSegment}.${claimsSegment}`, signature, keys))
1849
+ return { error: "crypto/rsa: verification error" };
1850
+ const timed = TIMED_CLAIMS.filter((key) => key in claims);
1851
+ if (timed.length > 0)
1852
+ throw fakeError(
1853
+ `internal token: the fake does not model jwt-go's ${timed.map((key) => `"${key}"`).join(", ")} check(s); gradient's tokens expire through "x".`
1854
+ );
1855
+ return { claims };
1856
+ }
1857
+ function identityOf(claims) {
1858
+ const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
1859
+ if (unmodelledClaims.length > 0)
1860
+ throw fakeError(
1861
+ `internal token: the fake does not model the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s); it reads "i", "g" and "x".`
1862
+ );
1863
+ const { i: id, g: grantList = [], x: rawExpiry } = claims;
1864
+ let expiresAt;
1865
+ if (rawExpiry != null) {
1866
+ if (typeof rawExpiry != "number")
1867
+ throw fakeError(
1868
+ `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.`
1869
+ );
1870
+ const parsed = int64Of(NUMBER_SOURCES.get(claims)?.get("x") ?? String(rawExpiry));
1871
+ if (typeof parsed == "string") return { refused: parsed };
1872
+ expiresAt = parsed;
1873
+ }
1874
+ if (id != null && typeof id != "string")
1875
+ return { refused: 'token field "i" must be a string' };
1876
+ let unmodelled;
1877
+ 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))
1878
+ throw fakeError(
1879
+ `internal token: "g" must be a list of { s, p } grants; got ${JSON.stringify(grantList)}.`
1880
+ );
1881
+ const grants = grantList.map((entry) => {
1882
+ const { s: path, p: permissions } = entry ?? {};
1883
+ if (typeof path != "string" || !Array.isArray(permissions) || !permissions.every((permission) => typeof permission == "string"))
1884
+ throw fakeError(
1885
+ `internal token: each grant must be { s: string, p: string[] }; got ${JSON.stringify(entry)}.`
1886
+ );
1887
+ return { path, permissions };
1888
+ }), refused = grantsError(grants);
1889
+ return refused !== void 0 ? { refused } : {
1890
+ identity: { user: { id: typeof id == "string" ? id : "" }, grants },
1891
+ expiresAt,
1892
+ ...unmodelled !== void 0 ? { unmodelled } : {}
1893
+ };
1894
+ }
1895
+ function checkInternalToken(token, keys) {
1896
+ const parsed = jwtError(token, keys);
1897
+ return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
1898
+ }
1899
+ function goTime(epochSeconds) {
1900
+ const date = new Date(epochSeconds * 1e3);
1901
+ if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
1902
+ throw fakeError(
1903
+ `internal token: "x" ${epochSeconds} is before year 1000; Go's formatting of it is not modelled.`
1904
+ );
1905
+ const iso = date.toISOString();
1906
+ return `${iso.slice(0, 10)} ${iso.slice(11, 19)} +0000 UTC`;
1907
+ }
1908
+ function internalTokenRefusal(request, check) {
1909
+ if ("refused" in check) return badRequest(request, check.refused);
1910
+ if (check.expiresAt === void 0 || Date.now() < check.expiresAt * 1e3) {
1911
+ if (check.unmodelled !== void 0) throw fakeError(check.unmodelled);
1912
+ return;
1913
+ }
1914
+ return new PlatformHttpError({
1915
+ ...request,
1916
+ statusCode: 403,
1917
+ statusMessage: "Forbidden",
1918
+ body: {
1919
+ error: {
1920
+ description: `Token has expired (at ${goTime(check.expiresAt)})`,
1921
+ type: "permissionDeniedError"
1922
+ }
1923
+ }
1924
+ });
1925
+ }
1761
1926
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1762
1927
  "fetch",
1763
1928
  "getDocument",
@@ -1965,11 +2130,16 @@ function serializeWrite(backend, run) {
1965
2130
  }
1966
2131
  ), result;
1967
2132
  }
2133
+ function internalToken(backend, token) {
2134
+ if (backend.identities.has(token) || backend.internalTokenKeys.length === 0 || !isJwtShaped(token)) return;
2135
+ let check = backend.internalTokens.get(token);
2136
+ return check === void 0 && (check = checkInternalToken(token, backend.internalTokenKeys), backend.internalTokens.set(token, check)), check;
2137
+ }
1968
2138
  function requireIdentity(backend, token, site) {
1969
- if (backend.identities.has(token)) return;
2139
+ if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
1970
2140
  const known = [...backend.identities.keys()];
1971
2141
  throw fakeError(
1972
- `${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)."
2142
+ `${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.")
1973
2143
  );
1974
2144
  }
1975
2145
  function rejectAmbiguousIdentity(site, config) {
@@ -2020,6 +2190,8 @@ function createTestClient(options = {}) {
2020
2190
  concurrentEdits: /* @__PURE__ */ new Map(),
2021
2191
  identities: new Map(Object.entries(options.identities ?? {})),
2022
2192
  revoked: /* @__PURE__ */ new Set(),
2193
+ internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2194
+ internalTokens: /* @__PURE__ */ new Map(),
2023
2195
  outages: /* @__PURE__ */ new Set(),
2024
2196
  writeChain: Promise.resolve()
2025
2197
  }, registry = backend.registry;
@@ -2119,7 +2291,9 @@ function makeHandle(handleArgs) {
2119
2291
  configuredPerspective
2120
2292
  } = 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 = () => {
2121
2293
  if (token === void 0) return accessControl;
2122
- const identity = backend.identities.get(token);
2294
+ const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
2295
+ if (verified !== void 0 && "refused" in verified)
2296
+ return { currentUser: { id: "" }, grants: [] };
2123
2297
  if (identity === void 0)
2124
2298
  throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
2125
2299
  return {
@@ -2135,18 +2309,27 @@ function makeHandle(handleArgs) {
2135
2309
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2136
2310
  return access;
2137
2311
  }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2138
- if (token === void 0) return;
2312
+ if (token === void 0 || internal() !== void 0) return;
2139
2313
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2140
2314
  const tokenProjectId = backend.identities.get(token)?.projectId;
2141
2315
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2142
2316
  throw sessionHostMismatch(request);
2317
+ }, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
2318
+ const check = internal();
2319
+ if (check === void 0) return;
2320
+ const refusal = internalTokenRefusal(request, check);
2321
+ if (refusal !== void 0) throw refusal;
2143
2322
  }, withSession = (request) => async (opts) => {
2144
2323
  const sent = rawRequest(opts);
2324
+ if (internal() !== void 0 && servedByProjectApi(sent.path))
2325
+ throw fakeError(
2326
+ `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.`
2327
+ );
2145
2328
  if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2146
2329
  throw projectApiDown(sent);
2147
2330
  return request(opts);
2148
2331
  }, admitToLake = (request) => {
2149
- refuseSession(request);
2332
+ refuseSession(request), refuseInternalToken(request);
2150
2333
  const access = activeAccess();
2151
2334
  if (access === void 0) return;
2152
2335
  const refusal = refusedToken(request, access.grants);
@@ -2709,6 +2892,10 @@ function makeHandle(handleArgs) {
2709
2892
  },
2710
2893
  identities: () => Object.fromEntries(backend.identities),
2711
2894
  revokeIdentity: (revokedToken) => {
2895
+ if (!backend.identities.has(revokedToken) && internalToken(backend, revokedToken) !== void 0)
2896
+ throw fakeError(
2897
+ "revokeIdentity(): an internal token has no session to revoke; mint one whose `x` has passed to get the Content Lake's expired-token answer."
2898
+ );
2712
2899
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2713
2900
  },
2714
2901
  simulateOutage: (component) => {