@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/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();
@@ -1757,6 +1760,169 @@ function encodeGroqQuery(query, params = {}) {
1757
1760
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1758
1761
  return `?${search}`;
1759
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 = 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 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
+ }
1760
1926
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1761
1927
  "fetch",
1762
1928
  "getDocument",
@@ -1964,11 +2130,16 @@ function serializeWrite(backend, run) {
1964
2130
  }
1965
2131
  ), result;
1966
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
+ }
1967
2138
  function requireIdentity(backend, token, site) {
1968
- if (backend.identities.has(token)) return;
2139
+ if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
1969
2140
  const known = [...backend.identities.keys()];
1970
2141
  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)."
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.")
1972
2143
  );
1973
2144
  }
1974
2145
  function rejectAmbiguousIdentity(site, config) {
@@ -2019,6 +2190,8 @@ function createTestClient(options = {}) {
2019
2190
  concurrentEdits: /* @__PURE__ */ new Map(),
2020
2191
  identities: new Map(Object.entries(options.identities ?? {})),
2021
2192
  revoked: /* @__PURE__ */ new Set(),
2193
+ internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2194
+ internalTokens: /* @__PURE__ */ new Map(),
2022
2195
  outages: /* @__PURE__ */ new Set(),
2023
2196
  writeChain: Promise.resolve()
2024
2197
  }, registry = backend.registry;
@@ -2118,7 +2291,9 @@ function makeHandle(handleArgs) {
2118
2291
  configuredPerspective
2119
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 = () => {
2120
2293
  if (token === void 0) return accessControl;
2121
- 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: [] };
2122
2297
  if (identity === void 0)
2123
2298
  throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
2124
2299
  return {
@@ -2134,18 +2309,27 @@ function makeHandle(handleArgs) {
2134
2309
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2135
2310
  return access;
2136
2311
  }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2137
- if (token === void 0) return;
2312
+ if (token === void 0 || internal() !== void 0) return;
2138
2313
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2139
2314
  const tokenProjectId = backend.identities.get(token)?.projectId;
2140
2315
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2141
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;
2142
2322
  }, withSession = (request) => async (opts) => {
2143
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
+ );
2144
2328
  if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2145
2329
  throw projectApiDown(sent);
2146
2330
  return request(opts);
2147
2331
  }, admitToLake = (request) => {
2148
- refuseSession(request);
2332
+ refuseSession(request), refuseInternalToken(request);
2149
2333
  const access = activeAccess();
2150
2334
  if (access === void 0) return;
2151
2335
  const refusal = refusedToken(request, access.grants);
@@ -2708,6 +2892,10 @@ function makeHandle(handleArgs) {
2708
2892
  },
2709
2893
  identities: () => Object.fromEntries(backend.identities),
2710
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
+ );
2711
2899
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2712
2900
  },
2713
2901
  simulateOutage: (component) => {