@sanity-labs/client-fake-for-test 0.18.0 → 0.20.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 +24 -3
- package/dist/index.cjs +103 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +103 -32
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1301,10 +1301,18 @@ export declare interface TestClientIdentity {
|
|
|
1301
1301
|
* Access API entries, keyed `"<access type>:<id>"` (`"organization:<id>"`,
|
|
1302
1302
|
* `"media-library:<id>"`, `"canvas:<id>"`, `"dashboard:<id>"`,
|
|
1303
1303
|
* `"project:<projectId>"`). On a non-project resource, an entry with
|
|
1304
|
-
* `roles` makes the identity a member there. Project membership needs no
|
|
1305
|
-
*
|
|
1304
|
+
* `roles` makes the identity a member there. Project membership needs no
|
|
1305
|
+
* entry: see `projectId`.
|
|
1306
1306
|
*/
|
|
1307
1307
|
access?: Record<string, ResourceAccess>;
|
|
1308
|
+
/**
|
|
1309
|
+
* The project a project-scoped token belongs to, as a robot token belongs
|
|
1310
|
+
* to the project that issued it. The identity is a member of that project
|
|
1311
|
+
* only, and its token is refused on any other project's API host. Omit
|
|
1312
|
+
* for a token the fake treats as a member of every project, accepted on
|
|
1313
|
+
* every host.
|
|
1314
|
+
*/
|
|
1315
|
+
projectId?: string;
|
|
1308
1316
|
}
|
|
1309
1317
|
|
|
1310
1318
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1301,10 +1301,18 @@ export declare interface TestClientIdentity {
|
|
|
1301
1301
|
* Access API entries, keyed `"<access type>:<id>"` (`"organization:<id>"`,
|
|
1302
1302
|
* `"media-library:<id>"`, `"canvas:<id>"`, `"dashboard:<id>"`,
|
|
1303
1303
|
* `"project:<projectId>"`). On a non-project resource, an entry with
|
|
1304
|
-
* `roles` makes the identity a member there. Project membership needs no
|
|
1305
|
-
*
|
|
1304
|
+
* `roles` makes the identity a member there. Project membership needs no
|
|
1305
|
+
* entry: see `projectId`.
|
|
1306
1306
|
*/
|
|
1307
1307
|
access?: Record<string, ResourceAccess>;
|
|
1308
|
+
/**
|
|
1309
|
+
* The project a project-scoped token belongs to, as a robot token belongs
|
|
1310
|
+
* to the project that issued it. The identity is a member of that project
|
|
1311
|
+
* only, and its token is refused on any other project's API host. Omit
|
|
1312
|
+
* for a token the fake treats as a member of every project, accepted on
|
|
1313
|
+
* every host.
|
|
1314
|
+
*/
|
|
1315
|
+
projectId?: string;
|
|
1308
1316
|
}
|
|
1309
1317
|
|
|
1310
1318
|
/**
|
package/dist/index.js
CHANGED
|
@@ -60,6 +60,26 @@ const sessionNotFound = (request) => new PlatformHttpError({
|
|
|
60
60
|
message: "Session not found",
|
|
61
61
|
statusCode: 401
|
|
62
62
|
}
|
|
63
|
+
}), sessionHostMismatch = (request) => new PlatformHttpError({
|
|
64
|
+
...request,
|
|
65
|
+
statusCode: 401,
|
|
66
|
+
statusMessage: "Unauthorized",
|
|
67
|
+
body: {
|
|
68
|
+
statusCode: 401,
|
|
69
|
+
errorCode: "SIO-401-AWH",
|
|
70
|
+
error: "Unauthorized",
|
|
71
|
+
message: "Session does not match project host"
|
|
72
|
+
}
|
|
73
|
+
}), projectMembershipRequired = (request) => accessApiError({
|
|
74
|
+
request,
|
|
75
|
+
statusCode: 401,
|
|
76
|
+
statusMessage: "Unauthorized",
|
|
77
|
+
message: "User must be a member of this project to perform this operation"
|
|
78
|
+
}), mediaLibraryReadRequired = (request) => accessApiError({
|
|
79
|
+
request,
|
|
80
|
+
statusCode: 401,
|
|
81
|
+
statusMessage: "Unauthorized",
|
|
82
|
+
message: "User must be able to read media libraries for this organization to perform this operation"
|
|
63
83
|
}), noPermission = (request) => accessApiError({
|
|
64
84
|
request,
|
|
65
85
|
statusCode: 403,
|
|
@@ -115,6 +135,9 @@ function datasetParts(id) {
|
|
|
115
135
|
const dot = id.indexOf(".");
|
|
116
136
|
return { projectId: id.slice(0, dot), dataset: id.slice(dot + 1) };
|
|
117
137
|
}
|
|
138
|
+
function isProjectMember(tokenProjectId, projectId) {
|
|
139
|
+
return tokenProjectId === void 0 || tokenProjectId === projectId;
|
|
140
|
+
}
|
|
118
141
|
function accessEntryRoles(type) {
|
|
119
142
|
return ({ identity, id }) => identity.access?.[accessKey(type, id)]?.roles;
|
|
120
143
|
}
|
|
@@ -149,6 +172,10 @@ const RESOURCE_CAPABILITIES = {
|
|
|
149
172
|
lookupAtBase: !0,
|
|
150
173
|
identity: "global",
|
|
151
174
|
acl: "served",
|
|
175
|
+
aclRefusals: {
|
|
176
|
+
unknown: notFound("Media library"),
|
|
177
|
+
read: { permission: "sanity.media-library.read", refusal: mediaLibraryReadRequired }
|
|
178
|
+
},
|
|
152
179
|
history: "served",
|
|
153
180
|
actions: "served",
|
|
154
181
|
refusedActions: { "sanity.action.release.create": releaseLimitExceeded },
|
|
@@ -161,6 +188,7 @@ const RESOURCE_CAPABILITIES = {
|
|
|
161
188
|
lookupAtBase: !0,
|
|
162
189
|
identity: "global",
|
|
163
190
|
acl: "served",
|
|
191
|
+
aclRefusals: { unknown: notFound("Resource") },
|
|
164
192
|
history: "served",
|
|
165
193
|
actions: notMounted,
|
|
166
194
|
refusedActions: {},
|
|
@@ -243,8 +271,8 @@ const ACCESS_CAPABILITIES = {
|
|
|
243
271
|
// Single-user reads are served only where the fake checks members read (the
|
|
244
272
|
// organization); elsewhere they refuse rather than answer unchecked.
|
|
245
273
|
user: noPermission,
|
|
246
|
-
//
|
|
247
|
-
memberRoles: ({ identity, id }) => (identity.usersByProject?.[id] ?? identity.user).roles ?? []
|
|
274
|
+
// A member holds its project roles; see `isProjectMember`.
|
|
275
|
+
memberRoles: ({ identity, id }) => isProjectMember(identity.projectId, id) ? (identity.usersByProject?.[id] ?? identity.user).roles ?? [] : void 0
|
|
248
276
|
},
|
|
249
277
|
"media-library": {
|
|
250
278
|
// Staging refuses it only because no probe token held roles read.
|
|
@@ -451,6 +479,8 @@ async function servePlatformRequest(ctx, url) {
|
|
|
451
479
|
const projectFeatures = path.match(PROJECT_FEATURES_PATH);
|
|
452
480
|
if (projectFeatures !== null) {
|
|
453
481
|
const projectId = decodeURIComponent(projectFeatures[1]);
|
|
482
|
+
if (!isProjectMember(ctx.actorProjectId(), projectId))
|
|
483
|
+
throw projectMembershipRequired(request);
|
|
454
484
|
return { value: featuresOf(ctx, projectId) };
|
|
455
485
|
}
|
|
456
486
|
const access = path.match(ACCESS_PATH);
|
|
@@ -469,12 +499,32 @@ async function servePlatformRequest(ctx, url) {
|
|
|
469
499
|
if (rest === "") return row.lookupAtBase ? serveLookup(ctx, resource) : void 0;
|
|
470
500
|
if (rest === "/acl")
|
|
471
501
|
return serveCapability(row.acl, request, () => {
|
|
502
|
+
refuseAcl({ ctx, request, resource, row });
|
|
472
503
|
const own = ctx.own(resource);
|
|
473
504
|
return own === void 0 ? void 0 : { value: own.grants };
|
|
474
505
|
});
|
|
475
506
|
if (rest.startsWith("/history/"))
|
|
476
507
|
return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
|
|
477
508
|
}
|
|
509
|
+
function refuseAclRequest(ctx, url) {
|
|
510
|
+
const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
|
|
511
|
+
if (matched?.rest !== "/acl") return;
|
|
512
|
+
const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
|
|
513
|
+
serveCapability(
|
|
514
|
+
row.acl,
|
|
515
|
+
request,
|
|
516
|
+
() => refuseAcl({ ctx, request, resource: matched.resource, row })
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
function refuseAcl(args) {
|
|
520
|
+
const { ctx, request, resource, row } = args;
|
|
521
|
+
if (row.aclRefusals === void 0) return;
|
|
522
|
+
const type = row.access.type, id = row.access.id(resource.id), registry = { organizationId: ctx.organizationId, resources: ctx.resources };
|
|
523
|
+
if (!holdsResource(type)(registry, id)) throw row.aclRefusals.unknown(request);
|
|
524
|
+
const { read } = row.aclRefusals;
|
|
525
|
+
if (read !== void 0 && !(ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? []).includes(read.permission))
|
|
526
|
+
throw read.refusal(request);
|
|
527
|
+
}
|
|
478
528
|
function featuresOf(ctx, projectId) {
|
|
479
529
|
const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
|
|
480
530
|
return [...new Set(features)].toSorted();
|
|
@@ -757,12 +807,6 @@ async function enforceWriteAccess(args) {
|
|
|
757
807
|
function defaultAclPath(projectId, dataset) {
|
|
758
808
|
return `/projects/${projectId}/datasets/${dataset}/acl`;
|
|
759
809
|
}
|
|
760
|
-
function refusedAcl(path) {
|
|
761
|
-
const matched = matchResourcePath(path);
|
|
762
|
-
if (matched?.rest !== "/acl") return;
|
|
763
|
-
const { acl } = capabilitiesOf(matched.resource.type);
|
|
764
|
-
return acl === "served" ? void 0 : acl({ method: "GET", path });
|
|
765
|
-
}
|
|
766
810
|
function projectUserOf(identity, projectId) {
|
|
767
811
|
return identity.usersByProject?.[projectId] ?? identity.user;
|
|
768
812
|
}
|
|
@@ -799,7 +843,7 @@ function serveProjectUsers(args) {
|
|
|
799
843
|
};
|
|
800
844
|
}, byId = consistentProjectRecords({
|
|
801
845
|
projectId: pathProjectId,
|
|
802
|
-
records: identities.map(toRecord)
|
|
846
|
+
records: identities.filter((identity) => isProjectMember(identity.projectId, pathProjectId)).map(toRecord)
|
|
803
847
|
}), ids = requestedIds.split(","), [firstId] = ids;
|
|
804
848
|
if (ids.length === 1 && firstId !== void 0) {
|
|
805
849
|
const record = byId.get(firstId);
|
|
@@ -819,17 +863,19 @@ function serveProjectUsers(args) {
|
|
|
819
863
|
}
|
|
820
864
|
const PROJECT_USERS_PATH = /^\/projects\/([^/]+)\/users\/([^/]+)$/, PROJECT_PATH = /^\/projects\/([^/]+)$/;
|
|
821
865
|
function serveProject(args) {
|
|
822
|
-
const records = args.identities.
|
|
866
|
+
const records = args.identities.filter(
|
|
867
|
+
(identity) => isProjectMember(identity.projectId, args.pathProjectId)
|
|
868
|
+
).map((identity) => {
|
|
823
869
|
const projectUser = projectUserOf(identity, args.pathProjectId);
|
|
824
870
|
return {
|
|
825
871
|
id: projectUser.id,
|
|
826
872
|
...projectUser.id.startsWith("p-") ? { isRobot: !0 } : {},
|
|
827
873
|
...projectUser.roles !== void 0 ? { roles: canonicalProjectRoles(projectUser.roles) } : {}
|
|
828
874
|
};
|
|
829
|
-
}),
|
|
875
|
+
}), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
|
|
830
876
|
return {
|
|
831
877
|
...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
|
|
832
|
-
members: [...
|
|
878
|
+
members: [...byId.values()]
|
|
833
879
|
};
|
|
834
880
|
}
|
|
835
881
|
function makeRequestImpl(ctx) {
|
|
@@ -838,8 +884,8 @@ function makeRequestImpl(ctx) {
|
|
|
838
884
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
839
885
|
if (path === "/users/me")
|
|
840
886
|
return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
841
|
-
if (path !== void 0 && path === accessControl.aclPath
|
|
842
|
-
return accessControl.grants;
|
|
887
|
+
if (path !== void 0 && path === accessControl.aclPath)
|
|
888
|
+
return refuseAclRequest(platform, path), accessControl.grants;
|
|
843
889
|
const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
|
|
844
890
|
if (pathProjectId !== void 0 && requestedIds !== void 0)
|
|
845
891
|
return serveProjectUsers({
|
|
@@ -1868,7 +1914,16 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
|
|
|
1868
1914
|
function ensureEntry(registry, resource) {
|
|
1869
1915
|
const key = registryKey(resource);
|
|
1870
1916
|
let entry = registry.get(key);
|
|
1871
|
-
return entry === void 0 && (entry = {
|
|
1917
|
+
return entry === void 0 && (entry = {
|
|
1918
|
+
resource,
|
|
1919
|
+
store: createTestStore(),
|
|
1920
|
+
history: createDocumentHistory(),
|
|
1921
|
+
exists: !1
|
|
1922
|
+
}, registry.set(key, entry)), entry;
|
|
1923
|
+
}
|
|
1924
|
+
function seedEntry(registry, resource, documents) {
|
|
1925
|
+
const entry = ensureEntry(registry, resource);
|
|
1926
|
+
entry.store.seed(documents), entry.exists = !0;
|
|
1872
1927
|
}
|
|
1873
1928
|
function createTestClient(options = {}) {
|
|
1874
1929
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
@@ -1885,16 +1940,16 @@ function createTestClient(options = {}) {
|
|
|
1885
1940
|
}, registry = backend.registry;
|
|
1886
1941
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
1887
1942
|
const root = options.resource ?? datasetResource(defaultProjectId, defaultDataset);
|
|
1888
|
-
|
|
1943
|
+
seedEntry(registry, root, options.documents);
|
|
1889
1944
|
}
|
|
1890
1945
|
if (options.datasets)
|
|
1891
1946
|
for (const [key, docs] of Object.entries(options.datasets)) {
|
|
1892
1947
|
const { projectId, dataset } = parseDatasetKey(key);
|
|
1893
|
-
|
|
1948
|
+
seedEntry(registry, datasetResource(projectId, dataset), docs);
|
|
1894
1949
|
}
|
|
1895
1950
|
if (options.resources)
|
|
1896
1951
|
for (const [key, docs] of Object.entries(options.resources))
|
|
1897
|
-
|
|
1952
|
+
seedEntry(registry, parseResourceKey(key), docs);
|
|
1898
1953
|
return makeHandle({
|
|
1899
1954
|
backend,
|
|
1900
1955
|
projectId: defaultProjectId,
|
|
@@ -1986,10 +2041,14 @@ function makeHandle(handleArgs) {
|
|
|
1986
2041
|
if (access === void 0)
|
|
1987
2042
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1988
2043
|
return access;
|
|
1989
|
-
},
|
|
1990
|
-
if (token
|
|
1991
|
-
|
|
1992
|
-
|
|
2044
|
+
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2045
|
+
if (token === void 0) return;
|
|
2046
|
+
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2047
|
+
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2048
|
+
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2049
|
+
throw sessionHostMismatch(request);
|
|
2050
|
+
}, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
2051
|
+
refuseSession(request);
|
|
1993
2052
|
const access = activeAccess();
|
|
1994
2053
|
if (access === void 0) return;
|
|
1995
2054
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2004,7 +2063,18 @@ function makeHandle(handleArgs) {
|
|
|
2004
2063
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2005
2064
|
}
|
|
2006
2065
|
] : []
|
|
2007
|
-
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id),
|
|
2066
|
+
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
|
|
2067
|
+
...store,
|
|
2068
|
+
seed: (documents) => {
|
|
2069
|
+
store.seed(documents), targetEntry.exists = !0;
|
|
2070
|
+
},
|
|
2071
|
+
add: (documents) => {
|
|
2072
|
+
store.add(documents), targetEntry.exists = !0;
|
|
2073
|
+
},
|
|
2074
|
+
put: (doc) => {
|
|
2075
|
+
store.put(doc), targetEntry.exists = !0;
|
|
2076
|
+
}
|
|
2077
|
+
}, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
|
|
2008
2078
|
const access = activeAccess();
|
|
2009
2079
|
if (access !== void 0)
|
|
2010
2080
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
@@ -2018,7 +2088,7 @@ function makeHandle(handleArgs) {
|
|
|
2018
2088
|
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
2019
2089
|
}
|
|
2020
2090
|
}), commitHistory = (transactionId) => {
|
|
2021
|
-
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
2091
|
+
beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
|
|
2022
2092
|
}, record = (transactionId, mutations, tag) => {
|
|
2023
2093
|
const effectiveTag = effectiveRequestTag(tag);
|
|
2024
2094
|
commitHistory(transactionId), backend.log.push({
|
|
@@ -2174,7 +2244,7 @@ function makeHandle(handleArgs) {
|
|
|
2174
2244
|
);
|
|
2175
2245
|
}, runAction = async (actions) => {
|
|
2176
2246
|
const request = lakeRequest("POST", "actions");
|
|
2177
|
-
if (
|
|
2247
|
+
if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2178
2248
|
return write(async () => {
|
|
2179
2249
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2180
2250
|
const refused = capabilities.refusedActions[action.actionType];
|
|
@@ -2381,9 +2451,7 @@ function makeHandle(handleArgs) {
|
|
|
2381
2451
|
request: withSession(
|
|
2382
2452
|
makeRequestImpl({
|
|
2383
2453
|
getAccess: requireActiveAccess,
|
|
2384
|
-
|
|
2385
|
-
// client to the global API host.
|
|
2386
|
-
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2454
|
+
useProjectHostname: projectHosted,
|
|
2387
2455
|
organizationId: backend.organizationId,
|
|
2388
2456
|
listIdentities: members,
|
|
2389
2457
|
platform: {
|
|
@@ -2402,8 +2470,11 @@ function makeHandle(handleArgs) {
|
|
|
2402
2470
|
return access.globalUser ?? access.currentUser;
|
|
2403
2471
|
},
|
|
2404
2472
|
actorAccess: () => requireActiveAccess().access,
|
|
2473
|
+
actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
|
|
2405
2474
|
identities: members,
|
|
2406
|
-
|
|
2475
|
+
// A dataset stands for its project, and every project exists in
|
|
2476
|
+
// the fake, so a dataset handle still counts as before.
|
|
2477
|
+
resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
|
|
2407
2478
|
}
|
|
2408
2479
|
})
|
|
2409
2480
|
)
|
|
@@ -2434,11 +2505,11 @@ function makeHandle(handleArgs) {
|
|
|
2434
2505
|
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2435
2506
|
});
|
|
2436
2507
|
},
|
|
2437
|
-
seed: (documents) =>
|
|
2438
|
-
add: (documents) =>
|
|
2508
|
+
seed: (documents) => publicStore.seed(documents),
|
|
2509
|
+
add: (documents) => publicStore.add(documents),
|
|
2439
2510
|
reset: () => store.reset(),
|
|
2440
2511
|
snapshot: () => store.snapshot(),
|
|
2441
|
-
store: () =>
|
|
2512
|
+
store: () => publicStore,
|
|
2442
2513
|
simulateConcurrentEdit: (id, count = 1) => {
|
|
2443
2514
|
const editKey = concurrentEditKey(id);
|
|
2444
2515
|
backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
|