@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/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:
@@ -313,7 +341,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
313
341
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
314
342
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
315
343
 
316
- - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
344
+ - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. Populus mounts the Access API from API version `2025-07-11`, so a handle on an earlier `apiVersion`, the default `"1"` included, gets the 404 Express answers for a route that is not mounted (`Cannot GET /access/…`), as on the platform; `X` reaches it. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
317
345
  - **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
318
346
  - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
319
347
  - **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
@@ -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();
@@ -480,7 +482,7 @@ function createDocumentHistory() {
480
482
  function historyIds(list) {
481
483
  return list.split(",").map((id) => decodeURIComponent(id));
482
484
  }
483
- 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 = [
484
486
  /^\/users\/me$/,
485
487
  /^\/projects\/[^/]+$/,
486
488
  /^\/projects\/[^/]+\/users\/[^/]+$/,
@@ -523,6 +525,7 @@ async function servePlatformRequest(ctx, uri, request) {
523
525
  }
524
526
  const access = path.match(ACCESS_PATH);
525
527
  if (access !== null) {
528
+ if (ctx.apiVersion < ACCESS_API_SINCE) throw notMounted(request);
526
529
  const [, type, id, rest2] = access;
527
530
  return serveAccess({ ctx, request, type, id: decodeURIComponent(id), rest: rest2 ?? "", query });
528
531
  }
@@ -1758,6 +1761,169 @@ function encodeGroqQuery(query, params = {}) {
1758
1761
  value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
1759
1762
  return `?${search}`;
1760
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 = node_crypto.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 node_crypto.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
+ }
1761
1927
  const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
1762
1928
  "fetch",
1763
1929
  "getDocument",
@@ -1965,11 +2131,16 @@ function serializeWrite(backend, run) {
1965
2131
  }
1966
2132
  ), result;
1967
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
+ }
1968
2139
  function requireIdentity(backend, token, site) {
1969
- if (backend.identities.has(token)) return;
2140
+ if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
1970
2141
  const known = [...backend.identities.keys()];
1971
2142
  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)."
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.")
1973
2144
  );
1974
2145
  }
1975
2146
  function rejectAmbiguousIdentity(site, config) {
@@ -2020,6 +2191,8 @@ function createTestClient(options = {}) {
2020
2191
  concurrentEdits: /* @__PURE__ */ new Map(),
2021
2192
  identities: new Map(Object.entries(options.identities ?? {})),
2022
2193
  revoked: /* @__PURE__ */ new Set(),
2194
+ internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2195
+ internalTokens: /* @__PURE__ */ new Map(),
2023
2196
  outages: /* @__PURE__ */ new Set(),
2024
2197
  writeChain: Promise.resolve()
2025
2198
  }, registry = backend.registry;
@@ -2119,7 +2292,9 @@ function makeHandle(handleArgs) {
2119
2292
  configuredPerspective
2120
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 = () => {
2121
2294
  if (token === void 0) return accessControl;
2122
- 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: [] };
2123
2298
  if (identity === void 0)
2124
2299
  throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
2125
2300
  return {
@@ -2135,18 +2310,27 @@ function makeHandle(handleArgs) {
2135
2310
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
2136
2311
  return access;
2137
2312
  }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2138
- if (token === void 0) return;
2313
+ if (token === void 0 || internal() !== void 0) return;
2139
2314
  if (backend.revoked.has(token)) throw sessionNotFound(request);
2140
2315
  const tokenProjectId = backend.identities.get(token)?.projectId;
2141
2316
  if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2142
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;
2143
2323
  }, withSession = (request) => async (opts) => {
2144
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
+ );
2145
2329
  if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
2146
2330
  throw projectApiDown(sent);
2147
2331
  return request(opts);
2148
2332
  }, admitToLake = (request) => {
2149
- refuseSession(request);
2333
+ refuseSession(request), refuseInternalToken(request);
2150
2334
  const access = activeAccess();
2151
2335
  if (access === void 0) return;
2152
2336
  const refusal = refusedToken(request, access.grants);
@@ -2628,6 +2812,7 @@ function makeHandle(handleArgs) {
2628
2812
  listIdentities: members,
2629
2813
  platform: {
2630
2814
  projectId,
2815
+ apiVersion,
2631
2816
  organizationId: backend.organizationId,
2632
2817
  projectFeatures: backend.projectFeatures,
2633
2818
  own: (asked) => registryKey(asked) === registryKey(target) ? {
@@ -2709,6 +2894,10 @@ function makeHandle(handleArgs) {
2709
2894
  },
2710
2895
  identities: () => Object.fromEntries(backend.identities),
2711
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
+ );
2712
2901
  requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2713
2902
  },
2714
2903
  simulateOutage: (component) => {