@sanity-labs/client-fake-for-test 0.22.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 +52 -0
- package/dist/index.cjs +246 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -1
- package/dist/index.d.ts +38 -1
- package/dist/index.js +247 -16
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClientError } from "@sanity/client";
|
|
2
|
+
import { ServerError } from "@sanity/client";
|
|
2
3
|
|
|
3
4
|
export declare type Action = ReleaseAction | VersionAction | DocumentAction;
|
|
4
5
|
|
|
@@ -182,9 +183,23 @@ export declare interface CreateTestClientOptions {
|
|
|
182
183
|
* more identities later with `addIdentity`.
|
|
183
184
|
*/
|
|
184
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[];
|
|
185
199
|
/**
|
|
186
200
|
* Token the root handle is bound to — must name an entry in
|
|
187
|
-
* `identities` (unknown tokens throw)
|
|
201
|
+
* `identities` (unknown tokens throw), or be a JWT when
|
|
202
|
+
* `internalTokenKeys` is set. Omit to leave the root handle
|
|
188
203
|
* identity-free (a bare factory for token-bound siblings): its
|
|
189
204
|
* `request` is undefined and its reads/writes are ungated. Mutually
|
|
190
205
|
* exclusive with `accessControl`.
|
|
@@ -738,6 +753,9 @@ export declare type Perspective =
|
|
|
738
753
|
| (string & {})
|
|
739
754
|
| string[];
|
|
740
755
|
|
|
756
|
+
/** A platform component {@link TestClient.simulateOutage} can take down: `"project-api"` is populus. */
|
|
757
|
+
export declare type PlatformComponent = "project-api";
|
|
758
|
+
|
|
741
759
|
/**
|
|
742
760
|
* The platform's refusal, as the `ClientError` `@sanity/client` throws for
|
|
743
761
|
* the same response: the fake hands `ClientError` the response the client
|
|
@@ -772,6 +790,15 @@ declare interface PlatformResponseArgs {
|
|
|
772
790
|
body: unknown;
|
|
773
791
|
}
|
|
774
792
|
|
|
793
|
+
/**
|
|
794
|
+
* The platform's 5xx answer, as the `ServerError` `@sanity/client` throws
|
|
795
|
+
* for a status of 500 or more (`src/http/request.ts`); see
|
|
796
|
+
* {@link PlatformHttpError} for how the fields are derived.
|
|
797
|
+
*/
|
|
798
|
+
export declare class PlatformServerError extends ServerError {
|
|
799
|
+
constructor(args: PlatformResponseArgs);
|
|
800
|
+
}
|
|
801
|
+
|
|
775
802
|
/** One row of the `/projects/<projectId>` members response. */
|
|
776
803
|
export declare interface ProjectMemberRecord {
|
|
777
804
|
id: string;
|
|
@@ -1245,6 +1272,16 @@ export declare interface TestClient {
|
|
|
1245
1272
|
* tokens throw.
|
|
1246
1273
|
*/
|
|
1247
1274
|
revokeIdentity: (token: string) => void;
|
|
1275
|
+
/**
|
|
1276
|
+
* Take a platform component down, as in an outage: from the next request
|
|
1277
|
+
* on, every request it serves, on every handle of the family (siblings
|
|
1278
|
+
* made before and after the call), throws its 5xx answer. `"project-api"`
|
|
1279
|
+
* is populus: `request()` of `/users/me`, the project, organization and
|
|
1280
|
+
* Access APIs, resource lookup and ACLs throws {@link PlatformServerError}
|
|
1281
|
+
* 500. The Content Lake (queries, documents, mutations, actions, history)
|
|
1282
|
+
* keeps answering. The outage lasts for the rest of the family's life.
|
|
1283
|
+
*/
|
|
1284
|
+
simulateOutage: (component: PlatformComponent) => void;
|
|
1248
1285
|
/**
|
|
1249
1286
|
* Every mutation committed through this client's registry, flattened
|
|
1250
1287
|
* and in order — `create` / `createOrReplace` / `createIfNotExists` /
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ClientError } from "@sanity/client";
|
|
2
|
+
import { ServerError } from "@sanity/client";
|
|
2
3
|
|
|
3
4
|
export declare type Action = ReleaseAction | VersionAction | DocumentAction;
|
|
4
5
|
|
|
@@ -182,9 +183,23 @@ export declare interface CreateTestClientOptions {
|
|
|
182
183
|
* more identities later with `addIdentity`.
|
|
183
184
|
*/
|
|
184
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[];
|
|
185
199
|
/**
|
|
186
200
|
* Token the root handle is bound to — must name an entry in
|
|
187
|
-
* `identities` (unknown tokens throw)
|
|
201
|
+
* `identities` (unknown tokens throw), or be a JWT when
|
|
202
|
+
* `internalTokenKeys` is set. Omit to leave the root handle
|
|
188
203
|
* identity-free (a bare factory for token-bound siblings): its
|
|
189
204
|
* `request` is undefined and its reads/writes are ungated. Mutually
|
|
190
205
|
* exclusive with `accessControl`.
|
|
@@ -738,6 +753,9 @@ export declare type Perspective =
|
|
|
738
753
|
| (string & {})
|
|
739
754
|
| string[];
|
|
740
755
|
|
|
756
|
+
/** A platform component {@link TestClient.simulateOutage} can take down: `"project-api"` is populus. */
|
|
757
|
+
export declare type PlatformComponent = "project-api";
|
|
758
|
+
|
|
741
759
|
/**
|
|
742
760
|
* The platform's refusal, as the `ClientError` `@sanity/client` throws for
|
|
743
761
|
* the same response: the fake hands `ClientError` the response the client
|
|
@@ -772,6 +790,15 @@ declare interface PlatformResponseArgs {
|
|
|
772
790
|
body: unknown;
|
|
773
791
|
}
|
|
774
792
|
|
|
793
|
+
/**
|
|
794
|
+
* The platform's 5xx answer, as the `ServerError` `@sanity/client` throws
|
|
795
|
+
* for a status of 500 or more (`src/http/request.ts`); see
|
|
796
|
+
* {@link PlatformHttpError} for how the fields are derived.
|
|
797
|
+
*/
|
|
798
|
+
export declare class PlatformServerError extends ServerError {
|
|
799
|
+
constructor(args: PlatformResponseArgs);
|
|
800
|
+
}
|
|
801
|
+
|
|
775
802
|
/** One row of the `/projects/<projectId>` members response. */
|
|
776
803
|
export declare interface ProjectMemberRecord {
|
|
777
804
|
id: string;
|
|
@@ -1245,6 +1272,16 @@ export declare interface TestClient {
|
|
|
1245
1272
|
* tokens throw.
|
|
1246
1273
|
*/
|
|
1247
1274
|
revokeIdentity: (token: string) => void;
|
|
1275
|
+
/**
|
|
1276
|
+
* Take a platform component down, as in an outage: from the next request
|
|
1277
|
+
* on, every request it serves, on every handle of the family (siblings
|
|
1278
|
+
* made before and after the call), throws its 5xx answer. `"project-api"`
|
|
1279
|
+
* is populus: `request()` of `/users/me`, the project, organization and
|
|
1280
|
+
* Access APIs, resource lookup and ACLs throws {@link PlatformServerError}
|
|
1281
|
+
* 500. The Content Lake (queries, documents, mutations, actions, history)
|
|
1282
|
+
* keeps answering. The outage lasts for the rest of the family's life.
|
|
1283
|
+
*/
|
|
1284
|
+
simulateOutage: (component: PlatformComponent) => void;
|
|
1248
1285
|
/**
|
|
1249
1286
|
* Every mutation committed through this client's registry, flattened
|
|
1250
1287
|
* and in order — `create` / `createOrReplace` / `createIfNotExists` /
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parse, evaluate } from "groq-js";
|
|
2
|
-
import { ClientError } from "@sanity/client";
|
|
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}`);
|
|
@@ -9,6 +10,11 @@ class PlatformHttpError extends ClientError {
|
|
|
9
10
|
super(platformResponse(args)), this.name = "PlatformHttpError";
|
|
10
11
|
}
|
|
11
12
|
}
|
|
13
|
+
class PlatformServerError extends ServerError {
|
|
14
|
+
constructor(args) {
|
|
15
|
+
super(platformResponse(args)), this.name = "PlatformServerError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
12
18
|
function platformResponse(args) {
|
|
13
19
|
const { method, url, statusCode, statusMessage, body } = args;
|
|
14
20
|
return {
|
|
@@ -79,7 +85,20 @@ const sessionNotFound = (request) => new PlatformHttpError({
|
|
|
79
85
|
statusCode: 401,
|
|
80
86
|
statusMessage: "Unauthorized",
|
|
81
87
|
message: "User must be a member of this project to perform this operation"
|
|
82
|
-
})
|
|
88
|
+
});
|
|
89
|
+
function projectApiDown(request) {
|
|
90
|
+
return new PlatformServerError({
|
|
91
|
+
...request,
|
|
92
|
+
statusCode: 500,
|
|
93
|
+
statusMessage: "Internal Server Error",
|
|
94
|
+
body: {
|
|
95
|
+
statusCode: 500,
|
|
96
|
+
error: "Internal Server Error",
|
|
97
|
+
message: "An internal server error occurred"
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
const mediaLibraryReadRequired = (request) => accessApiError({
|
|
83
102
|
request,
|
|
84
103
|
statusCode: 401,
|
|
85
104
|
statusMessage: "Unauthorized",
|
|
@@ -392,13 +411,15 @@ function grantsError(grants) {
|
|
|
392
411
|
}
|
|
393
412
|
function refusedToken(request, grants) {
|
|
394
413
|
const description = grantsError(grants);
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
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
|
+
});
|
|
402
423
|
}
|
|
403
424
|
function createDocumentHistory() {
|
|
404
425
|
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
@@ -461,7 +482,22 @@ function createDocumentHistory() {
|
|
|
461
482
|
function historyIds(list) {
|
|
462
483
|
return list.split(",").map((id) => decodeURIComponent(id));
|
|
463
484
|
}
|
|
464
|
-
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\/([^/]+)(\/.*)
|
|
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\/([^/]+)(\/.*)$/, PROJECT_API_PATHS = [
|
|
486
|
+
/^\/users\/me$/,
|
|
487
|
+
/^\/projects\/[^/]+$/,
|
|
488
|
+
/^\/projects\/[^/]+\/users\/[^/]+$/,
|
|
489
|
+
PROJECT_ROLES_PATH,
|
|
490
|
+
PROJECT_FEATURES_PATH,
|
|
491
|
+
MY_ATTRIBUTES_PATH,
|
|
492
|
+
ACCESS_PATH
|
|
493
|
+
];
|
|
494
|
+
function servedByProjectApi(path) {
|
|
495
|
+
if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
|
|
496
|
+
const matched = matchResourcePath(path);
|
|
497
|
+
if (matched === void 0) return !1;
|
|
498
|
+
const row = capabilitiesOf(matched.resource.type);
|
|
499
|
+
return matched.rest === "" ? row.lookupAtBase : matched.rest === "/acl" && row.acl === "served";
|
|
500
|
+
}
|
|
465
501
|
function page(data) {
|
|
466
502
|
return { data, nextCursor: null };
|
|
467
503
|
}
|
|
@@ -1724,6 +1760,169 @@ function encodeGroqQuery(query, params = {}) {
|
|
|
1724
1760
|
value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
|
|
1725
1761
|
return `?${search}`;
|
|
1726
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
|
+
}
|
|
1727
1926
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
1728
1927
|
"fetch",
|
|
1729
1928
|
"getDocument",
|
|
@@ -1931,11 +2130,16 @@ function serializeWrite(backend, run) {
|
|
|
1931
2130
|
}
|
|
1932
2131
|
), result;
|
|
1933
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
|
+
}
|
|
1934
2138
|
function requireIdentity(backend, token, site) {
|
|
1935
|
-
if (backend.identities.has(token)) return;
|
|
2139
|
+
if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
|
|
1936
2140
|
const known = [...backend.identities.keys()];
|
|
1937
2141
|
throw fakeError(
|
|
1938
|
-
`${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.")
|
|
1939
2143
|
);
|
|
1940
2144
|
}
|
|
1941
2145
|
function rejectAmbiguousIdentity(site, config) {
|
|
@@ -1986,6 +2190,9 @@ function createTestClient(options = {}) {
|
|
|
1986
2190
|
concurrentEdits: /* @__PURE__ */ new Map(),
|
|
1987
2191
|
identities: new Map(Object.entries(options.identities ?? {})),
|
|
1988
2192
|
revoked: /* @__PURE__ */ new Set(),
|
|
2193
|
+
internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
|
|
2194
|
+
internalTokens: /* @__PURE__ */ new Map(),
|
|
2195
|
+
outages: /* @__PURE__ */ new Set(),
|
|
1989
2196
|
writeChain: Promise.resolve()
|
|
1990
2197
|
}, registry = backend.registry;
|
|
1991
2198
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -2084,7 +2291,9 @@ function makeHandle(handleArgs) {
|
|
|
2084
2291
|
configuredPerspective
|
|
2085
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 = () => {
|
|
2086
2293
|
if (token === void 0) return accessControl;
|
|
2087
|
-
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: [] };
|
|
2088
2297
|
if (identity === void 0)
|
|
2089
2298
|
throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
|
|
2090
2299
|
return {
|
|
@@ -2100,13 +2309,27 @@ function makeHandle(handleArgs) {
|
|
|
2100
2309
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
2101
2310
|
return access;
|
|
2102
2311
|
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2103
|
-
if (token === void 0) return;
|
|
2312
|
+
if (token === void 0 || internal() !== void 0) return;
|
|
2104
2313
|
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2105
2314
|
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2106
2315
|
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2107
2316
|
throw sessionHostMismatch(request);
|
|
2108
|
-
},
|
|
2109
|
-
|
|
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;
|
|
2322
|
+
}, withSession = (request) => async (opts) => {
|
|
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
|
+
);
|
|
2328
|
+
if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2329
|
+
throw projectApiDown(sent);
|
|
2330
|
+
return request(opts);
|
|
2331
|
+
}, admitToLake = (request) => {
|
|
2332
|
+
refuseSession(request), refuseInternalToken(request);
|
|
2110
2333
|
const access = activeAccess();
|
|
2111
2334
|
if (access === void 0) return;
|
|
2112
2335
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2669,8 +2892,15 @@ function makeHandle(handleArgs) {
|
|
|
2669
2892
|
},
|
|
2670
2893
|
identities: () => Object.fromEntries(backend.identities),
|
|
2671
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
|
+
);
|
|
2672
2899
|
requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
|
|
2673
2900
|
},
|
|
2901
|
+
simulateOutage: (component) => {
|
|
2902
|
+
backend.outages.add(component);
|
|
2903
|
+
},
|
|
2674
2904
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2675
2905
|
transactions: () => [...backend.log],
|
|
2676
2906
|
clearLog: () => {
|
|
@@ -2705,6 +2935,7 @@ export {
|
|
|
2705
2935
|
ERR_PREFIX,
|
|
2706
2936
|
GuardDeniedError,
|
|
2707
2937
|
PlatformHttpError,
|
|
2938
|
+
PlatformServerError,
|
|
2708
2939
|
SUPPORTED_SURFACE,
|
|
2709
2940
|
UNSUPPORTED_MEMBERS,
|
|
2710
2941
|
WriteAccessDeniedError,
|