@sanity-labs/client-fake-for-test 0.18.0 → 0.19.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
@@ -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 entry: every identity is a member of
1305
- * every project with its project-scoped roles.
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 entry: every identity is a member of
1305
- * every project with its project-scoped roles.
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
- // Every registered identity is a member of every project, with its project roles.
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.map((identity) => {
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
- }), members = consistentProjectRecords({ projectId: args.pathProjectId, records });
875
+ }), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
830
876
  return {
831
877
  ...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
832
- members: [...members.values()]
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 && refusedAcl(path) === void 0)
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({
@@ -1986,10 +2032,14 @@ function makeHandle(handleArgs) {
1986
2032
  if (access === void 0)
1987
2033
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1988
2034
  return access;
1989
- }, refuseRevoked = (request) => {
1990
- if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
1991
- }, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
1992
- refuseRevoked(request);
2035
+ }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2036
+ if (token === void 0) return;
2037
+ if (backend.revoked.has(token)) throw sessionNotFound(request);
2038
+ const tokenProjectId = backend.identities.get(token)?.projectId;
2039
+ if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2040
+ throw sessionHostMismatch(request);
2041
+ }, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
2042
+ refuseSession(request);
1993
2043
  const access = activeAccess();
1994
2044
  if (access === void 0) return;
1995
2045
  const refusal = refusedToken(request, access.grants);
@@ -2174,7 +2224,7 @@ function makeHandle(handleArgs) {
2174
2224
  );
2175
2225
  }, runAction = async (actions) => {
2176
2226
  const request = lakeRequest("POST", "actions");
2177
- if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
2227
+ if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2178
2228
  return write(async () => {
2179
2229
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2180
2230
  const refused = capabilities.refusedActions[action.actionType];
@@ -2381,9 +2431,7 @@ function makeHandle(handleArgs) {
2381
2431
  request: withSession(
2382
2432
  makeRequestImpl({
2383
2433
  getAccess: requireActiveAccess,
2384
- // `@sanity/client` sends every request of a `resource`-configured
2385
- // client to the global API host.
2386
- useProjectHostname: useProjectHostname && resource === void 0,
2434
+ useProjectHostname: projectHosted,
2387
2435
  organizationId: backend.organizationId,
2388
2436
  listIdentities: members,
2389
2437
  platform: {
@@ -2402,6 +2450,7 @@ function makeHandle(handleArgs) {
2402
2450
  return access.globalUser ?? access.currentUser;
2403
2451
  },
2404
2452
  actorAccess: () => requireActiveAccess().access,
2453
+ actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
2405
2454
  identities: members,
2406
2455
  resources: () => [...registry.values()].map((entry) => entry.resource)
2407
2456
  }