From be7985da9ffbffaacaad5fcbfe3405bed439a77c Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:50:03 +0000 Subject: [PATCH 01/28] Let Rotur orgs own projects and spaces in place of Rotur groups --- opal.json | 2 +- scripts/e2e_smoke.py | 68 ++++++- src/auth/user-identity.osl | 2 +- src/classroom/classroom-release.osl | 2 +- src/classroom/classrooms.osl | 2 +- src/community/challenges.osl | 10 +- src/community/groups.osl | 163 --------------- src/community/org-page.osl | 77 ++++++++ src/community/orgs.osl | 196 +++++++++++++++++++ src/community/orgs.test.osl | 181 +++++++++++++++++ src/community/routes.osl | 3 +- src/community/space-model.osl | 2 +- src/community/space-responses.osl | 2 +- src/community/spaces.osl | 65 +++--- src/projects/fork-visibility.test.osl | 4 +- src/projects/project-access.osl | 2 +- src/projects/project-create.osl | 28 +-- src/projects/project-discovery.osl | 2 +- src/projects/project-remix.test.osl | 6 +- src/projects/project-response.osl | 2 +- src/projects/project-team.test.osl | 6 +- src/projects/project-update-lookups.osl | 11 +- src/projects/project-update-lookups.test.osl | 6 +- src/projects/project-update.osl | 30 +-- src/storage/storage.osl | 6 +- 25 files changed, 594 insertions(+), 284 deletions(-) delete mode 100644 src/community/groups.osl create mode 100644 src/community/org-page.osl create mode 100644 src/community/orgs.osl create mode 100644 src/community/orgs.test.osl diff --git a/opal.json b/opal.json index bfd38cd..a45bfb5 100644 --- a/opal.json +++ b/opal.json @@ -1,6 +1,6 @@ { "name": "mistwarp-api", - "version": "1.7.0", + "version": "2.0.0", "main": "main.osl", "scripts": { "dev": ["osl", "run", "main.osl"], diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index d7f0f0f..567bb9b 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -34,6 +34,16 @@ USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena"} FULL_STORAGE = {"u_dee"} +ORGS = { + "studio": { + "id": "o_studio", "username": "studio", "display_name": "Smoke Studio", "bio": "Games", "member_count": 3, + "members": [ + {"id": "u_sam", "username": "sam", "admin": True, "perms": ["admin"], "public": True}, + {"id": "u_alice", "username": "alice", "admin": False, "perms": ["billing"], "public": True}, + {"id": "u_dee", "username": "dee", "admin": False, "perms": ["apps"], "public": False}, + ], + }, +} GONE_USERS = {"gone_user"} BUSY_USERS = {"busy_user"} BANNED_USERS = {"banned_user"} @@ -89,7 +99,13 @@ def do_GET(self): if self.path.startswith("/v2/storage-ledger/"): self.answer(404, {"code": "not_found"}) return + if self.path.startswith("/v2/integrations/mistwarp/"): + self.answer_org_integration() + return name = self.path.split("?", 1)[0][len("/profile/"):] if self.path.startswith("/profile/") else "" + if name in ORGS: + self.answer(200, {"id": ORGS[name]["id"], "username": name, "account_type": "org"}) + return if name in GONE_USERS: self.answer(404, {"error": "User not found"}) return @@ -108,6 +124,25 @@ def do_GET(self): return self.answer(200, {"id": USERS[name], "username": name}) + def answer_org_integration(self): + if self.headers.get("X-Commerce-Key") != "smoke": + self.answer(403, {"error": "invalid service key"}) + return + parts = self.path.split("?", 1)[0].split("/") + if parts[4] == "orgs" and len(parts) == 6: + org = ORGS.get(urllib.parse.unquote(parts[5])) + self.answer(200, org) if org else self.answer(404, {"code": "not_org", "not_org": True}) + return + if parts[4] == "users" and len(parts) == 7 and parts[6] == "orgs": + mine = [] + for org in ORGS.values(): + for member in org["members"]: + if member["id"] == parts[5]: + mine.append({"id": org["id"], "username": org["username"], "display_name": org["display_name"], "perms": member["perms"]}) + self.answer(200, {"orgs": mine}) + return + self.answer(404, {"code": "not_found"}) + def do_POST(self): if not self.path.startswith("/v2/storage-ledger/"): self.close_connection = True @@ -149,7 +184,7 @@ def __init__(self, binary, keep): os.makedirs(os.path.join(data, "sessions")) with open(os.path.join(self.dir, ".env"), "w") as env: rotur = "http://127.0.0.1:%d" % self.rotur.server_address[1] - env.write("PORT=%d\nAPP_URL=http://127.0.0.1:%d\nROTUR_BASE=%s\nROTUR_LOCAL_API_URL=%s\nROTUR_SERVICE_SECRET=smoke\n" % (self.port, self.port, rotur, rotur)) + env.write("PORT=%d\nAPP_URL=http://127.0.0.1:%d\nROTUR_BASE=%s\nROTUR_LOCAL_API_URL=%s\nROTUR_SERVICE_SECRET=smoke\nCOMMERCE_SERVICE_KEY=smoke\n" % (self.port, self.port, rotur, rotur)) with open(os.path.join(data, "agreement.json"), "w") as handle: json.dump({"version": 1, "text": "", "updatedAt": 1700000000000}, handle) with open(os.path.join(data, "agreement.md"), "w") as handle: @@ -777,10 +812,7 @@ def patch(name, body, who="sam"): patch("patch vanity without plan", {"vanitySlug": "smoke-game"}) patch("patch null vanity", {"vanitySlug": None}) patch("patch vanity cleared", {"vanitySlug": ""}) - patch("patch group tag invalid", {"groupTag": "!!!"}) - patch("patch group tag not managed", {"groupTag": "somegroup"}) - patch("patch null group tag", {"groupTag": None}) - patch("patch group tag cleared", {"groupTag": " "}) + patch("patch group tag ignored", {"groupTag": "somegroup"}) patch("patch nameless teammate", {"collaborators": [{"role": "editor"}]}) patch("patch team share too high", {"collaborators": [{"username": "alice", "role": "editor", "share": 60}]}) patch("patch team unknown user", {"collaborators": [{"username": "ghost_user", "role": "editor"}]}) @@ -802,7 +834,7 @@ def patch(name, body, who="sam"): patch("patch editor session refused", {"collaborators": []}, who="sam_editor") patch("patch transfer as maintainer", {"owner": "bob"}, who="alice") patch("patch transfer unknown", {"owner": "ghost_user"}) - patch("patch transfer", {"owner": "bob", "keepGroup": True, "title": "Given away"}) + patch("patch transfer", {"owner": "bob", "title": "Given away"}) patch("patch after transfer", {"title": "Mine again"}) step("get updated project", "GET", path, "bob") for name, body in ( @@ -990,6 +1022,29 @@ def synced_tree(server, ids, alias, who, head, merge): return zip_files(files) +def org_flow(server, step, steps, ids): + step("org page for a person", "GET", "/v1/orgs/bob") + step("my orgs", "GET", "/v1/me/orgs", "alice") + step("org create refused for billing", "POST", "/v1/projects", "alice", {"title": "Not allowed", "org": "studio"}) + step("org create for a person", "POST", "/v1/projects", "dee", {"title": "Not an org", "org": "bob"}) + status, created = step("org create", "POST", "/v1/projects", "dee", {"title": "Studio game", "org": "studio"}) + ids[str(created.get("id", "")) if isinstance(created, dict) else ""] = "" + path = "/v1/projects/" + step("org project as publisher", "GET", path, "sam") + step("org project edit as publisher", "PUT", path, "sam", {"title": "Studio game 2"}) + step("org project edit as billing", "PUT", path, "alice", {"title": "Nope"}) + status, mine = step("org own create", "POST", "/v1/projects", "bob", {"title": "Bob's game"}) + ids[str(mine.get("id", "")) if isinstance(mine, dict) else ""] = "" + step("org transfer refused for an outsider", "PUT", "/v1/projects/", "bob", {"owner": "studio"}) + status, given = step("org transfer by member", "POST", "/v1/projects", "dee", {"title": "Dee's game"}) + ids[str(given.get("id", "")) if isinstance(given, dict) else ""] = "" + step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) + step("org transfer back", "PUT", "/v1/projects/", "sam", {"owner": "dee"}) + step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) + step("org page", "GET", "/v1/orgs/studio") + step("org page as member", "GET", "/v1/orgs/studio", "dee") + + def remix_sync_flow(server, step, steps, ids): plain = sb3_archive(project_with_costumes([])) status, created = step("sync original create", "POST", "/v1/projects", "sam", {"title": "Sync original"}) @@ -1289,6 +1344,7 @@ def step(name, method, path, who=None, body=None, upload=None, headers=(), form= slow_ledger_flow(server, step, steps, ids) locks_flow(server, step, steps, ids) remix_sync_flow(server, step, steps, ids) + org_flow(server, step, steps, ids) time.sleep(1.5) for real, alias in list(ids.items()): if alias in ("", "", ""): diff --git a/src/auth/user-identity.osl b/src/auth/user-identity.osl index 5210f47..32c755f 100644 --- a/src/auth/user-identity.osl +++ b/src/auth/user-identity.osl @@ -578,7 +578,7 @@ def discoverUserIdentityOutcome(string username) object ( ) ensureUserIdentity(userId, currentUsername) identityRefreshCache.set(userId, currentUsername) - return {id: userId, outcome: "found"} + return {id: userId, outcome: "found", accountType: (profile.account_type ?? "").toStr()} ) def usernameForId(string userId) string ( diff --git a/src/classroom/classroom-release.osl b/src/classroom/classroom-release.osl index 1226fde..5631369 100644 --- a/src/classroom/classroom-release.osl +++ b/src/classroom/classroom-release.osl @@ -114,7 +114,7 @@ def handleGetClaim(*serve.Context c) ( def moveProjectOwner(object project, string username, string userId) ( project.owner = username project.ownerId = userId - project.groupTag = "" + project.ownerType = "" project.edited = timestamp saveProject(project) upsertIndexEntry(project) diff --git a/src/classroom/classrooms.osl b/src/classroom/classrooms.osl index 1f82f39..5d16eb5 100644 --- a/src/classroom/classrooms.osl +++ b/src/classroom/classrooms.osl @@ -1132,7 +1132,7 @@ def createBlankStudentProject(object student, string title) object ( id: id, owner: student.username, ownerId: student["_id"], - groupTag: "", + ownerType: "", branding: {}, vanitySlug: "", title: title, diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 327d73d..0813426 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -61,9 +61,8 @@ def challengeJudges(object space) array ( return [] ) array judges = challengeArray(space, "judges") - string tag = groupTagOf(space) - if tag != "" ( - array members = groupMemberNames(roturGroupSnapshot(tag)) + if isOrgOwned(space) ( + array members = orgPublicMemberNames(roturOrgSnapshot((space.owner ?? "").toStr())) for i members.len ( string member = members[i].toStr() if !stringArrayContainsUser(judges, member) ( @@ -75,7 +74,10 @@ def challengeJudges(object space) array ( ) def isChallengeJudge(object space, string username) boolean ( - return stringArrayContainsUser(challengeJudges(space), username) + if stringArrayContainsUser(challengeJudges(space), username) ( + return true + ) + return !challengeAudienceJudged(space) and isOrgOwned(space) and orgHasMember(roturOrgSnapshot((space.owner ?? "").toStr()), "", username) ) def isChallengeJudgeInvitee(object space, string username) boolean ( diff --git a/src/community/groups.osl b/src/community/groups.osl deleted file mode 100644 index e9755f0..0000000 --- a/src/community/groups.osl +++ /dev/null @@ -1,163 +0,0 @@ -export { - canManageGroupContent, - canManageGroupTag, - groupTagOf, - normalizeGroupTag -} - -*cache.Cache groupSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) - -def normalizeGroupTag(string value) string ( - string tag = value.toLower().strip() - if tag.len < 1 or tag.len > 10 or !regex.match("^[a-z0-9]+$", tag) ( - return "" - ) - return tag -) - -def roturPublicGroupSnapshot(string tag) object ( - object publicResponse = requests.get(roturBase ++ "/groups/" ++ url.escape(tag)).unwrapOr({body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false}) - if publicResponse.status != 200 ( - return {ok: false, error: if publicResponse.status == 404 then "group not found" else "could not load group"} - ) - auto publicParsed = json.parse(publicResponse.body, {type: "object"}) - if publicParsed.isErr() ( - return {ok: false, error: "invalid group response"} - ) - object fallback = {ok: true, degraded: true, group: publicParsed.unwrap(), members: []} - groupSnapshotCache.set(tag, fallback) - return fallback -) - -def roturGroupSnapshot(string rawTag) object ( - string tag = normalizeGroupTag(rawTag) - if tag == "" ( - return {ok: false, error: "invalid group tag"} - ) - if groupSnapshotCache.has(tag) ( - return groupSnapshotCache.get(tag).assertElse(object, {ok: false}) - ) - if commerceServiceKey == "" ( - return roturPublicGroupSnapshot(tag) - ) - object response = requests.get( - roturBase ++ "/groups/" ++ url.escape(tag) ++ "/integrations/mistwarp", - {headers: {"X-Commerce-Key": commerceServiceKey}} - ).unwrapOr({body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false}) - if response.status != 200 ( - return roturPublicGroupSnapshot(tag) - ) - auto parsed = json.parse(response.body, {type: "object"}) - if parsed.isErr() ( - return {ok: false, error: "invalid group response"} - ) - object data = parsed.unwrap().assert(object) - object snapshot = {ok: true, group: data.group, members: data.members} - groupSnapshotCache.set(tag, snapshot) - return snapshot -) - -def groupMemberNames(object snapshot) array ( - array names = [] - if !snapshot.ok or !snapshot.contains("members") or snapshot.members == null ( - return names - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - string username = member.username.toStr().strip() - if username != "" and !stringArrayContainsUser(names, username) ( - names.append(username) - ) - ) - return names -) - -def groupHasMember(object snapshot, string userId, string username) boolean ( - if !snapshot.ok ( - return false - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - if identityMatches(member.user_id.toStr(), member.username.toStr(), userId, username) ( - return true - ) - ) - return false -) - -def groupMemberCanManage(object snapshot, string userId, string username) boolean ( - if !snapshot.ok ( - return false - ) - object group = snapshot.group.assert(object) - if normalizeUsername(group.owner_user_id.toStr()) == normalizeUsername(username) ( - return true - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - if identityMatches(member.user_id.toStr(), member.username.toStr(), userId, username) ( - array permissions = member.permissions.assertElse(array, []) - return permissions.contains("groups.manage") or permissions.contains("groups.group.edit") - ) - ) - return false -) - -def canManageGroupTag(string tag,*serve.Context c) boolean ( - if contextBool(c, "isAdmin") ( - return true - ) - return groupMemberCanManage(roturGroupSnapshot(tag), contextString(c, "userId"), contextString(c, "username")) -) - -def groupTagOf(object value) string ( - if value.contains("groupTag") and value.groupTag != null ( - return normalizeGroupTag(value.groupTag.toStr()) - ) - return "" -) - -def canManageGroupContent(object value,*serve.Context c) boolean ( - string tag = groupTagOf(value) - return tag != "" and canManageGroupTag(tag, c) -) - -def handleGetMistWarpGroup(*serve.Context c) ( - string tag = normalizeGroupTag(c.param("tag")) - object snapshot = roturGroupSnapshot(tag) - if !snapshot.ok ( - c.notFound("group not found") - return - ) - boolean canManage = contextBool(c, "authenticated") and groupMemberCanManage(snapshot, contextString(c, "userId"), contextString(c, "username")) - array projects = [] - array projectEntries = projectSearchDocs.where("groupTag", "==", tag).sort("edited", "desc").all() - for i projectEntries.len ( - object project = projectEntries[i].assert(object) - if project.shared == true or project.visibility.toStr() == "unlisted" or canManage ( - projects.append(project) - ) - ) - projects = projectsVisibleTo(projects, c) - array spaces = [] - array spaceEntries = spaceDocs.where("groupTag", "==", tag).sort("edited", "desc").all() - for i spaceEntries.len ( - object space = spaceEntries[i].assert(object) - if space.visibility.toStr() == "public" or space.visibility.toStr() == "unlisted" or canManage ( - spaces.append(spaceListResponse(space, c)) - ) - ) - c.json(200, { - ok: true, - group: snapshot.group, - members: groupMemberNames(snapshot), - projects: projects, - spaces: spaces, - canManage: canManage, - isMember: contextBool(c, "authenticated") and groupHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")), - membershipLive:!snapshot.contains("degraded") or snapshot.degraded != true - }) -) diff --git a/src/community/org-page.osl b/src/community/org-page.osl new file mode 100644 index 0000000..df57786 --- /dev/null +++ b/src/community/org-page.osl @@ -0,0 +1,77 @@ +export {} + +def orgMemberResponse(object member) object ( + return { + username: (member.username ?? "").toStr(), + displayName: (member.display_name ?? "").toStr(), + admin: member.admin == true + } +) + +def orgProfileResponse(object org) object ( + return { + id: (org.id ?? "").toStr(), + username: (org.username ?? "").toStr(), + displayName: (org.display_name ?? "").toStr(), + bio: (org.bio ?? "").toStr(), + location: (org.location ?? "").toStr(), + links: (org.links ?? []).assertElse(array, []), + created: (org.created ?? 0).toNum(), + memberCount: (org.member_count ?? 0).toNum() + } +) + +def orgLookupFailed(*serve.Context c, object snapshot) ( + if snapshot.contains("unavailable") and snapshot.unavailable == true ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + c.notFound("organisation not found") +) + +def handleGetMistWarpOrg(*serve.Context c) ( + object snapshot = roturOrgSnapshot(c.param("name")) + if !snapshot.ok ( + orgLookupFailed(c, snapshot) + return + ) + string userId = contextString(c, "userId") + string username = contextString(c, "username") + boolean signedIn = contextBool(c, "authenticated") + boolean isMember = signedIn and orgHasMember(snapshot, userId, username) + array members = [] + array all = snapshot.members.assertElse(array, []) + for i all.len ( + object member = all[i].assertElse(object, {}) + if member.public == true or isMember ( + members.append(orgMemberResponse(member)) + ) + ) + object org = snapshot.org.assertElse(object, {}) + boolean canManage = signedIn and (contextBool(c, "isAdmin") or orgMemberCanPublish(snapshot, userId, username)) + c.json(200, { + ok: true, + org: orgProfileResponse(org), + members: members, + projects: projectsVisibleTo(ownerIndexEntries((org.username ?? "").toStr(), canManage), c), + spaces: orgSpaces((org.id ?? "").toStr(), canManage, c), + isMember: isMember, + canManage: canManage + }) +) + +def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( + array spaces = [] + if orgId == "" ( + return spaces + ) + array entries = spaceDocs.where("ownerId", "==", orgId).sort("edited", "desc").all() + for i entries.len ( + object space = entries[i].assertElse(object, {}) + string visibility = (space.visibility ?? "").toStr() + if visibility == "public" or canManage ( + spaces.append(spaceListResponse(space, c)) + ) + ) + return spaces +) diff --git a/src/community/orgs.osl b/src/community/orgs.osl new file mode 100644 index 0000000..f960935 --- /dev/null +++ b/src/community/orgs.osl @@ -0,0 +1,196 @@ +export { + canManageOrgContent, + canPublishForOrg, + creationOwner, + isOrgOwned, + orgHasMember, + orgPublicMemberNames, + roturOrgSnapshot +} + +*cache.Cache orgSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) +*cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) + +def roturServiceGet(string path) object ( + object failed = {body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false} + return requests.get(roturBase ++ path, {headers: {"X-Commerce-Key": commerceServiceKey}}).unwrapOr(failed) +) + +def roturOrgSnapshot(string rawName) object ( + string name = normalizeUsername(rawName) + if name == "" or !isSafePathPart(name) ( + return {ok: false, notOrg: true} + ) + if orgSnapshotCache.has(name) ( + return orgSnapshotCache.get(name).assertElse(object, {ok: false, unavailable: true}) + ) + if commerceServiceKey == "" ( + return {ok: false, unavailable: true} + ) + object response = roturServiceGet("/v2/integrations/mistwarp/orgs/" ++ url.escape(name)) + if response.status == 404 ( + object missing = {ok: false, notOrg: true} + orgSnapshotCache.set(name, missing) + return missing + ) + if response.status != 200 ( + return {ok: false, unavailable: true} + ) + auto parsed = json.parse(response.body, {type: "object"}) + if parsed.isErr() ( + return {ok: false, unavailable: true} + ) + object data = parsed.unwrap().assert(object) + object snapshot = {ok: true, org: data, members: (data.members ?? []).assertElse(array, [])} + orgSnapshotCache.set(name, snapshot) + return snapshot +) + +def orgMemberPerms(object snapshot, string userId, string username) array ( + if !snapshot.ok ( + return [] + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + if identityMatches((member.id ?? "").toStr(), (member.username ?? "").toStr(), userId, username) ( + if member.admin == true ( + return ["admin"] + ) + return (member.perms ?? []).assertElse(array, []) + ) + ) + return [] +) + +def orgHasMember(object snapshot, string userId, string username) boolean ( + if !snapshot.ok or (userId == "" and username == "") ( + return false + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + if identityMatches((member.id ?? "").toStr(), (member.username ?? "").toStr(), userId, username) ( + return true + ) + ) + return false +) + +def orgPermsAllowPublishing(array perms) boolean ( + return perms.contains("admin") or perms.contains("apps") +) + +def orgMemberCanPublish(object snapshot, string userId, string username) boolean ( + return orgPermsAllowPublishing(orgMemberPerms(snapshot, userId, username)) +) + +def canPublishForOrg(string name,*serve.Context c) boolean ( + if !contextBool(c, "authenticated") ( + return false + ) + object snapshot = roturOrgSnapshot(name) + if !snapshot.ok ( + return false + ) + if contextBool(c, "isAdmin") ( + return true + ) + return orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) +) + +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" +) + +def canManageOrgContent(object value,*serve.Context c) boolean ( + return isOrgOwned(value) and canPublishForOrg((value.owner ?? "").toStr(), c) +) + +def creationOwner(*serve.Context c, object body, string noun) object ( + string requestedOrg = (body.org ?? "").toStr().strip() + if requestedOrg == "" ( + return {ok: true, owner: contextString(c, "username"), ownerId: contextString(c, "userId"), ownerType: ""} + ) + object snapshot = roturOrgSnapshot(requestedOrg) + if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( + return {ok: false, status: 503, error: "Rotur can't be reached right now. Try again soon."} + ) + if !snapshot.ok ( + return {ok: false, status: 400, error: "organisation not found"} + ) + if !canPublishForOrg(requestedOrg, c) ( + return {ok: false, status: 403, error: "you cannot create " ++ noun ++ " for this organisation"} + ) + object org = snapshot.org.assertElse(object, {}) + string orgId = (org.id ?? "").toStr() + string orgName = (org.username ?? "").toStr() + if orgId == "" or orgName == "" ( + return {ok: false, status: 503, error: "Rotur can't be reached right now. Try again soon."} + ) + return {ok: true, owner: orgName, ownerId: orgId, ownerType: "org"} +) + +def orgPublicMemberNames(object snapshot) array ( + array names = [] + if !snapshot.ok ( + return names + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + string username = (member.username ?? "").toStr().strip() + if member.public == true and username != "" and !stringArrayContainsUser(names, username) ( + names.append(username) + ) + ) + return names +) + +def roturUserOrgs(string userId) object ( + if userId == "" or !isSafePathPart(userId) ( + return {ok: true, orgs: []} + ) + if userOrgsCache.has(userId) ( + return userOrgsCache.get(userId).assertElse(object, {ok: false}) + ) + if commerceServiceKey == "" ( + return {ok: false} + ) + object response = roturServiceGet("/v2/integrations/mistwarp/users/" ++ url.escape(userId) ++ "/orgs") + if response.status == 404 ( + return {ok: true, orgs: []} + ) + if response.status != 200 ( + return {ok: false} + ) + auto parsed = json.parse(response.body, {type: "object"}) + if parsed.isErr() ( + return {ok: false} + ) + object data = parsed.unwrap().assert(object) + object found = {ok: true, orgs: (data.orgs ?? []).assertElse(array, [])} + userOrgsCache.set(userId, found) + return found +) + +def handleGetMyOrgs(*serve.Context c) ( + object found = roturUserOrgs(contextString(c, "userId")) + if !found.ok ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + array orgs = [] + array entries = found.orgs.assertElse(array, []) + for i entries.len ( + object org = entries[i].assertElse(object, {}) + array perms = (org.perms ?? []).assertElse(array, []) + orgs.append({ + username: (org.username ?? "").toStr(), + displayName: (org.display_name ?? "").toStr(), + perms: perms, + canPublish: orgPermsAllowPublishing(perms) + }) + ) + c.json(200, {ok: true, orgs: orgs}) +) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl new file mode 100644 index 0000000..06e8aff --- /dev/null +++ b/src/community/orgs.test.osl @@ -0,0 +1,181 @@ +import "std:testing" +import "std:json" +import "std:requests" +import "std:serve" +import "std:thread" +import "std:cache" +import "std:url" + +string roturBase = "http://127.0.0.1:18351" +string commerceServiceKey = "mw-key" +array askedRotur = [] +number orgStatus = 200 + +def normalizeUsername(string name) string ( + return name.toLower().strip() +) + +def isSafePathPart(string value) boolean ( + return value != "" and !value.contains("/") +) + +def identityMatches(string storedId, string storedUsername, string userId, string username) boolean ( + if storedId != "" and userId != "" ( + return storedId == userId + ) + return normalizeUsername(storedUsername) == normalizeUsername(username) +) + +def stringArrayContainsUser(array users, string username) boolean ( + for i users.len ( + if normalizeUsername(users[i].toStr()) == normalizeUsername(username) ( + return true + ) + ) + return false +) + +def contextString(*serve.Context c, string key) string ( + if key == "username" ( + return (c.header("X-Test-User") ?? "") + ) + if key == "userId" ( + return (c.header("X-Test-Id") ?? "") + ) + return "" +) + +def contextBool(*serve.Context c, string key) boolean ( + if key == "authenticated" ( + return (c.header("X-Test-User") ?? "") != "" + ) + if key == "isAdmin" ( + return (c.header("X-Test-Admin") ?? "") == "1" + ) + return false +) + +import "./orgs.osl" + +object studio = { + id: "org_studio", + username: "Studio", + display_name: "The Studio", + bio: "We make games.", + member_count: 4, + members: [ + {id: "u_ada", username: "ada", admin: true, perms: ["admin"], public: true}, + {id: "u_bea", username: "bea", admin: false, perms: ["apps"], public: false}, + {id: "u_cal", username: "cal", admin: false, perms: ["billing"], public: true}, + {id: "u_dee", username: "dee", admin: false, perms: [], public: false} + ] +} + +def handleFakeOrg(*serve.Context c) ( + askedRotur.append(c.param("name") ++ " " ++ (c.header("X-Commerce-Key") ?? "")) + if (c.header("X-Commerce-Key") ?? "") != commerceServiceKey ( + c.json(403, {error: "invalid service key"}) + return + ) + if orgStatus != 200 ( + c.json(orgStatus, {error: "no"}) + return + ) + if c.param("name") != "studio" ( + c.json(404, {error: "Not an organisation", code: "not_org", not_org: true}) + return + ) + c.json(200, studio) +) + +def handleFakeUserOrgs(*serve.Context c) ( + askedRotur.append("orgs of " ++ c.param("id")) + c.json(200, {orgs: [{id: "org_studio", username: "Studio", display_name: "The Studio", perms: ["apps"]}, {id: "org_other", username: "other", perms: []}]}) +) + +def handleCheckPublish(*serve.Context c) ( + c.json(200, {ok: canPublishForOrg(c.param("name"), c)}) +) + +def handleCheckContent(*serve.Context c) ( + c.json(200, {ok: canManageOrgContent({owner: "studio", ownerType: (c.query("kind") ?? "")}, c)}) +) + +def handleCheckCreation(*serve.Context c) ( + c.json(200, creationOwner(c, {org: (c.query("org") ?? "")}, "projects")) +) + +*serve.Router fakeRotur = serve.new() +fakeRotur.GET("/v2/integrations/mistwarp/orgs/:name", handleFakeOrg) +fakeRotur.GET("/v2/integrations/mistwarp/users/:id/orgs", handleFakeUserOrgs) +fakeRotur.GET("/check/publish/:name", handleCheckPublish) +fakeRotur.GET("/check/content", handleCheckContent) +fakeRotur.GET("/check/create", handleCheckCreation) +fakeRotur.GET("/ready", handleFakeUserOrgs) + +def runFakeRotur() ( + fakeRotur.run(":18351") +) +thread.new(runFakeRotur) +for i 50 ( + if requests.get(roturBase ++ "/ready").isOk() ( + break + ) + wait 0.1 +) + +def ask(string path, string user, string id) object ( + object response = requests.get(roturBase ++ path, {headers: {"X-Test-User": user, "X-Test-Id": id}}).unwrap() + return json.parse(response.body, {type: "object"}).unwrap().assert(object) +) + +askedRotur = [] +object snapshot = roturOrgSnapshot("Studio") +testing.assert(snapshot.ok and snapshot.org.id == "org_studio", "an org comes back from Rotur") +testing.assert(askedRotur == ["studio mw-key"], "MistWarp asks with its service key, by the lowercased name") +void roturOrgSnapshot("studio") +testing.assert(askedRotur.len == 1, "a second look within the minute is cached") + +testing.assert(orgMemberPerms(snapshot, "u_ada", "ada") == ["admin"], "an admin has every permission") +testing.assert(orgMemberPerms(snapshot, "", "BEA") == ["apps"], "a member is found by name too") +testing.assert(orgMemberPerms(snapshot, "u_zed", "zed") == [], "someone outside the org has none") +testing.assert(orgHasMember(snapshot, "", "dee") and !orgHasMember(snapshot, "", "zed"), "membership includes private members") +testing.assert(orgPublicMemberNames(snapshot) == ["ada", "cal"], "only public members are named") +testing.assert(orgMemberCanPublish(snapshot, "u_bea", "bea") and orgMemberCanPublish(snapshot, "u_ada", "ada"), "apps and admin may publish") +testing.assert(!orgMemberCanPublish(snapshot, "u_cal", "cal") and !orgMemberCanPublish(snapshot, "u_dee", "dee"), "billing and plain members may not") + +object person = roturOrgSnapshot("ada") +testing.assert(!person.ok and person.notOrg == true, "a person is not an org") +testing.assert(!roturOrgSnapshot("a/b").ok and askedRotur.len == 2, "an unsafe name is never sent") + +orgStatus = 500 +object down = roturOrgSnapshot("busy") +testing.assert(!down.ok and down.unavailable == true, "a Rotur error is reported as unavailable") +void roturOrgSnapshot("busy") +testing.assert(askedRotur.len == 4, "an unavailable answer is not cached") +orgStatus = 200 + +testing.assert(isOrgOwned({ownerType: "org"}) and !isOrgOwned({ownerType: ""}) and !isOrgOwned({}), "only content marked as org-owned is") + +testing.assert(ask("/check/publish/studio", "bea", "u_bea").ok == true, "a member with apps can publish for the org") +testing.assert(ask("/check/publish/studio", "cal", "u_cal").ok == false, "a billing member cannot") +testing.assert(ask("/check/publish/studio", "", "").ok == false, "nobody signed out can") +testing.assert(ask("/check/publish/ada", "ada", "u_ada").ok == false, "nobody publishes for a person") +testing.assert(ask("/check/content?kind=org", "bea", "u_bea").ok == true, "a publisher manages the org's content") +testing.assert(ask("/check/content", "bea", "u_bea").ok == false, "but not content the org's name merely matches") + +object created = ask("/check/create?org=studio", "bea", "u_bea") +testing.assert(created.ok and created.owner == "Studio" and created.ownerId == "org_studio" and created.ownerType == "org", "content made for an org is owned by it") +object refused = ask("/check/create?org=studio", "dee", "u_dee") +testing.assert(!refused.ok and refused.status == 403, "a member without apps can't make content for the org") +object notOrg = ask("/check/create?org=ada", "ada", "u_ada") +testing.assert(!notOrg.ok and notOrg.status == 400, "content can't be made for a person through org") +object mine = ask("/check/create", "bea", "u_bea") +testing.assert(mine.ok and mine.owner == "bea" and mine.ownerType == "", "without an org, content is the creator's") + +askedRotur = [] +object orgs = roturUserOrgs("u_bea") +testing.assert(orgs.ok and orgs.orgs.len == 2 and askedRotur == ["orgs of u_bea"], "a person's orgs come from Rotur") +void roturUserOrgs("u_bea") +testing.assert(askedRotur.len == 1, "and are cached") +testing.assert(orgPermsAllowPublishing(["apps"]) and !orgPermsAllowPublishing([]), "the org list says where someone can publish") diff --git a/src/community/routes.osl b/src/community/routes.osl index f9e5b33..c848866 100644 --- a/src/community/routes.osl +++ b/src/community/routes.osl @@ -21,7 +21,8 @@ def registerCommunityRoutes(*serve.Router api) ( api.GET("/me/purchases", requireAuth, handleGetMyPurchases) - api.GET("/groups/:tag", handleGetMistWarpGroup) + api.GET("/orgs/:name", handleGetMistWarpOrg) + api.GET("/me/orgs", requireAuth, handleGetMyOrgs) api.GET("/development/pulls", handleDevelopmentPulls) api.GET("/roadmap", handleListIdeas) diff --git a/src/community/space-model.osl b/src/community/space-model.osl index b0d2aa0..5596fc1 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -124,7 +124,7 @@ def canManageSpace(object space,*serve.Context c) boolean ( if isSpaceOwner(space, c) ( return true ) - if canManageGroupContent(space, c) ( + if canManageOrgContent(space, c) ( return true ) return stringArrayContainsUser(spaceManagers(space), username) diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index d18f5c6..333b26a 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -115,7 +115,7 @@ def spaceListResponse(object space,*serve.Context c) object ( kind: space.kind, visibility: space.visibility, owner: space.owner, - groupTag: groupTagOf(space), + ownerType: if isOrgOwned(space) then "org" else "", edited: space.edited, startsAt: space.startsAt, endsAt: space.endsAt, diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 18864dd..21baae6 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -100,22 +100,15 @@ def handleGetSpace(*serve.Context c) ( def handleCreateSpace(*serve.Context c) ( object body = requestJSON(c) - number ownedSpaces = spaceDocs.where("ownerId", "==", contextString(c, "userId")).count() - if !contextBool(c, "isAdmin") and ownedSpaces >= mistwarpBenefitsForUserId(contextString(c, "userId")).maxSpaces.toNum() ( - c.json(413, {ok: false, error: "space limit reached; delete a space or upgrade your plan"}) + object owner = creationOwner(c, body, "spaces") + if !owner.ok ( + c.json(owner.status.toNum(), {ok: false, error: owner.error}) return ) - string groupTag = "" - if body.contains("groupTag") and body.groupTag != null and body.groupTag.toStr().strip() != "" ( - groupTag = normalizeGroupTag(body.groupTag.toStr()) - if groupTag == "" ( - c.badRequest("invalid group tag") - return - ) - if !canManageGroupTag(groupTag, c) ( - c.forbidden("you cannot create spaces for this group") - return - ) + number ownedSpaces = spaceDocs.where("ownerId", "==", owner.ownerId.toStr()).count() + if !contextBool(c, "isAdmin") and ownedSpaces >= mistwarpBenefitsForUserId(owner.ownerId.toStr()).maxSpaces.toNum() ( + c.json(413, {ok: false, error: "space limit reached; delete a space or upgrade your plan"}) + return ) string title = body.title.toStr().strip() string kind = body.kind.toStr().toLower().strip() @@ -170,9 +163,9 @@ def handleCreateSpace(*serve.Context c) ( description: description, kind: kind, visibility: visibility, - owner: contextString(c, "username"), - ownerId: contextString(c, "userId"), - groupTag: groupTag, + owner: owner.owner, + ownerId: owner.ownerId, + ownerType: owner.ownerType, managers: [], curatorInvites: [], projects: [], @@ -215,13 +208,18 @@ def handleUpdateSpace(*serve.Context c) ( ) object body = requestJSON(c) if body.contains("owner") ( - boolean canTransfer = isSpaceOwner(space, c) or canManageGroupContent(space, c) + boolean canTransfer = isSpaceOwner(space, c) or canManageOrgContent(space, c) if !canTransfer ( c.forbidden("you cannot transfer this space") return ) string requestedOwner = body.owner.toStr().strip() - string nextOwnerId = discoverUserIdentity(requestedOwner) + object identity = discoverUserIdentityOutcome(requestedOwner) + if identity.outcome == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) + return + ) + string nextOwnerId = identity.id.toStr() if nextOwnerId == "" ( c.badRequest("Rotur user not found") return @@ -231,29 +229,20 @@ def handleUpdateSpace(*serve.Context c) ( c.badRequest("Rotur user not found") return ) + boolean sameOwner = identityMatches((space.ownerId ?? "").toStr(), space.owner.toStr(), nextOwnerId, nextOwner) number nextOwnerLimit = mistwarpBenefitsForUserId(nextOwnerId).maxSpaces.toNum() - if !identityMatches((space.ownerId ?? "").toStr(), space.owner.toStr(), nextOwnerId, nextOwner) and spaceDocs.where("ownerId", "==", nextOwnerId).count() >= nextOwnerLimit ( + if !sameOwner and spaceDocs.where("ownerId", "==", nextOwnerId).count() >= nextOwnerLimit ( c.badRequest("the new owner has reached their space limit") return ) - space.owner = nextOwner - space.ownerId = nextOwnerId - if !body.contains("keepGroup") or body.keepGroup != true ( - space.groupTag = "" - ) - ) - if body.contains("groupTag") ( - string nextGroupTag = normalizeGroupTag(body.groupTag.toStr()) - if body.groupTag.toStr().strip() == "" ( - nextGroupTag = "" - ) else if nextGroupTag == "" ( - c.badRequest("invalid group tag") - return - ) else if !canManageGroupTag(nextGroupTag, c) ( - c.forbidden("you cannot move this space into that group") + boolean nextOwnerIsOrg = (identity.accountType ?? "").toStr() == "org" + if nextOwnerIsOrg and !sameOwner and !canPublishForOrg(nextOwner, c) ( + c.forbidden("you cannot move this space into that organisation") return ) - space.groupTag = nextGroupTag + space.owner = nextOwner + space.ownerId = nextOwnerId + space.ownerType = if nextOwnerIsOrg then "org" else "" ) if body.contains("title") ( string title = body.title.toStr().strip() @@ -525,8 +514,8 @@ def handleMySpaces(*serve.Context c) ( string spaceId = space["_id"].toStr() if !seen.contains(spaceId) ( boolean include = isSpaceOwner(space, c) - if !include and groupTagOf(space) != "" ( - include = canManageGroupContent(space, c) + if !include and isOrgOwned(space) ( + include = canManageOrgContent(space, c) ) if include ( seen[spaceId] = true diff --git a/src/projects/fork-visibility.test.osl b/src/projects/fork-visibility.test.osl index fe8bff6..a6e1592 100644 --- a/src/projects/fork-visibility.test.osl +++ b/src/projects/fork-visibility.test.osl @@ -28,7 +28,7 @@ def isBannedUser(string username) boolean ( return false ) -def canManageGroupContent(object project, object ctx) boolean ( +def canManageOrgContent(object project, object ctx) boolean ( return false ) @@ -102,7 +102,7 @@ def canEditProjectTest(object project, object ctx) boolean ( if ctx.isAdmin ( return true ) - if canManageGroupContent(project, ctx) ( + if canManageOrgContent(project, ctx) ( return true ) string role = projectRole(project, ctx.username.toStr()) diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index a532294..1bc6f7c 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -56,7 +56,7 @@ def canEditProject(object project,*serve.Context c) boolean ( if contextBool(c, "isAdmin") ( return true ) - if canManageGroupContent(project, c) ( + if canManageOrgContent(project, c) ( return true ) string role = projectRole(project, contextString(c, "username")) diff --git a/src/projects/project-create.osl b/src/projects/project-create.osl index e8463e0..5dca2ce 100644 --- a/src/projects/project-create.osl +++ b/src/projects/project-create.osl @@ -1,22 +1,14 @@ def handleCreateProject(*serve.Context c) ( object body = requestJSON(c) - string username = contextString(c, "username") - number projectLimit = mistwarpBenefitsForUserId(contextString(c, "userId")).maxProjects.toNum() - if !contextBool(c, "isAdmin") and ownedProjectSlotCount(contextString(c, "userId"), username) >= projectLimit ( - c.json(413, {ok: false, error: "project limit reached; delete a trashed project permanently or upgrade your plan"}) + object owner = creationOwner(c, body, "projects") + if !owner.ok ( + c.json(owner.status.toNum(), {ok: false, error: owner.error}) return ) - string groupTag = "" - if body.contains("groupTag") and body.groupTag != null and body.groupTag.toStr().strip() != "" ( - groupTag = normalizeGroupTag(body.groupTag.toStr()) - if groupTag == "" ( - c.badRequest("invalid group tag") - return - ) - if !canManageGroupTag(groupTag, c) ( - c.forbidden("you cannot create projects for this group") - return - ) + number projectLimit = mistwarpBenefitsForUserId(owner.ownerId.toStr()).maxProjects.toNum() + if !contextBool(c, "isAdmin") and ownedProjectSlotCount(owner.ownerId.toStr(), owner.owner.toStr()) >= projectLimit ( + c.json(413, {ok: false, error: "project limit reached; delete a trashed project permanently or upgrade your plan"}) + return ) string title = body.title.toStr().strip() @@ -51,9 +43,9 @@ def handleCreateProject(*serve.Context c) ( string id = generateId() object project = { id: id, - owner: username, - ownerId: contextString(c, "userId"), - groupTag: groupTag, + owner: owner.owner, + ownerId: owner.ownerId, + ownerType: owner.ownerType, branding: {}, vanitySlug: "", title: title, diff --git a/src/projects/project-discovery.osl b/src/projects/project-discovery.osl index 8a0566e..3d4b0ec 100644 --- a/src/projects/project-discovery.osl +++ b/src/projects/project-discovery.osl @@ -190,7 +190,7 @@ def sitemapUrl(string path) string ( def handleSitemap(*serve.Context c) ( array entries = projectsVisibleToEveryone(sharedIndexEntries()) entries.sortBy("views", "descending") - array staticPaths = ["/", "/explore", "/spaces", "/themes", "/groups", "/news", "/leaderboard", "/roadmap", "/compare"] + array staticPaths = ["/", "/explore", "/spaces", "/themes", "/news", "/leaderboard", "/roadmap", "/compare"] string sitemapXml = "" for i staticPaths.len ( sitemapXml ++= sitemapUrl(staticPaths[i].toStr()) diff --git a/src/projects/project-remix.test.osl b/src/projects/project-remix.test.osl index 5580c2c..57081b9 100644 --- a/src/projects/project-remix.test.osl +++ b/src/projects/project-remix.test.osl @@ -133,11 +133,11 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canManageGroupTag(string tag,*serve.Context c) boolean ( +def canPublishForOrg(string name, *serve.Context c) boolean ( return false ) -def groupTagOf(object value) string ( - return "" +def isOrgOwned(object value) boolean ( + return false ) def generateId() string ( ids += 1 diff --git a/src/projects/project-response.osl b/src/projects/project-response.osl index 7f8d7df..2246b49 100644 --- a/src/projects/project-response.osl +++ b/src/projects/project-response.osl @@ -193,7 +193,7 @@ def projectResponse(object project,*serve.Context c) object ( object response = { id: project.id, owner: project.owner, - groupTag: groupTagOf(project), + ownerType: if isOrgOwned(project) then "org" else "", branding: if project.contains("branding") then project.branding else {}, vanitySlug: activeVanity.slug.toStr(), title: project.title, diff --git a/src/projects/project-team.test.osl b/src/projects/project-team.test.osl index 9a70cfa..b7a853a 100644 --- a/src/projects/project-team.test.osl +++ b/src/projects/project-team.test.osl @@ -33,11 +33,11 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canManageGroupTag(string tag, *serve.Context c) boolean ( +def canPublishForOrg(string name, *serve.Context c) boolean ( return false ) -def groupTagOf(object value) string ( - return "" +def isOrgOwned(object value) boolean ( + return false ) def noStorageHold() object ( return {ok: true, reservations: []} diff --git a/src/projects/project-update-lookups.osl b/src/projects/project-update-lookups.osl index 6d5e0b8..9046274 100644 --- a/src/projects/project-update-lookups.osl +++ b/src/projects/project-update-lookups.osl @@ -65,20 +65,19 @@ def lookupVanityEligibility(UpdateLookups lookups, object holder) string ( return lookups.answers[key].toStr() ) -def lookupGroupManager(UpdateLookups lookups, *serve.Context c, string tag) boolean ( - string key = "group:" ++ tag +def lookupOrgPublisher(UpdateLookups lookups, *serve.Context c, string name) boolean ( + string key = "org-publisher:" ++ name.toLower().strip() if !lookupKnown(lookups, key) ( if lookups.replay ( return false ) - lookups.answers[key] = canManageGroupTag(tag, c) + lookups.answers[key] = canPublishForOrg(name, c) ) return lookups.answers[key] == true ) -def lookupGroupContentManager(UpdateLookups lookups, *serve.Context c, object project) boolean ( - string tag = groupTagOf(project) - return tag != "" and lookupGroupManager(lookups, c, tag) +def lookupOrgContentManager(UpdateLookups lookups, *serve.Context c, object project) boolean ( + return isOrgOwned(project) and lookupOrgPublisher(lookups, c, (project.owner ?? "").toStr()) ) def storageHoldKey(string userId, object changes, boolean enforce) string ( diff --git a/src/projects/project-update-lookups.test.osl b/src/projects/project-update-lookups.test.osl index ad55b48..426f0af 100644 --- a/src/projects/project-update-lookups.test.osl +++ b/src/projects/project-update-lookups.test.osl @@ -26,11 +26,11 @@ def vanityEligibility(object project) string ( asked.append("vanity " ++ project.id.toStr()) return "yes" ) -def canManageGroupTag(string tag, *serve.Context c) boolean ( +def canPublishForOrg(string name, *serve.Context c) boolean ( return true ) -def groupTagOf(object value) string ( - return (value.groupTag ?? "").toStr() +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" ) def noStorageHold() object ( return {ok: true, reservations: []} diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index 1bbe5c5..ca9b7c9 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -91,8 +91,6 @@ def applyAccessChanges(*serve.Context c, object project, object body, UpdateLook if isRefused(refusal) return refusal refusal = applyOwnerTransfer(c, project, body, transfer, lookups) if isRefused(refusal) return refusal - refusal = applyGroupTag(c, project, body, lookups) - if isRefused(refusal) return refusal object creatorBenefits = lookupProjectBenefits(lookups, project) refusal = applyBranding(project, body, creatorBenefits) if isRefused(refusal) return refusal @@ -128,7 +126,7 @@ def canEditProjectWith(*serve.Context c, object project, UpdateLookups lookups) if !contextBool(c, "authenticated") ( return false ) - if contextBool(c, "isAdmin") or lookupGroupContentManager(lookups, c, project) ( + if contextBool(c, "isAdmin") or lookupOrgContentManager(lookups, c, project) ( return true ) string role = projectRole(project, contextString(c, "username")) @@ -153,7 +151,7 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans if !body.contains("owner") ( return noRefusal() ) - boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupGroupContentManager(lookups, c, project) + boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupOrgContentManager(lookups, c, project) if !canTransfer ( return refuse(403, "you cannot transfer this project") ) @@ -175,33 +173,19 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans if !sameOwner and ownedProjectSlotCount(nextOwnerId, nextOwner) >= nextOwnerLimit ( return refuse(400, "the new owner has reached their project limit") ) + boolean nextOwnerIsOrg = (identity.accountType ?? "").toStr() == "org" + if nextOwnerIsOrg and !sameOwner and !lookupOrgPublisher(lookups, c, nextOwner) ( + return refuse(403, "you cannot move this project into that organisation") + ) if !sameOwner ( transfer.fromId = projectOwnerId(project) ) project.owner = nextOwner project.ownerId = nextOwnerId - if !body.contains("keepGroup") or body.keepGroup != true ( - project.groupTag = "" - ) + project.ownerType = if nextOwnerIsOrg then "org" else "" return noRefusal() ) -def applyGroupTag(*serve.Context c, object project, object body, UpdateLookups lookups) Refusal ( - if !body.contains("groupTag") ( - return noRefusal() - ) - string requestedGroupTag = (body.groupTag ?? "").toStr() - string nextGroupTag = normalizeGroupTag(requestedGroupTag) - if requestedGroupTag.strip() == "" ( - nextGroupTag = "" - ) else if nextGroupTag == "" ( - return refuse(400, "invalid group tag") - ) else if !lookupGroupManager(lookups, c, nextGroupTag) ( - return refuse(403, "you cannot move this project into that group") - ) - project.groupTag = nextGroupTag - return noRefusal() -) def vanitySlugHeldElsewhere(object project, string slug, UpdateLookups lookups) boolean ( array matches = vanityClaimEntries(slug) diff --git a/src/storage/storage.osl b/src/storage/storage.osl index c48db16..167e39d 100644 --- a/src/storage/storage.osl +++ b/src/storage/storage.osl @@ -179,10 +179,6 @@ def indexEntryFromProject(object project) object ( if project.contains("remixRoot") and project.remixRoot != null ( remixRoot = project.remixRoot.toStr() ) - string groupTag = "" - if project.contains("groupTag") and project.groupTag != null ( - groupTag = normalizeGroupTag(project.groupTag.toStr()) - ) number lastUploadAt = 0 if project.contains("lastUploadAt") and project.lastUploadAt != null ( lastUploadAt = project.lastUploadAt.toNum() @@ -196,7 +192,7 @@ def indexEntryFromProject(object project) object ( owner: project.owner, ownerId: ownerId, ownerKey: normalizeUsername(project.owner.toStr()), - groupTag: groupTag, + ownerType: if isOrgOwned(project) then "org" else "", vanityClaim: vanitySlug, vanitySlug: if (project.vanityLapsedAt ?? 0).toNum() > 0 then "" else vanitySlug, title: project.title, From 60ff2b8c4473036faf3fb16d7abdc1b6ddfa5563 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:46:10 +0000 Subject: [PATCH 02/28] Org publishers manage org-owned projects as owners --- src/projects/project-response.osl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/projects/project-response.osl b/src/projects/project-response.osl index 2246b49..b25bc86 100644 --- a/src/projects/project-response.osl +++ b/src/projects/project-response.osl @@ -282,7 +282,7 @@ def projectResponse(object project,*serve.Context c) object ( contributors: searchEntry.contributors, acceptedChanges: searchEntry.acceptedChanges } - response.myRole = projectRole(project, viewer) + response.myRole = if isOwner and isOrgOwned(project) and canManageOrgContent(project, c) then "owner" else projectRole(project, viewer) response.canSaveDirectly = canSaveLiveProject(project, c) if isOwner ( response.collaborators = collaborators From 04ce631312c2be19c1f0f1fee9820bca2dca57b1 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:14:57 +0000 Subject: [PATCH 03/28] Tie org content to the org's id, fan out its notifications and treat publishers as owners --- scripts/e2e_smoke.py | 8 +++ src/admin/errors.osl | 6 +- src/admin/project-moderation.osl | 4 +- src/community/challenges.osl | 58 +++++++++++++++--- src/community/comments.osl | 4 +- src/community/notifications.osl | 18 ++++++ src/community/notifications.test.osl | 25 ++++++++ src/community/org-page.osl | 20 +++++- src/community/orgs.osl | 62 ++++++++++++++----- src/community/orgs.test.osl | 64 +++++++++++++++++++- src/community/project-feedback.osl | 6 +- src/community/routes.osl | 4 +- src/community/space-comments.osl | 2 +- src/community/space-model.osl | 2 +- src/community/space-responses.osl | 2 +- src/community/spaces.osl | 35 +++++++---- src/games/game-marketplace.osl | 2 +- src/git/pulls.osl | 8 +-- src/git/pulls.test.osl | 6 ++ src/history/commit-management.osl | 6 +- src/projects/extensions.osl | 2 +- src/projects/extensions.test.osl | 3 + src/projects/live-collaboration.osl | 2 +- src/projects/monetize.osl | 2 +- src/projects/project-access.osl | 9 +++ src/projects/project-create.osl | 14 +++-- src/projects/project-publishing.osl | 8 ++- src/projects/project-remix.test.osl | 7 ++- src/projects/project-response.osl | 2 +- src/projects/project-team.test.osl | 7 ++- src/projects/project-trash.osl | 2 +- src/projects/project-update-lookups.osl | 28 ++++++--- src/projects/project-update-lookups.test.osl | 53 +++++++++++++++- src/projects/project-update.osl | 29 +++++++-- 34 files changed, 417 insertions(+), 93 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 567bb9b..8f08cac 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1041,8 +1041,16 @@ def org_flow(server, step, steps, ids): step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) step("org transfer back", "PUT", "/v1/projects/", "sam", {"owner": "dee"}) step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) + status, own_space = step("org own space create", "POST", "/v1/spaces", "sam", {"title": "Sam's space", "kind": "collection"}) + own_space = own_space.get("space", {}) if isinstance(own_space, dict) else {} + ids[str(own_space.get("_id", own_space.get("id", "")))] = "" + step("org space move refused for billing", "PUT", "/v1/spaces/", "alice", {"owner": "studio"}) + step("org space move", "PUT", "/v1/spaces/", "sam", {"owner": "studio"}) + step("org space managed by publisher", "PUT", "/v1/spaces/", "dee", {"title": "Studio collection"}) step("org page", "GET", "/v1/orgs/studio") step("org page as member", "GET", "/v1/orgs/studio", "dee") + step("org project delete by billing", "DELETE", path, "alice") + step("org project delete by publisher", "DELETE", path, "dee") def remix_sync_flow(server, step, steps, ids): diff --git a/src/admin/errors.osl b/src/admin/errors.osl index 9c30daf..b4ad06c 100644 --- a/src/admin/errors.osl +++ b/src/admin/errors.osl @@ -8,14 +8,14 @@ array siteErrorPathWords = [ "about", "account-frame.html", "addon-settings.html", "addons", "admin", "assignments", "bounties", "changes", "claim", "classroom", "commits", "compare", "dpa", "editor", "editor.html", "embed", "embed.html", "entry", "explore", "followers", "following", "fullscreen", "fullscreen.html", "groups", "index.html", "join", - "leaderboard", "library", "manage", "mystuff", "news", "notifications", "p", "perks", "player", "player.html", + "leaderboard", "library", "manage", "mystuff", "news", "notifications", "orgs", "p", "perks", "player", "player.html", "posts", "privacy", "project", "pulls", "purchases", "random", "remixes", "roadmap", "school", "search", "settings", "simple.html", "spaces", "stats", "status", "students", "subprocessors", "support", "terms", "themes", "trust", "users", "wallet" ] array siteErrorIdParents = [ - "assignments", "bounties", "claim", "commits", "entry", "groups", "join", "news", "p", "posts", "project", + "assignments", "bounties", "claim", "commits", "entry", "groups", "join", "news", "orgs", "p", "posts", "project", "pulls", "spaces", "students", "themes", "users" ] @@ -61,7 +61,7 @@ def siteErrorText(string text, string pageUrl, string scrubbedUrl) string ( value = regex.replace(regex.escape(page) ++ "([^A-Za-z0-9._~%/-]|$)", value, scrubbedUrl ++ "$1") ) value = regex.replace("(https?://[^[:space:]?#()<>\"']+)[?#][^[:space:]()<>\"']*?((:[0-9]+){1,2})?([[:space:])<>\"']|$)", value, "$1$2$4") - value = regex.replace("(?i)(https?://([a-z0-9-]+[.])*mistwarp[.]org)/(p|project|users|spaces|groups|bounties|news|posts|themes|claim|join)/[^/?#[:space:]:()<>\"']+", value, "$1/$3/:id") + value = regex.replace("(?i)(https?://([a-z0-9-]+[.])*mistwarp[.]org)/(p|project|users|orgs|spaces|groups|bounties|news|posts|themes|claim|join)/[^/?#[:space:]:()<>\"']+", value, "$1/$3/:id") value = regex.replace("(?i)(https?://editor[.]mistwarp[.]org)/[0-9]+", value, "$1/:id") value = regex.replace("(https?://avatars[.]rotur[.]dev)/[^/?#[:space:]:()<>\"']+", value, "$1/:id") value = regex.replace("(?i)/(users|blocks|mutes|followers|following|curators|invitations|judges|profiles?|projects|classes|students|teachers|claim|join|vanity|game-saves|library)/[^/?#[:space:]:()<>\"']+", value, "/$1/:id") diff --git a/src/admin/project-moderation.osl b/src/admin/project-moderation.osl index 38a3bd0..b60077e 100644 --- a/src/admin/project-moderation.osl +++ b/src/admin/project-moderation.osl @@ -351,7 +351,7 @@ def hideProjectForModeration(object project, string reason, string actor) ( ownerProfile.featuredProject = "" saveProfile(ownerProfile) ) - addNotification(project.owner.toStr(), actor, "project_hidden", {projectId: project.id, projectTitle: project.title, reason: reason}) + notifyContentOwner(project, actor, "project_hidden", {projectId: project.id, projectTitle: project.title, reason: reason}) ) def handleRestoreHiddenProject(*serve.Context c) ( @@ -383,6 +383,6 @@ def handleRestoreHiddenProject(*serve.Context c) ( ) saveProject(project) upsertIndexEntry(project) - addNotification(project.owner.toStr(), contextString(c, "username"), "project_restored", {projectId: project.id, projectTitle: project.title, visibility: visibility}) + notifyContentOwner(project, contextString(c, "username"), "project_restored", {projectId: project.id, projectTitle: project.title, visibility: visibility}) c.json(200, {ok: true, project: projectResponse(project, c)}) ) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 0813426..50d64a6 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -56,28 +56,66 @@ def challengeAudienceVotingEnabled(object space) boolean ( return challengeAudienceJudged(space) or (space.contains("communityVoting") and space.communityVoting == true) ) +def challengeOrgSnapshot(object space) object ( + if challengeAudienceJudged(space) or !isOrgOwned(space) ( + return {ok: false} + ) + object snapshot = roturOrgSnapshot((space.owner ?? "").toStr()) + string ownerId = (space.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return {ok: false} + ) + return snapshot +) + +def challengeOrgJudges(object space) array ( + object snapshot = challengeOrgSnapshot(space) + array listed = [] + array publishers = orgPublisherNames(snapshot) + array visible = orgPublicMemberNames(snapshot) + for i publishers.len ( + if stringArrayContainsUser(visible, publishers[i].toStr()) ( + listed.append(publishers[i]) + ) + ) + return listed +) + def challengeJudges(object space) array ( if challengeAudienceJudged(space) ( return [] ) array judges = challengeArray(space, "judges") - if isOrgOwned(space) ( - array members = orgPublicMemberNames(roturOrgSnapshot((space.owner ?? "").toStr())) - for i members.len ( - string member = members[i].toStr() - if !stringArrayContainsUser(judges, member) ( - judges.append(member) - ) + array members = challengeOrgJudges(space) + for i members.len ( + string member = members[i].toStr() + if !stringArrayContainsUser(judges, member) ( + judges.append(member) ) ) return judges ) +def challengeJudgeCount(object space) number ( + if challengeAudienceJudged(space) ( + return 0 + ) + array judges = challengeArray(space, "judges") + array publishers = orgPublisherNames(challengeOrgSnapshot(space)) + number count = judges.len + for i publishers.len ( + if !stringArrayContainsUser(judges, publishers[i].toStr()) ( + count += 1 + ) + ) + return count +) + def isChallengeJudge(object space, string username) boolean ( if stringArrayContainsUser(challengeJudges(space), username) ( return true ) - return !challengeAudienceJudged(space) and isOrgOwned(space) and orgHasMember(roturOrgSnapshot((space.owner ?? "").toStr()), "", username) + return stringArrayContainsUser(orgPublisherNames(challengeOrgSnapshot(space)), username) ) def isChallengeJudgeInvitee(object space, string username) boolean ( @@ -262,7 +300,7 @@ def handleJoinChallenge(*serve.Context c) ( space.edited = timestamp putSpaceDocument(space) if !isSpaceOwner(space, c) ( - addNotification(space.owner.toStr(), contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) + notifyContentOwner(space, contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) ) ) c.json(200, {ok: true, joined: true, participantCount: participants.len}) @@ -319,7 +357,7 @@ def handleRespondChallengeJudgeInvite(*serve.Context c) ( judges.append(contextString(c, "username")) ) space.judges = judges - addNotification(space.owner.toStr(), contextString(c, "username"), "challenge_judge_accepted", {spaceId: space["_id"], spaceTitle: space.title}) + notifyContentOwner(space, contextString(c, "username"), "challenge_judge_accepted", {spaceId: space["_id"], spaceTitle: space.title}) ) space.edited = timestamp putSpaceDocument(space) diff --git a/src/community/comments.osl b/src/community/comments.osl index 1a18f25..1b94c8f 100644 --- a/src/community/comments.osl +++ b/src/community/comments.osl @@ -621,9 +621,9 @@ def handleCreateProjectComment(*serve.Context c) ( ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(parentAuthor) ( if donationAmount > 0 ( - addNotification(project.owner.toStr(), commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}) + notifyContentOwner(project, commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}) ) else ( - addNotification(project.owner.toStr(), commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) + notifyContentOwner(project, commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) ) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), parentAuthor], {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 0840619..4ac3cd1 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -1,5 +1,6 @@ export { addNotification, + notifyContentOwner, loadNotifications, saveNotifications } @@ -448,3 +449,20 @@ def markNotificationsReadLocked(string username) ( ) saveNotifications(username, items) ) + +def notifyContentOwner(object content, string actor, string notifType, object extra) ( + string owner = (content.owner ?? "").toStr() + if !isOrgOwned(content) ( + addNotification(owner, actor, notifType, extra) + return + ) + object snapshot = roturOrgSnapshot(owner) + string ownerId = (content.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return + ) + array names = orgPublisherNames(snapshot) + for i names.len ( + addNotification(names[i].toStr(), actor, notifType, extra) + ) +) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index 59c2a55..f1a882b 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -85,6 +85,21 @@ def rewriteNotificationIdentityFields(object data, string oldKey, string newName return false ) +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" +) + +def roturOrgSnapshot(string name) object ( + if name == "studio" ( + return {ok: true, org: {id: "o_studio"}} + ) + return {ok: false, notOrg: true} +) + +def orgPublisherNames(object snapshot) array ( + return if snapshot.ok then ["ada", "bea"] else [] +) + import "./notifications.osl" def handleFakeNotification(*serve.Context c) ( @@ -127,3 +142,13 @@ messageRefused = ["student>owner"] addNotification("owner", "student", "comment", {projectId: "p4"}) testing.assert(askedRotur.len == 0, "a student's notification stays in MistWarp") testing.assert(loadNotifications("owner").len == 2, "and classroom rules, not Rotur's message signal, decide it") + +roturStatus = 200 +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p5"}) +testing.assert(askedRotur.len == 1 and askedRotur[1].toStr().contains("ada") and !askedRotur[1].toStr().contains("\"studio\""), "a love on an org's project goes to its other publishers, not the org account") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_taken", ownerType: "org"}, "zed", "love", {projectId: "p6"}) +testing.assert(askedRotur.len == 0, "content left by an org whose name was taken notifies nobody") +notifyContentOwner({owner: "sam", ownerType: ""}, "zed", "love", {projectId: "p7"}) +testing.assert(askedRotur.len == 1, "a person's content notifies them as before") diff --git a/src/community/org-page.osl b/src/community/org-page.osl index df57786..9647801 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -53,13 +53,29 @@ def handleGetMistWarpOrg(*serve.Context c) ( ok: true, org: orgProfileResponse(org), members: members, - projects: projectsVisibleTo(ownerIndexEntries((org.username ?? "").toStr(), canManage), c), + projects: projectsVisibleTo(orgProjectEntries(org, canManage), c), spaces: orgSpaces((org.id ?? "").toStr(), canManage, c), isMember: isMember, canManage: canManage }) ) +def orgProjectEntries(object org, boolean canManage) array ( + string orgId = (org.id ?? "").toStr() + array owned = [] + if orgId == "" ( + return owned + ) + array entries = ownerIndexEntries((org.username ?? "").toStr(), canManage) + for i entries.len ( + object entry = entries[i].assertElse(object, {}) + if (entry.ownerType ?? "").toStr() == "org" and (entry.ownerId ?? "").toStr() == orgId ( + owned.append(entry) + ) + ) + return owned +) + def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( array spaces = [] if orgId == "" ( @@ -69,7 +85,7 @@ def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( for i entries.len ( object space = entries[i].assertElse(object, {}) string visibility = (space.visibility ?? "").toStr() - if visibility == "public" or canManage ( + if visibility == "public" or visibility == "unlisted" or canManage ( spaces.append(spaceListResponse(space, c)) ) ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index f960935..91b0650 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -3,7 +3,10 @@ export { canPublishForOrg, creationOwner, isOrgOwned, + orgAccess, orgHasMember, + orgMemberCanPublish, + orgPublisherNames, orgPublicMemberNames, roturOrgSnapshot } @@ -13,7 +16,7 @@ export { def roturServiceGet(string path) object ( object failed = {body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false} - return requests.get(roturBase ++ path, {headers: {"X-Commerce-Key": commerceServiceKey}}).unwrapOr(failed) + return requests.get(roturBase ++ path, {headers: {"X-Commerce-Key": commerceServiceKey}, timeoutMs: 10000}).unwrapOr(failed) ) def roturOrgSnapshot(string rawName) object ( @@ -21,8 +24,9 @@ def roturOrgSnapshot(string rawName) object ( if name == "" or !isSafePathPart(name) ( return {ok: false, notOrg: true} ) - if orgSnapshotCache.has(name) ( - return orgSnapshotCache.get(name).assertElse(object, {ok: false, unavailable: true}) + object cached = orgSnapshotCache.get(name).assertElse(object, {}) + if cached.contains("ok") ( + return cached ) if commerceServiceKey == "" ( return {ok: false, unavailable: true} @@ -41,6 +45,9 @@ def roturOrgSnapshot(string rawName) object ( return {ok: false, unavailable: true} ) object data = parsed.unwrap().assert(object) + if (data.id ?? "").toStr() == "" or (data.username ?? "").toStr() == "" ( + return {ok: false, unavailable: true} + ) object snapshot = {ok: true, org: data, members: (data.members ?? []).assertElse(array, [])} orgSnapshotCache.set(name, snapshot) return snapshot @@ -85,18 +92,26 @@ def orgMemberCanPublish(object snapshot, string userId, string username) boolean return orgPermsAllowPublishing(orgMemberPerms(snapshot, userId, username)) ) -def canPublishForOrg(string name,*serve.Context c) boolean ( +def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( if !contextBool(c, "authenticated") ( - return false + return "no" + ) + if contextBool(c, "isAdmin") ( + return "yes" ) object snapshot = roturOrgSnapshot(name) if !snapshot.ok ( - return false + return if snapshot.contains("unavailable") and snapshot.unavailable == true then "unavailable" else "no" ) - if contextBool(c, "isAdmin") ( - return true + object org = snapshot.org.assertElse(object, {}) + if expectedOrgId != "" and (org.id ?? "").toStr() != expectedOrgId ( + return "no" ) - return orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) + return if orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) then "yes" else "no" +) + +def canPublishForOrg(string name,*serve.Context c) boolean ( + return orgAccess(name, "", c) == "yes" ) def isOrgOwned(object value) boolean ( @@ -104,7 +119,7 @@ def isOrgOwned(object value) boolean ( ) def canManageOrgContent(object value,*serve.Context c) boolean ( - return isOrgOwned(value) and canPublishForOrg((value.owner ?? "").toStr(), c) + return isOrgOwned(value) and orgAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) == "yes" ) def creationOwner(*serve.Context c, object body, string noun) object ( @@ -119,7 +134,7 @@ def creationOwner(*serve.Context c, object body, string noun) object ( if !snapshot.ok ( return {ok: false, status: 400, error: "organisation not found"} ) - if !canPublishForOrg(requestedOrg, c) ( + if !contextBool(c, "isAdmin") and !orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) ( return {ok: false, status: 403, error: "you cannot create " ++ noun ++ " for this organisation"} ) object org = snapshot.org.assertElse(object, {}) @@ -147,19 +162,38 @@ def orgPublicMemberNames(object snapshot) array ( return names ) +def orgPublisherNames(object snapshot) array ( + array names = [] + if !snapshot.ok ( + return names + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + string username = (member.username ?? "").toStr().strip() + if username != "" and orgMemberCanPublish(snapshot, (member.id ?? "").toStr(), username) and !stringArrayContainsUser(names, username) ( + names.append(username) + ) + ) + return names +) + def roturUserOrgs(string userId) object ( if userId == "" or !isSafePathPart(userId) ( return {ok: true, orgs: []} ) - if userOrgsCache.has(userId) ( - return userOrgsCache.get(userId).assertElse(object, {ok: false}) + object cached = userOrgsCache.get(userId).assertElse(object, {}) + if cached.contains("ok") ( + return cached ) if commerceServiceKey == "" ( return {ok: false} ) object response = roturServiceGet("/v2/integrations/mistwarp/users/" ++ url.escape(userId) ++ "/orgs") if response.status == 404 ( - return {ok: true, orgs: []} + object none = {ok: true, orgs: []} + userOrgsCache.set(userId, none) + return none ) if response.status != 200 ( return {ok: false} diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 06e8aff..8102c18 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -5,6 +5,8 @@ import "std:serve" import "std:thread" import "std:cache" import "std:url" +import "std:db" +import "std:fs" string roturBase = "http://127.0.0.1:18351" string commerceServiceKey = "mw-key" @@ -55,7 +57,35 @@ def contextBool(*serve.Context c, string key) boolean ( return false ) +string spaceDbPath = "/tmp/mistwarp-org-page-" ++ timestamp.toStr() ++ ".db" +*db.DB orgPageDb = db.open(spaceDbPath) +*db.Collection spaceDocs = orgPageDb.collection("spaces") +void spaceDocs.insertOne({_id: "s_pub", ownerId: "org_studio", visibility: "public", edited: 3}) +void spaceDocs.insertOne({_id: "s_unl", ownerId: "org_studio", visibility: "unlisted", edited: 2}) +void spaceDocs.insertOne({_id: "s_pri", ownerId: "org_studio", visibility: "private", edited: 1}) + +def ownerIndexEntries(string owner, boolean includeUnshared) array ( + array entries = [ + {id: "p_org", ownerId: "org_studio", ownerType: "org", shared: true}, + {id: "p_old", ownerId: "org_gone", ownerType: "org", shared: true}, + {id: "p_person", ownerId: "u_studio", ownerType: "", shared: true} + ] + if includeUnshared ( + entries.append({id: "p_draft", ownerId: "org_studio", ownerType: "org", shared: false}) + ) + return entries +) + +def projectsVisibleTo(array entries,*serve.Context c) array ( + return entries +) + +def spaceListResponse(object space,*serve.Context c) object ( + return {id: space["_id"]} +) + import "./orgs.osl" +import "./org-page.osl" object studio = { id: "org_studio", @@ -81,6 +111,10 @@ def handleFakeOrg(*serve.Context c) ( c.json(orgStatus, {error: "no"}) return ) + if c.param("name") == "broken" ( + c.json(200, {error: "half an answer"}) + return + ) if c.param("name") != "studio" ( c.json(404, {error: "Not an organisation", code: "not_org", not_org: true}) return @@ -98,7 +132,7 @@ def handleCheckPublish(*serve.Context c) ( ) def handleCheckContent(*serve.Context c) ( - c.json(200, {ok: canManageOrgContent({owner: "studio", ownerType: (c.query("kind") ?? "")}, c)}) + c.json(200, {ok: canManageOrgContent({owner: "studio", ownerId: (c.query("id") ?? ""), ownerType: (c.query("kind") ?? "")}, c)}) ) def handleCheckCreation(*serve.Context c) ( @@ -112,6 +146,7 @@ fakeRotur.GET("/check/publish/:name", handleCheckPublish) fakeRotur.GET("/check/content", handleCheckContent) fakeRotur.GET("/check/create", handleCheckCreation) fakeRotur.GET("/ready", handleFakeUserOrgs) +fakeRotur.GET("/page/:name", handleGetMistWarpOrg) def runFakeRotur() ( fakeRotur.run(":18351") @@ -179,3 +214,30 @@ testing.assert(orgs.ok and orgs.orgs.len == 2 and askedRotur == ["orgs of u_bea" void roturUserOrgs("u_bea") testing.assert(askedRotur.len == 1, "and are cached") testing.assert(orgPermsAllowPublishing(["apps"]) and !orgPermsAllowPublishing([]), "the org list says where someone can publish") + +testing.assert(ask("/check/content?kind=org&id=org_studio", "bea", "u_bea").ok == true, "a publisher manages content the org owns by id") +testing.assert(ask("/check/content?kind=org&id=org_gone", "bea", "u_bea").ok == false, "but not content left by an earlier org with the same name") +testing.assert(ask("/check/content?kind=org&id=org_gone", "zed", "u_zed").ok == false, "nor does anyone else") +object broken = roturOrgSnapshot("broken") +testing.assert(!broken.ok and broken.unavailable == true, "a 200 without an org in it is unavailable, not an empty org") + +def page(string user, string id) object ( + return ask("/page/studio", user, id) +) + +object anonymous = page("", "") +array anonymousMembers = anonymous.members.assert(array) +testing.assert(anonymousMembers.len == 2 and anonymousMembers[1].username == "ada" and anonymousMembers[2].username == "cal", "a visitor sees only the listed members") +testing.assert(anonymous.isMember == false and anonymous.canManage == false, "a visitor is neither member nor publisher") +testing.assert(anonymous.projects.assert(array).len == 1 and anonymous.projects[1].id == "p_org", "a visitor sees the org's shared projects, not an old org's or a person's") +testing.assert(anonymous.spaces.assert(array).len == 2, "a visitor sees public and unlisted spaces") + +object member = page("dee", "u_dee") +testing.assert(member.members.assert(array).len == 4 and member.isMember == true and member.canManage == false, "a member sees every member but cannot manage") +testing.assert(member.projects.assert(array).len == 1 and member.spaces.assert(array).len == 2, "a member without apps sees what visitors see") + +object publisher = page("bea", "u_bea") +testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts and private spaces") + +orgPageDb.close() +void fs.remove(spaceDbPath) diff --git a/src/community/project-feedback.osl b/src/community/project-feedback.osl index f3967ae..55e6d64 100644 --- a/src/community/project-feedback.osl +++ b/src/community/project-feedback.osl @@ -23,7 +23,7 @@ def handleCreateProjectFeedback(*serve.Context c) ( string feedbackId = project.id.toStr() ++ ":" ++ randomString(16) object feedback = {_id: feedbackId, projectId: project.id, type: feedbackType, message: message, status: "open", author: contextString(c, "username"), authorId: contextString(c, "userId"), created: timestamp, edited: timestamp} void feedbackDocs.insertOne(feedback) - addNotification(project.owner.toStr(), contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType}) + notifyContentOwner(project, contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType}) c.json(201, {ok: true}) ) @@ -121,7 +121,7 @@ def handleSaveProjectReview(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRole(project, contextString(c, "username")) == "owner" ( + if projectRoleFor(project, c) == "owner" ( c.badRequest("you cannot review your own project") return ) @@ -152,7 +152,7 @@ def handleSaveProjectReview(*serve.Context c) ( object review = {_id: reviewId, projectId: project.id, author: contextString(c, "username"), authorId: contextString(c, "userId"), authorKey: normalizeUsername(contextString(c, "username")), rating: rating, message: message, created: created, edited: timestamp} putDocument(reviewDocs, reviewId, review) if existing.len == 0 ( - addNotification(project.owner.toStr(), contextString(c, "username"), "project_review", {projectId: project.id, projectTitle: project.title, rating: rating}) + notifyContentOwner(project, contextString(c, "username"), "project_review", {projectId: project.id, projectTitle: project.title, rating: rating}) ) review.playtimeMs = authorPublicPlaytime(project.id.toStr(), review.author.toStr()) c.json(200, {ok: true, review: review}) diff --git a/src/community/routes.osl b/src/community/routes.osl index c848866..23ebaa0 100644 --- a/src/community/routes.osl +++ b/src/community/routes.osl @@ -21,8 +21,8 @@ def registerCommunityRoutes(*serve.Router api) ( api.GET("/me/purchases", requireAuth, handleGetMyPurchases) - api.GET("/orgs/:name", handleGetMistWarpOrg) - api.GET("/me/orgs", requireAuth, handleGetMyOrgs) + api.GET("/orgs/:name", serve.rateLimit({requests: 120, window: date.minute}), handleGetMistWarpOrg) + api.GET("/me/orgs", requireAuth, serve.rateLimit({requests: 120, window: date.minute}), handleGetMyOrgs) api.GET("/development/pulls", handleDevelopmentPulls) api.GET("/roadmap", handleListIdeas) diff --git a/src/community/space-comments.osl b/src/community/space-comments.osl index dbe4e53..4760b07 100644 --- a/src/community/space-comments.osl +++ b/src/community/space-comments.osl @@ -43,7 +43,7 @@ def handleCreateSpaceComment(*serve.Context c) ( addNotification(parentAuthor, commenter, "reply", notificationData) ) if normalizeUsername(space.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(space.owner.toStr()) != normalizeUsername(parentAuthor) ( - addNotification(space.owner.toStr(), commenter, "space_comment", notificationData) + notifyContentOwner(space, commenter, "space_comment", notificationData) ) notifyMentions(created.comment.content.toStr(), commenter, [space.owner.toStr(), parentAuthor], notificationData) c.json(201, created) diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 5596fc1..95a2be7 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -94,7 +94,7 @@ def isSpaceOwner(object space,*serve.Context c) boolean ( if space.contains("ownerId") and space.ownerId != null ( ownerId = space.ownerId.toStr() ) - return contextBool(c, "isAdmin") or identityMatches(ownerId, space.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) + return contextBool(c, "isAdmin") or identityMatches(ownerId, space.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) or canManageOrgContent(space, c) ) def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index 333b26a..51ab925 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -80,7 +80,7 @@ def spaceResponse(object space,*serve.Context c) object ( response.phase = challengePhase(space) response.isJudge = isChallengeJudge(space, contextString(c, "username")) response.judgeInvited = isChallengeJudgeInvitee(space, contextString(c, "username")) - response.judgeCount = challengeJudges(space).len + response.judgeCount = challengeJudgeCount(space) response.participantCount = challengeArray(space, "participants").len response.joined = stringArrayContainsUser(challengeArray(space, "participants"), contextString(c, "username")) response.judges = challengeJudges(space) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 21baae6..075c836 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -203,12 +203,16 @@ def handleUpdateSpace(*serve.Context c) ( return ) if !canManageSpace(space, c) ( + if isOrgOwned(space) and orgAccess(space.owner.toStr(), (space.ownerId ?? "").toStr(), c) == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) c.forbidden("you cannot manage this space") return ) object body = requestJSON(c) if body.contains("owner") ( - boolean canTransfer = isSpaceOwner(space, c) or canManageOrgContent(space, c) + boolean canTransfer = isSpaceOwner(space, c) if !canTransfer ( c.forbidden("you cannot transfer this space") return @@ -235,11 +239,24 @@ def handleUpdateSpace(*serve.Context c) ( c.badRequest("the new owner has reached their space limit") return ) - boolean nextOwnerIsOrg = (identity.accountType ?? "").toStr() == "org" - if nextOwnerIsOrg and !sameOwner and !canPublishForOrg(nextOwner, c) ( - c.forbidden("you cannot move this space into that organisation") + object nextOrg = roturOrgSnapshot(nextOwner) + boolean nextOrgUnknown = !nextOrg.ok and nextOrg.contains("unavailable") and nextOrg.unavailable == true + boolean nextOwnerIsOrg = nextOrg.ok + if (nextOrgUnknown and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) return ) + if nextOwnerIsOrg and !sameOwner ( + string access = orgAccess(nextOwner, nextOwnerId, c) + if access == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) + return + ) + if access != "yes" ( + c.forbidden("you cannot move this space into that organisation") + return + ) + ) space.owner = nextOwner space.ownerId = nextOwnerId space.ownerType = if nextOwnerIsOrg then "org" else "" @@ -428,7 +445,7 @@ def handleAddSpaceProject(*serve.Context c) ( ) space.edited = timestamp putSpaceDocument(space) - addNotification(space.owner.toStr(), contextString(c, "username"), "space_project", {spaceId: space["_id"], spaceTitle: space.title, projectId: project.id, projectTitle: project.title}) + notifyContentOwner(space, contextString(c, "username"), "space_project", {spaceId: space["_id"], spaceTitle: space.title, projectId: project.id, projectTitle: project.title}) ) c.json(200, {ok: true, space: spaceResponse(space, c)}) ) @@ -513,11 +530,7 @@ def handleMySpaces(*serve.Context c) ( object space = allSpaces[i].assert(object) string spaceId = space["_id"].toStr() if !seen.contains(spaceId) ( - boolean include = isSpaceOwner(space, c) - if !include and isOrgOwned(space) ( - include = canManageOrgContent(space, c) - ) - if include ( + if isSpaceOwner(space, c) ( seen[spaceId] = true stored.append(space) ) @@ -624,7 +637,7 @@ def handleRespondSpaceCuratorInvite(*serve.Context c) ( if accepted ( notificationType = "space_curator_accepted" ) - addNotification(space.owner.toStr(), username, notificationType, {spaceId: space["_id"], spaceTitle: space.title}) + notifyContentOwner(space, username, notificationType, {spaceId: space["_id"], spaceTitle: space.title}) c.json(200, {ok: true, accepted: accepted}) ) diff --git a/src/games/game-marketplace.osl b/src/games/game-marketplace.osl index 2efd032..af785aa 100644 --- a/src/games/game-marketplace.osl +++ b/src/games/game-marketplace.osl @@ -210,7 +210,7 @@ def completeGameProductPurchase(string key) object ( ) number paid = (entry.price ?? product.price).toNum() addPurchaseRecord(buyer, {projectId: project.id.toStr(), productId: product.id, title: product.name, seller: project.owner, amount: paid, at: timestamp, type: "game_product"}) - addNotification(project.owner.toStr(), buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: paid}) + notifyContentOwner(project, buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: paid}) ) forgetPurchase(key) return {ok: true, project: project, product: product} diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 505e796..29de37a 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -147,7 +147,7 @@ def isPullSourceOwnerWithSource(object pull, object source,*serve.Context c) boo if !contextBool(c, "authenticated") ( return false ) - if source.len > 0 and projectRole(source, contextString(c, "username")) == "owner" ( + if source.len > 0 and projectRoleFor(source, c) == "owner" ( return true ) return identityMatches( @@ -201,7 +201,7 @@ def createNativePull(*serve.Context c, object target, object source, string titl if !projectHasWorkspace(target) or !projectHasWorkspace(source) ( return {ok: false, status: 400, error: "both projects need MistWarp history before changes can be sent"} ) - if projectRole(source, contextString(c, "username")) != "owner" ( + if projectRoleFor(source, c) != "owner" ( return {ok: false, status: 403, error: "use a remix you own"} ) if source.remixParent.toStr() != target.id.toStr() ( @@ -227,7 +227,7 @@ def createNativePull(*serve.Context c, object target, object source, string titl ) object pull = inserted.pull.assert(object) sequence = pull.index.toNum() - addNotification(target.owner.toStr(), contextString(c, "username"), "contribution", {projectId: target.id, projectTitle: target.title, pull: sequence}) + notifyContentOwner(target, contextString(c, "username"), "contribution", {projectId: target.id, projectTitle: target.title, pull: sequence}) return {ok: true, pull: pullResponse(pull)} ) @@ -643,7 +643,7 @@ def handleCreatePullComment(*serve.Context c) ( addNotification(pull.author.toStr(), commenter, "comment", notificationData) ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(project.owner.toStr()) != normalizeUsername(pull.author.toStr()) ( - addNotification(project.owner.toStr(), commenter, "comment", notificationData) + notifyContentOwner(project, commenter, "comment", notificationData) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), pull.author.toStr()], notificationData) created.comment = commentResponse(created.comment.assert(object), commenter) diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index c365856..902d3d5 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -85,6 +85,12 @@ def contextString(*serve.Context c, string key) string ( def addNotification(string target, string actor, string kind, object payload) ( return ) +def notifyContentOwner(object content, string actor, string kind, object payload) ( + return +) +def projectRoleFor(object project,*serve.Context c) string ( + return projectRole(project, contextString(c, "username")) +) def canEditProject(object project,*serve.Context c) boolean ( return false diff --git a/src/history/commit-management.osl b/src/history/commit-management.osl index d0e37e7..2b0ded4 100644 --- a/src/history/commit-management.osl +++ b/src/history/commit-management.osl @@ -42,13 +42,13 @@ def normalizedCommitCoAuthors(array incoming) object ( return {ok: true, coAuthors: coAuthors} ) -def applyCommitPatch(string id, string sha, object body, string username, boolean isAdmin) object ( +def applyCommitPatch(string id, string sha, object body,*serve.Context c, boolean isAdmin) object ( auto loaded = loadProject(id) if !loaded.ok ( return {status: 404, error: "project not found"} ) object project = loaded.project.assert(object) - string role = projectRole(project, username) + string role = projectRoleFor(project, c) if !projectSourcePolicyAllows(project, role == "owner") ( return {status: 403, error: "only the owner can edit commits for this project"} ) @@ -110,7 +110,7 @@ def applyCommitPatchLocked(*serve.Context c) object ( string lockName = "project-history-" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) - return applyCommitPatch(c.param("id"), c.param("sha"), requestJSON(c), contextString(c, "username"), contextBool(c, "isAdmin")) + return applyCommitPatch(c.param("id"), c.param("sha"), requestJSON(c), c, contextBool(c, "isAdmin")) ) def handleGetCommitCollaborators(*serve.Context c) ( diff --git a/src/projects/extensions.osl b/src/projects/extensions.osl index 4545d17..b74152e 100644 --- a/src/projects/extensions.osl +++ b/src/projects/extensions.osl @@ -498,7 +498,7 @@ def unshareProjectForBlockedExtension(object project) boolean ( profile.featuredProject = "" saveProfile(profile) ) - addNotification(project.owner.toStr(), "MistWarp", "moderation", {message: "Your project \"" ++ project.title.toStr() ++ "\" uses an extension that has been blocked. Remove the extension before sharing the project again."}) + notifyContentOwner(project, "MistWarp", "moderation", {message: "Your project \"" ++ project.title.toStr() ++ "\" uses an extension that has been blocked. Remove the extension before sharing the project again."}) return true ) diff --git a/src/projects/extensions.test.osl b/src/projects/extensions.test.osl index 0424d01..2abd385 100644 --- a/src/projects/extensions.test.osl +++ b/src/projects/extensions.test.osl @@ -58,6 +58,9 @@ def saveProfile(object profile) boolean ( def addNotification(string target, string actor, string kind, object payload) ( return ) +def notifyContentOwner(object content, string actor, string kind, object payload) ( + addNotification((content.owner ?? "").toStr(), actor, kind, payload) +) def saveProject(object project) boolean ( return true ) diff --git a/src/projects/live-collaboration.osl b/src/projects/live-collaboration.osl index eefdf86..a35de25 100644 --- a/src/projects/live-collaboration.osl +++ b/src/projects/live-collaboration.osl @@ -73,7 +73,7 @@ def handleLiveCollaboration(*serve.Context c) ( ) object project = res.project.assert(object) string username = normalizeUsername(contextString(c, "username")) - string role = projectRole(project, username) + string role = projectRoleFor(project, c) if role == "" ( c.forbidden("only project team members can discover editing sessions") return diff --git a/src/projects/monetize.osl b/src/projects/monetize.osl index ea6bc44..8ec02dc 100644 --- a/src/projects/monetize.osl +++ b/src/projects/monetize.osl @@ -82,7 +82,7 @@ def projectSeeInside(object project) boolean ( ) def sourcePolicyAllowsViewer(object project,*serve.Context c) boolean ( - boolean owner = contextBool(c, "authenticated") and projectRole(project, contextString(c, "username")) == "owner" + boolean owner = contextBool(c, "authenticated") and projectRoleFor(project, c) == "owner" return projectSourcePolicyAllows(project, owner) ) diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 1bc6f7c..205f83e 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -7,6 +7,7 @@ export { projectJsonAccess, projectMustStayPrivate, projectRole, + projectRoleFor, removeString } @@ -63,6 +64,14 @@ def canEditProject(object project,*serve.Context c) boolean ( return role == "owner" or role == "maintainer" ) +def projectRoleFor(object project,*serve.Context c) string ( + string role = projectRole(project, contextString(c, "username")) + if role != "owner" and canManageOrgContent(project, c) ( + return "owner" + ) + return role +) + def canViewForkProject(object project,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false diff --git a/src/projects/project-create.osl b/src/projects/project-create.osl index 5dca2ce..6e6a8fa 100644 --- a/src/projects/project-create.osl +++ b/src/projects/project-create.osl @@ -90,9 +90,11 @@ def ownedProjectSlotCount(string userId, string username) number ( ) def projectFirstShared(object project) ( - addActivity(project.owner.toStr(), "share", {projectId: project.id, projectTitle: project.title}) + if !isOrgOwned(project) ( + addActivity(project.owner.toStr(), "share", {projectId: project.id, projectTitle: project.title}) + roturBadgeEvent(project.owner.toStr(), "project_shared", 0) + ) notifyPublishedRemix(project) - roturBadgeEvent(project.owner.toStr(), "project_shared", 0) ) def notifyPublishedRemix(object project) ( @@ -104,11 +106,13 @@ def notifyPublishedRemix(object project) ( return ) object parent = parentResult.project.assert(object) - addNotification(parent.owner.toStr(), project.owner.toStr(), "remix", {projectId: project.id, projectTitle: parent.title}) - if normalizeUsername(parent.owner.toStr()) != normalizeUsername(project.owner.toStr()) ( + notifyContentOwner(parent, project.owner.toStr(), "remix", {projectId: project.id, projectTitle: parent.title}) + if normalizeUsername(parent.owner.toStr()) != normalizeUsername(project.owner.toStr()) and !isOrgOwned(parent) ( roturBadgeEvent(parent.owner.toStr(), "remixed", 0) ) - addActivity(project.owner.toStr(), "remix", {projectId: project.id, projectTitle: project.title, parentId: parent.id, parentTitle: parent.title}) + if !isOrgOwned(project) ( + addActivity(project.owner.toStr(), "remix", {projectId: project.id, projectTitle: project.title, parentId: parent.id, parentTitle: parent.title}) + ) project.remixNotified = true saveProject(project) ) diff --git a/src/projects/project-publishing.osl b/src/projects/project-publishing.osl index 3c38ab9..ecf7ccd 100644 --- a/src/projects/project-publishing.osl +++ b/src/projects/project-publishing.osl @@ -194,10 +194,12 @@ def handleReactProjectLocked(*serve.Context c) ( ) upsertIndexEntry(project) - notifyLikeMilestones(project.owner.toStr(), "project", project.id.toStr(), previousLikes, loves.len, "/project/" ++ project.id.toStr(), {projectId: project.id, projectTitle: project.title}) + if !isOrgOwned(project) ( + notifyLikeMilestones(project.owner.toStr(), "project", project.id.toStr(), previousLikes, loves.len, "/project/" ++ project.id.toStr(), {projectId: project.id, projectTitle: project.title}) + ) if addedHeart ( - addNotification(project.owner.toStr(), viewer, "love", {projectId: project.id, projectTitle: project.title}) - if firstLove and normalizeUsername(viewer) != normalizeUsername(project.owner.toStr()) ( + notifyContentOwner(project, viewer, "love", {projectId: project.id, projectTitle: project.title}) + if firstLove and normalizeUsername(viewer) != normalizeUsername(project.owner.toStr()) and !isOrgOwned(project) ( roturBadgeEvent(project.owner.toStr(), "love_received", 0) ) addActivity(viewer, "love", {projectId: project.id, projectTitle: project.title, projectOwner: project.owner}) diff --git a/src/projects/project-remix.test.osl b/src/projects/project-remix.test.osl index 57081b9..45858b5 100644 --- a/src/projects/project-remix.test.osl +++ b/src/projects/project-remix.test.osl @@ -133,8 +133,11 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canPublishForOrg(string name, *serve.Context c) boolean ( - return false +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + return "no" +) +def roturOrgSnapshot(string name) object ( + return {ok: false, notOrg: true} ) def isOrgOwned(object value) boolean ( return false diff --git a/src/projects/project-response.osl b/src/projects/project-response.osl index b25bc86..fc1b943 100644 --- a/src/projects/project-response.osl +++ b/src/projects/project-response.osl @@ -282,7 +282,7 @@ def projectResponse(object project,*serve.Context c) object ( contributors: searchEntry.contributors, acceptedChanges: searchEntry.acceptedChanges } - response.myRole = if isOwner and isOrgOwned(project) and canManageOrgContent(project, c) then "owner" else projectRole(project, viewer) + response.myRole = projectRoleFor(project, c) response.canSaveDirectly = canSaveLiveProject(project, c) if isOwner ( response.collaborators = collaborators diff --git a/src/projects/project-team.test.osl b/src/projects/project-team.test.osl index b7a853a..71a10b4 100644 --- a/src/projects/project-team.test.osl +++ b/src/projects/project-team.test.osl @@ -33,8 +33,11 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canPublishForOrg(string name, *serve.Context c) boolean ( - return false +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + return "no" +) +def roturOrgSnapshot(string name) object ( + return {ok: false, notOrg: true} ) def isOrgOwned(object value) boolean ( return false diff --git a/src/projects/project-trash.osl b/src/projects/project-trash.osl index 01ac472..3d8546b 100644 --- a/src/projects/project-trash.osl +++ b/src/projects/project-trash.osl @@ -116,7 +116,7 @@ def handleDeleteProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRole(project, contextString(c, "username")) != "owner" and !contextBool(c, "isAdmin") ( + if projectRoleFor(project, c) != "owner" and !contextBool(c, "isAdmin") ( c.forbidden("not your project") return ) diff --git a/src/projects/project-update-lookups.osl b/src/projects/project-update-lookups.osl index 9046274..f54d913 100644 --- a/src/projects/project-update-lookups.osl +++ b/src/projects/project-update-lookups.osl @@ -65,19 +65,33 @@ def lookupVanityEligibility(UpdateLookups lookups, object holder) string ( return lookups.answers[key].toStr() ) -def lookupOrgPublisher(UpdateLookups lookups, *serve.Context c, string name) boolean ( - string key = "org-publisher:" ++ name.toLower().strip() +def lookupOrgAccess(UpdateLookups lookups, *serve.Context c, string name, string expectedOrgId) string ( + string key = "org-access:" ++ name.toLower().strip() ++ ":" ++ expectedOrgId if !lookupKnown(lookups, key) ( if lookups.replay ( - return false + return "unavailable" ) - lookups.answers[key] = canPublishForOrg(name, c) + lookups.answers[key] = orgAccess(name, expectedOrgId, c) ) - return lookups.answers[key] == true + return lookups.answers[key].toStr() +) + +def lookupOrgContentAccess(UpdateLookups lookups, *serve.Context c, object project) string ( + if !isOrgOwned(project) ( + return "no" + ) + return lookupOrgAccess(lookups, c, (project.owner ?? "").toStr(), (project.ownerId ?? "").toStr()) ) -def lookupOrgContentManager(UpdateLookups lookups, *serve.Context c, object project) boolean ( - return isOrgOwned(project) and lookupOrgPublisher(lookups, c, (project.owner ?? "").toStr()) +def lookupOrgSnapshot(UpdateLookups lookups, string name) object ( + string key = "org-snapshot:" ++ name.toLower().strip() + if !lookupKnown(lookups, key) ( + if lookups.replay ( + return {ok: false, unavailable: true} + ) + lookups.answers[key] = roturOrgSnapshot(name) + ) + return lookups.answers[key].assertElse(object, {ok: false, unavailable: true}) ) def storageHoldKey(string userId, object changes, boolean enforce) string ( diff --git a/src/projects/project-update-lookups.test.osl b/src/projects/project-update-lookups.test.osl index 426f0af..3605234 100644 --- a/src/projects/project-update-lookups.test.osl +++ b/src/projects/project-update-lookups.test.osl @@ -1,6 +1,8 @@ import "std:testing" import "std:json" import "std:serve" +import "std:requests" +import "std:thread" import "./project-refusal.osl" import "./project-update-lookups.osl" @@ -26,8 +28,13 @@ def vanityEligibility(object project) string ( asked.append("vanity " ++ project.id.toStr()) return "yes" ) -def canPublishForOrg(string name, *serve.Context c) boolean ( - return true +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + asked.append("org " ++ name ++ " " ++ expectedOrgId) + return if name == "busy" then "unavailable" else "yes" +) +def roturOrgSnapshot(string name) object ( + asked.append("snapshot " ++ name) + return {ok: true, org: {id: "o_" ++ name}} ) def isOrgOwned(object value) boolean ( return (value.ownerType ?? "").toStr() == "org" @@ -77,6 +84,48 @@ released = [] releaseStorageHolds(holds, "") testing.assert(released == ["u_a", "u_b"], "an unsaved update releases every hold") +def handleOrgLookups(*serve.Context c) ( + UpdateLookups orgs = UpdateLookups() + number before = asked.len + object answers = { + publisher: lookupOrgContentAccess(orgs, c, {owner: "Studio", ownerId: "o_studio", ownerType: "org"}), + person: lookupOrgContentAccess(orgs, c, {owner: "sam", ownerType: ""}), + busy: lookupOrgAccess(orgs, c, "busy", ""), + snapshot: lookupOrgSnapshot(orgs, "Studio").org.id, + livePassAsked: asked.len - before + } + orgs.replay = true + number replayBefore = asked.len + answers.replayed = lookupOrgAccess(orgs, c, "studio", "o_studio") + answers.replayedSnapshot = lookupOrgSnapshot(orgs, "studio").ok + answers.replayAsked = asked.len - replayBefore + answers.missedBefore = orgs.missed + answers.unknown = lookupOrgAccess(orgs, c, "other", "") + answers.missedAfter = orgs.missed + c.json(200, answers) +) + +*serve.Router lookupServer = serve.new() +lookupServer.GET("/orgs", handleOrgLookups) +def runLookupServer() ( + lookupServer.run(":18364") +) +thread.new(runLookupServer) +object orgResult = {} +for i 50 ( + auto attempt = requests.get("http://127.0.0.1:18364/orgs") + if attempt.isOk() ( + orgResult = json.parse(attempt.unwrap().body, {type: "object"}).unwrap().assert(object) + break + ) + wait 0.1 +) +testing.assert(orgResult.publisher == "yes" and orgResult.snapshot == "o_studio", "a publisher manages org content and an org is looked up") +testing.assert(orgResult.person == "no" and orgResult.livePassAsked == 3, "a person's content never asks Rotur about orgs") +testing.assert(orgResult.busy == "unavailable", "an unreachable Rotur is unavailable, not a refusal") +testing.assert(orgResult.replayed == "yes" and orgResult.replayedSnapshot == true and orgResult.replayAsked == 0 and orgResult.missedBefore == false, "org answers replay by name, whatever its case") +testing.assert(orgResult.unknown == "unavailable" and orgResult.missedAfter == true, "an org the live pass never asked about is a miss") + testing.assert(roturUnavailableRefusal("alice").status == 503 and roturUnavailableRefusal("alice").body.code == "rotur_unavailable", "an unreachable Rotur is a 503") object knownIdentities = {} diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index ca9b7c9..ea3baca 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -77,6 +77,9 @@ def finishProjectUpdate(*serve.Context c, object body, UpdateOutcome outcome) ( def applyProjectUpdate(*serve.Context c, object project, object body, UpdateLookups lookups, OwnerTransfer transfer) Refusal ( if !canEditProjectWith(c, project, lookups) ( + if contextBool(c, "authenticated") and lookupOrgContentAccess(lookups, c, project) == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) return refuse(403, "not your project") ) Refusal refusal = applyAccessChanges(c, project, body, lookups, transfer) @@ -126,7 +129,7 @@ def canEditProjectWith(*serve.Context c, object project, UpdateLookups lookups) if !contextBool(c, "authenticated") ( return false ) - if contextBool(c, "isAdmin") or lookupOrgContentManager(lookups, c, project) ( + if contextBool(c, "isAdmin") or lookupOrgContentAccess(lookups, c, project) == "yes" ( return true ) string role = projectRole(project, contextString(c, "username")) @@ -144,14 +147,14 @@ def updateScopeRefusal(*serve.Context c, object project, object body) Refusal ( ) def isOwnerOrAdmin(*serve.Context c, object project) boolean ( - return projectRole(project, contextString(c, "username")) == "owner" or contextBool(c, "isAdmin") + return projectRoleFor(project, c) == "owner" or contextBool(c, "isAdmin") ) def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTransfer transfer, UpdateLookups lookups) Refusal ( if !body.contains("owner") ( return noRefusal() ) - boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupOrgContentManager(lookups, c, project) + boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupOrgContentAccess(lookups, c, project) == "yes" if !canTransfer ( return refuse(403, "you cannot transfer this project") ) @@ -173,9 +176,23 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans if !sameOwner and ownedProjectSlotCount(nextOwnerId, nextOwner) >= nextOwnerLimit ( return refuse(400, "the new owner has reached their project limit") ) - boolean nextOwnerIsOrg = (identity.accountType ?? "").toStr() == "org" - if nextOwnerIsOrg and !sameOwner and !lookupOrgPublisher(lookups, c, nextOwner) ( - return refuse(403, "you cannot move this project into that organisation") + object nextOrg = lookupOrgSnapshot(lookups, nextOwner) + boolean nextOrgUnknown = !nextOrg.ok and nextOrg.contains("unavailable") and nextOrg.unavailable == true + if nextOrgUnknown and (identity.accountType ?? "").toStr() == "org" ( + return roturUnavailableRefusal(requestedOwner) + ) + boolean nextOwnerIsOrg = nextOrg.ok + if nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId ( + return roturUnavailableRefusal(requestedOwner) + ) + if nextOwnerIsOrg and !sameOwner ( + string access = lookupOrgAccess(lookups, c, nextOwner, nextOwnerId) + if access == "unavailable" ( + return roturUnavailableRefusal(requestedOwner) + ) + if access != "yes" ( + return refuse(403, "you cannot move this project into that organisation") + ) ) if !sameOwner ( transfer.fromId = projectOwnerId(project) From 75d7f0ae0f7b314f7915292278e8abf7231f2146 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:36:47 +0000 Subject: [PATCH 04/28] Let org publishers recover, moderate and collaborate on org content, and keep the org page read-only --- src/community/comments.osl | 4 ++-- src/community/notifications.osl | 10 +++++++++- src/community/notifications.test.osl | 7 +++++++ src/community/org-page.osl | 4 ++-- src/community/orgs.osl | 16 ++++++---------- src/community/orgs.test.osl | 18 ++++++------------ src/community/social.osl | 4 ++-- src/community/spaces.osl | 4 +++- src/git/pulls.osl | 2 +- src/git/pulls.test.osl | 3 +++ src/projects/live-collaboration.osl | 6 +++--- src/projects/project-access.osl | 22 ++++++++++++++++++++++ src/projects/project-trash.osl | 13 ++++++++++--- src/realtime/site-realtime.osl | 4 ++-- 14 files changed, 78 insertions(+), 39 deletions(-) diff --git a/src/community/comments.osl b/src/community/comments.osl index 1b94c8f..f29884b 100644 --- a/src/community/comments.osl +++ b/src/community/comments.osl @@ -649,7 +649,7 @@ def handleDeleteProjectComment(*serve.Context c) ( object project = res.project.assert(object) boolean requesterIsAdmin = contextBool(c, "isAdmin") - object deleted = deleteComment("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), project.owner.toStr(), requesterIsAdmin) + object deleted = deleteComment("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), projectModerator(project, c), requesterIsAdmin) if !deleted.ok ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return @@ -704,7 +704,7 @@ def handlePinProjectComment(*serve.Context c) ( if body.contains("pinned") and body.pinned != null ( pinned = body.pinned == true ) - object updated = setCommentPin("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), project.owner.toStr(), contextBool(c, "isAdmin"), pinned) + object updated = setCommentPin("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), projectModerator(project, c), contextBool(c, "isAdmin"), pinned) if !updated.ok ( c.json(updated.status.toInt(), {ok: false, error: updated.error}) return diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 4ac3cd1..9708c67 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -456,13 +456,21 @@ def notifyContentOwner(object content, string actor, string notifType, object ex addNotification(owner, actor, notifType, extra) return ) + thread.new(notifyOrgPublishers, owner, (content.ownerId ?? "").toStr(), actor, notifType, extra) +) + +number orgNotificationLimit = 25 + +def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra) ( object snapshot = roturOrgSnapshot(owner) - string ownerId = (content.ownerId ?? "").toStr() if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return ) array names = orgPublisherNames(snapshot) for i names.len ( + if i > orgNotificationLimit ( + return + ) addNotification(names[i].toStr(), actor, notifType, extra) ) ) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index f1a882b..37573e5 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -146,9 +146,16 @@ testing.assert(loadNotifications("owner").len == 2, "and classroom rules, not Ro roturStatus = 200 askedRotur = [] notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p5"}) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) testing.assert(askedRotur.len == 1 and askedRotur[1].toStr().contains("ada") and !askedRotur[1].toStr().contains("\"studio\""), "a love on an org's project goes to its other publishers, not the org account") askedRotur = [] notifyContentOwner({owner: "studio", ownerId: "o_taken", ownerType: "org"}, "zed", "love", {projectId: "p6"}) +wait 0.3 testing.assert(askedRotur.len == 0, "content left by an org whose name was taken notifies nobody") notifyContentOwner({owner: "sam", ownerType: ""}, "zed", "love", {projectId: "p7"}) testing.assert(askedRotur.len == 1, "a person's content notifies them as before") diff --git a/src/community/org-page.osl b/src/community/org-page.osl index 9647801..df14d32 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -66,10 +66,10 @@ def orgProjectEntries(object org, boolean canManage) array ( if orgId == "" ( return owned ) - array entries = ownerIndexEntries((org.username ?? "").toStr(), canManage) + array entries = projectSearchDocs.where("ownerId", "==", orgId).sort("edited", "desc").all() for i entries.len ( object entry = entries[i].assertElse(object, {}) - if (entry.ownerType ?? "").toStr() == "org" and (entry.ownerId ?? "").toStr() == orgId ( + if (entry.ownerType ?? "").toStr() == "org" and (entry.shared == true or canManage) ( owned.append(entry) ) ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 91b0650..ba4eefc 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -12,6 +12,7 @@ export { } *cache.Cache orgSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) +*cache.Cache orgUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) *cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) def roturServiceGet(string path) object ( @@ -28,7 +29,7 @@ def roturOrgSnapshot(string rawName) object ( if cached.contains("ok") ( return cached ) - if commerceServiceKey == "" ( + if commerceServiceKey == "" or orgUnavailableCache.get(name).assertElse(boolean, false) ( return {ok: false, unavailable: true} ) object response = roturServiceGet("/v2/integrations/mistwarp/orgs/" ++ url.escape(name)) @@ -37,15 +38,10 @@ def roturOrgSnapshot(string rawName) object ( orgSnapshotCache.set(name, missing) return missing ) - if response.status != 200 ( - return {ok: false, unavailable: true} - ) - auto parsed = json.parse(response.body, {type: "object"}) - if parsed.isErr() ( - return {ok: false, unavailable: true} - ) - object data = parsed.unwrap().assert(object) + auto parsed = json.parse(response.body ?? "", {type: "object"}) + object data = if response.status == 200 and parsed.isOk() then parsed.unwrap().assert(object) else {} if (data.id ?? "").toStr() == "" or (data.username ?? "").toStr() == "" ( + orgUnavailableCache.set(name, true) return {ok: false, unavailable: true} ) object snapshot = {ok: true, org: data, members: (data.members ?? []).assertElse(array, [])} @@ -223,7 +219,7 @@ def handleGetMyOrgs(*serve.Context c) ( username: (org.username ?? "").toStr(), displayName: (org.display_name ?? "").toStr(), perms: perms, - canPublish: orgPermsAllowPublishing(perms) + canPublish: org.admin == true or orgPermsAllowPublishing(perms) }) ) c.json(200, {ok: true, orgs: orgs}) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 8102c18..efb8936 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -64,17 +64,11 @@ void spaceDocs.insertOne({_id: "s_pub", ownerId: "org_studio", visibility: "publ void spaceDocs.insertOne({_id: "s_unl", ownerId: "org_studio", visibility: "unlisted", edited: 2}) void spaceDocs.insertOne({_id: "s_pri", ownerId: "org_studio", visibility: "private", edited: 1}) -def ownerIndexEntries(string owner, boolean includeUnshared) array ( - array entries = [ - {id: "p_org", ownerId: "org_studio", ownerType: "org", shared: true}, - {id: "p_old", ownerId: "org_gone", ownerType: "org", shared: true}, - {id: "p_person", ownerId: "u_studio", ownerType: "", shared: true} - ] - if includeUnshared ( - entries.append({id: "p_draft", ownerId: "org_studio", ownerType: "org", shared: false}) - ) - return entries -) +*db.Collection projectSearchDocs = orgPageDb.collection("projects") +void projectSearchDocs.insertOne({_id: "p_org", id: "p_org", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: true, edited: 4}) +void projectSearchDocs.insertOne({_id: "p_old", id: "p_old", ownerId: "org_gone", ownerKey: "studio", ownerType: "org", shared: true, edited: 3}) +void projectSearchDocs.insertOne({_id: "p_person", id: "p_person", ownerId: "u_studio", ownerKey: "studio", ownerType: "", shared: true, edited: 2}) +void projectSearchDocs.insertOne({_id: "p_draft", id: "p_draft", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: false, edited: 1}) def projectsVisibleTo(array entries,*serve.Context c) array ( return entries @@ -187,7 +181,7 @@ orgStatus = 500 object down = roturOrgSnapshot("busy") testing.assert(!down.ok and down.unavailable == true, "a Rotur error is reported as unavailable") void roturOrgSnapshot("busy") -testing.assert(askedRotur.len == 4, "an unavailable answer is not cached") +testing.assert(askedRotur.len == 3, "an unavailable answer is remembered briefly, so a list of spaces doesn't ask again for each") orgStatus = 200 testing.assert(isOrgOwned({ownerType: "org"}) and !isOrgOwned({ownerType: ""}) and !isOrgOwned({}), "only content marked as org-owned is") diff --git a/src/community/social.osl b/src/community/social.osl index 4b00137..db22a54 100644 --- a/src/community/social.osl +++ b/src/community/social.osl @@ -51,7 +51,7 @@ def ownerIndexEntries(string owner, boolean includeUnshared) array ( for i keyMatches.len ( object entry = keyMatches[i].assert(object) string pid = entry.id.toStr() - if ownerId != "" and (entry.ownerId ?? "").toStr() != ownerId ( + if ownerId != "" and (entry.ownerId ?? "").toStr() != ownerId and (entry.ownerType ?? "").toStr() != "org" ( entry.ownerId = ownerId putDocument(projectSearchDocs, entry["_id"].toStr(), entry) auto loaded = loadProject(pid) @@ -391,7 +391,7 @@ def handleUpdateProfile(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRole(project, username) != "owner" ( + if projectRoleFor(project, c) != "owner" ( c.forbidden("not your project") return ) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 075c836..e784476 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -734,6 +734,8 @@ def handleReactSpaceLocked(*serve.Context c) ( c.internalError("could not save reaction") return ) - notifyLikeMilestones(space.owner.toStr(), space.kind.toStr(), space["_id"].toStr(), previousLikes, likes.len, "/spaces/" ++ space["_id"].toStr(), {}) + if !isOrgOwned(space) ( + notifyLikeMilestones(space.owner.toStr(), space.kind.toStr(), space["_id"].toStr(), previousLikes, likes.len, "/spaces/" ++ space["_id"].toStr(), {}) + ) c.json(200, {ok: true, likeCount: likes.len, brokenHeartCount: brokenHearts.len, myReaction: if hadReaction then "" else reactionType}) ) diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 29de37a..26ad58e 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -662,7 +662,7 @@ def handleDeletePullComment(*serve.Context c) ( return ) object project = res.project.assert(object) - object deleted = deleteComment(pullCommentKey(pull), c.param("cid"), contextString(c, "username"), project.owner.toStr(), contextBool(c, "isAdmin")) + object deleted = deleteComment(pullCommentKey(pull), c.param("cid"), contextString(c, "username"), projectModerator(project, c), contextBool(c, "isAdmin")) if !deleted.ok ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index 902d3d5..ee7e275 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -88,6 +88,9 @@ def addNotification(string target, string actor, string kind, object payload) ( def notifyContentOwner(object content, string actor, string kind, object payload) ( return ) +def projectModerator(object project,*serve.Context c) string ( + return project.owner.toStr() +) def projectRoleFor(object project,*serve.Context c) string ( return projectRole(project, contextString(c, "username")) ) diff --git a/src/projects/live-collaboration.osl b/src/projects/live-collaboration.osl index a35de25..1a77302 100644 --- a/src/projects/live-collaboration.osl +++ b/src/projects/live-collaboration.osl @@ -39,7 +39,7 @@ def liveSession(object project, string branch) object ( if session.getKeys().len == 0 or session.expires.toNum() <= timestamp ( return {} ) - string role = projectRole(project, session.host.toStr()) + string role = projectRoleForName(project, session.host.toStr()) if !isSharedEditorRole(role) ( return {} ) @@ -92,7 +92,7 @@ def handleLiveCollaboration(*serve.Context c) ( object session = liveSession(project, branch) object editors = projectEditorPresence.get(project.id.toStr()).assertElse(object, {}) for key in editors.getKeys() ( - if editors[key].expires.toNum() <= timestamp or projectRole(project, editors[key].username.toStr()) == "" ( + if editors[key].expires.toNum() <= timestamp or projectRoleForName(project, editors[key].username.toStr()) == "" ( editors.delete(key) ) ) @@ -108,7 +108,7 @@ def handleLiveCollaboration(*serve.Context c) ( if session.getKeys().len != 0 ( object activeMembers = session.members.assert(object) for key in activeMembers.getKeys() ( - string memberRole = projectRole(project, key) + string memberRole = projectRoleForName(project, key) if activeMembers[key].expires.toNum() <= timestamp or memberRole == "" ( activeMembers.delete(key) ) diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 205f83e..794c73b 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -5,9 +5,11 @@ export { canViewProjectJson, ensureViewKey, projectJsonAccess, + projectModerator, projectMustStayPrivate, projectRole, projectRoleFor, + projectRoleForName, removeString } @@ -72,6 +74,26 @@ def projectRoleFor(object project,*serve.Context c) string ( return role ) +def projectModerator(object project,*serve.Context c) string ( + if canManageOrgContent(project, c) ( + return contextString(c, "username") + ) + return project.owner.toStr() +) + +def projectRoleForName(object project, string username) string ( + string role = projectRole(project, username) + if role == "owner" or username == "" or !isOrgOwned(project) ( + return role + ) + object snapshot = roturOrgSnapshot(project.owner.toStr()) + string ownerId = (project.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return role + ) + return if orgMemberCanPublish(snapshot, "", username) then "owner" else role +) + def canViewForkProject(object project,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false diff --git a/src/projects/project-trash.osl b/src/projects/project-trash.osl index 3d8546b..72196c0 100644 --- a/src/projects/project-trash.osl +++ b/src/projects/project-trash.osl @@ -177,6 +177,13 @@ def purgeExpiredTrash() ( ) ) +def canManageTrashedProject(object project,*serve.Context c) boolean ( + if contextBool(c, "isAdmin") or canManageOrgContent(project, c) ( + return true + ) + return identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) +) + def handleGetMyTrash(*serve.Context c) ( purgeExpiredTrash() array projects = [] @@ -190,7 +197,7 @@ def handleGetMyTrash(*serve.Context c) ( if res.ok ( object project = res.data.assert(object) string ownerId = (project.ownerId ?? "").toStr() - if identityMatches(ownerId, project.owner.toStr(), userId, username) ( + if identityMatches(ownerId, project.owner.toStr(), userId, username) or canManageOrgContent(project, c) ( projects.append({ id: project.id, title: project.title, @@ -214,7 +221,7 @@ def handleRestoreProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if !identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) and !contextBool(c, "isAdmin") ( + if !canManageTrashedProject(project, c) ( c.forbidden("not your project") return ) @@ -246,7 +253,7 @@ def handlePurgeTrashedProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if !identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) and !contextBool(c, "isAdmin") ( + if !canManageTrashedProject(project, c) ( c.forbidden("not your project") return ) diff --git a/src/realtime/site-realtime.osl b/src/realtime/site-realtime.osl index 3bafc5b..cb5bfa8 100644 --- a/src/realtime/site-realtime.osl +++ b/src/realtime/site-realtime.osl @@ -36,7 +36,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return false ) if isStudentUserId((conn.Get("userId") ?? "").toStr()) ( - return projectRole(project, conn.Get("username").toStr()) != "" + return projectRoleForName(project, conn.Get("username").toStr()) != "" ) if projectIsViewable(project) ( return true @@ -45,7 +45,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return true ) if conn.Get("authenticated") == true ( - return projectRole(project, conn.Get("username").toStr()) != "" + return projectRoleForName(project, conn.Get("username").toStr()) != "" ) return false ) From 66a71290a8b4fed1ff2b73cb5548cca9eb193a98 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:06:25 +0000 Subject: [PATCH 05/28] Treat org publishers as entry owners, refuse moves to orgs Rotur can't confirm, and dedupe org fan-outs --- scripts/e2e_smoke.py | 8 +++++++- src/community/notifications.osl | 9 ++++++++- src/community/notifications.test.osl | 13 +++++++++++++ src/community/orgs.osl | 5 ----- src/community/orgs.test.osl | 2 +- src/community/social.osl | 2 +- src/community/space-model.osl | 2 +- src/community/spaces.osl | 3 +-- src/git/pulls.osl | 8 +++++++- src/projects/monetize.osl | 2 +- src/projects/project-update.osl | 3 +-- 11 files changed, 41 insertions(+), 16 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 8f08cac..f986247 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -44,13 +44,14 @@ ], }, } +GHOST_ORGS = {"ghoststudio": "o_ghost"} GONE_USERS = {"gone_user"} BUSY_USERS = {"busy_user"} BANNED_USERS = {"banned_user"} SLOW_USERS = {"slow_user": "u_slow"} SLOW_LEDGER_USERS = {"u_lena"} ROTUR_DELAY = 4 -EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} +EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure", "org transfer to an org Rotur can't vouch for", "org space move to an org Rotur can't vouch for"} CHECK_STEPS = {"sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} @@ -106,6 +107,9 @@ def do_GET(self): if name in ORGS: self.answer(200, {"id": ORGS[name]["id"], "username": name, "account_type": "org"}) return + if name in GHOST_ORGS: + self.answer(200, {"id": GHOST_ORGS[name], "username": name, "account_type": "org"}) + return if name in GONE_USERS: self.answer(404, {"error": "User not found"}) return @@ -1036,6 +1040,7 @@ def org_flow(server, step, steps, ids): status, mine = step("org own create", "POST", "/v1/projects", "bob", {"title": "Bob's game"}) ids[str(mine.get("id", "")) if isinstance(mine, dict) else ""] = "" step("org transfer refused for an outsider", "PUT", "/v1/projects/", "bob", {"owner": "studio"}) + step("org transfer to an org Rotur can't vouch for", "PUT", "/v1/projects/", "bob", {"owner": "ghoststudio"}) status, given = step("org transfer by member", "POST", "/v1/projects", "dee", {"title": "Dee's game"}) ids[str(given.get("id", "")) if isinstance(given, dict) else ""] = "" step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) @@ -1045,6 +1050,7 @@ def org_flow(server, step, steps, ids): own_space = own_space.get("space", {}) if isinstance(own_space, dict) else {} ids[str(own_space.get("_id", own_space.get("id", "")))] = "" step("org space move refused for billing", "PUT", "/v1/spaces/", "alice", {"owner": "studio"}) + step("org space move to an org Rotur can't vouch for", "PUT", "/v1/spaces/", "sam", {"owner": "ghoststudio"}) step("org space move", "PUT", "/v1/spaces/", "sam", {"owner": "studio"}) step("org space managed by publisher", "PUT", "/v1/spaces/", "dee", {"title": "Studio collection"}) step("org page", "GET", "/v1/orgs/studio") diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 9708c67..a5f1cd7 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -456,10 +456,17 @@ def notifyContentOwner(object content, string actor, string notifType, object ex addNotification(owner, actor, notifType, extra) return ) - thread.new(notifyOrgPublishers, owner, (content.ownerId ?? "").toStr(), actor, notifType, extra) + string ownerId = (content.ownerId ?? "").toStr() + string fanOutKey = ownerId ++ ":" ++ owner ++ ":" ++ actor ++ ":" ++ notifType ++ ":" ++ extra.toStr() + if recentOrgFanOuts.get(fanOutKey).assertElse(boolean, false) ( + return + ) + recentOrgFanOuts.set(fanOutKey, true) + thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra) ) number orgNotificationLimit = 25 +*cache.Cache recentOrgFanOuts = cache.new({capacity: 10000, ttl: 600000}) def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra) ( object snapshot = roturOrgSnapshot(owner) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index 37573e5..b58047d 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -4,6 +4,7 @@ import "std:json" import "std:requests" import "std:serve" import "std:thread" +import "std:cache" string notificationsDir = "notifications/" string editorOrigin = "https://mistwarp.org" @@ -159,3 +160,15 @@ wait 0.3 testing.assert(askedRotur.len == 0, "content left by an org whose name was taken notifies nobody") notifyContentOwner({owner: "sam", ownerType: ""}, "zed", "love", {projectId: "p7"}) testing.assert(askedRotur.len == 1, "a person's content notifies them as before") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p5"}) +wait 0.3 +testing.assert(askedRotur.len == 0, "the same love toggled again soon doesn't fan out to the publishers twice") +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p8"}) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) +testing.assert(askedRotur.len == 1, "a love on another of the org's projects still fans out") diff --git a/src/community/orgs.osl b/src/community/orgs.osl index ba4eefc..822b47b 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -1,6 +1,5 @@ export { canManageOrgContent, - canPublishForOrg, creationOwner, isOrgOwned, orgAccess, @@ -106,10 +105,6 @@ def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( return if orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) then "yes" else "no" ) -def canPublishForOrg(string name,*serve.Context c) boolean ( - return orgAccess(name, "", c) == "yes" -) - def isOrgOwned(object value) boolean ( return (value.ownerType ?? "").toStr() == "org" ) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index efb8936..6a43934 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -122,7 +122,7 @@ def handleFakeUserOrgs(*serve.Context c) ( ) def handleCheckPublish(*serve.Context c) ( - c.json(200, {ok: canPublishForOrg(c.param("name"), c)}) + c.json(200, {ok: orgAccess(c.param("name"), "", c) == "yes"}) ) def handleCheckContent(*serve.Context c) ( diff --git a/src/community/social.osl b/src/community/social.osl index db22a54..598c5a8 100644 --- a/src/community/social.osl +++ b/src/community/social.osl @@ -391,7 +391,7 @@ def handleUpdateProfile(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRoleFor(project, c) != "owner" ( + if projectRole(project, username) != "owner" ( c.forbidden("not your project") return ) diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 95a2be7..3305027 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -102,7 +102,7 @@ def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( if project.contains("ownerId") and project.ownerId != null ( ownerId = project.ownerId.toStr() ) - return identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) + return identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) or canManageOrgContent(project, c) ) def isSpaceInvitee(object space,*serve.Context c) boolean ( diff --git a/src/community/spaces.osl b/src/community/spaces.osl index e784476..d1de72e 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -240,9 +240,8 @@ def handleUpdateSpace(*serve.Context c) ( return ) object nextOrg = roturOrgSnapshot(nextOwner) - boolean nextOrgUnknown = !nextOrg.ok and nextOrg.contains("unavailable") and nextOrg.unavailable == true boolean nextOwnerIsOrg = nextOrg.ok - if (nextOrgUnknown and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( + if (!nextOrg.ok and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) return ) diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 26ad58e..5893962 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -1253,7 +1253,13 @@ def completeNativePull(object project, string pullIndex, string expectedHead, st project.mergedContributors = mergedContributors saveProject(project) upsertIndexEntry(project) - addNotification(pull.sourceOwner.toStr(), project.owner.toStr(), "contribution_merged", {projectId: project.id, projectTitle: project.title, pull: pull.index}) + object mergedNotice = {projectId: project.id, projectTitle: project.title, pull: pull.index} + object sourceLoad = loadProject((pull.sourceProjectId ?? "").toStr()) + if sourceLoad.ok and identityMatches((pull.sourceOwnerId ?? "").toStr(), pull.sourceOwner.toStr(), (sourceLoad.project.ownerId ?? "").toStr(), (sourceLoad.project.owner ?? "").toStr()) ( + notifyContentOwner(sourceLoad.project.assert(object), project.owner.toStr(), "contribution_merged", mergedNotice) + ) else ( + addNotification(pull.sourceOwner.toStr(), project.owner.toStr(), "contribution_merged", mergedNotice) + ) if pull.contains("bountyId") and pull.bountyId != null and pull.bountyId.toStr() != "" ( boolean bountyPaid = awardContributionBounty(pull.bountyId.toStr(), project.id.toStr(), pull.sourceOwner.toStr()) if !bountyPaid ( diff --git a/src/projects/monetize.osl b/src/projects/monetize.osl index 8ec02dc..b3371a5 100644 --- a/src/projects/monetize.osl +++ b/src/projects/monetize.osl @@ -476,7 +476,7 @@ def completeProjectPurchase(string key) object ( upsertIndexEntry(project) siteBroadcastStats(project.id.toStr(), buyer, {saved: true}) addPurchaseRecord(buyer, {projectId: project.id.toStr(), title: project.title, seller: seller, amount: owed, at: timestamp}) - addNotification(seller, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) + notifyContentOwner(project, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) ) forgetPurchase(key) return {ok: true, project: project} diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index ea3baca..8dfa323 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -177,8 +177,7 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans return refuse(400, "the new owner has reached their project limit") ) object nextOrg = lookupOrgSnapshot(lookups, nextOwner) - boolean nextOrgUnknown = !nextOrg.ok and nextOrg.contains("unavailable") and nextOrg.unavailable == true - if nextOrgUnknown and (identity.accountType ?? "").toStr() == "org" ( + if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" ( return roturUnavailableRefusal(requestedOwner) ) boolean nextOwnerIsOrg = nextOrg.ok From 3ee875298bfaf84248afb5316b5f776eec0312bc Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:43:10 +0000 Subject: [PATCH 06/28] Keep org projects off same-named personal accounts, count the submitting publisher as the challenge participant, and give creation refusals a code --- src/auth/user-identity.osl | 2 +- src/community/org-page.osl | 2 +- src/community/orgs.osl | 13 +++++++------ src/community/orgs.test.osl | 1 + src/community/social.osl | 6 +++++- src/community/space-model.osl | 3 --- src/community/spaces.osl | 10 +++++++--- src/projects/project-create.osl | 2 +- 8 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/auth/user-identity.osl b/src/auth/user-identity.osl index 32c755f..597f17b 100644 --- a/src/auth/user-identity.osl +++ b/src/auth/user-identity.osl @@ -464,7 +464,7 @@ def backfillOwnerIdForUserProjects(string userId, string username) ( array matches = projectSearchDocs.where("ownerKey", "==", ownerKey).all() for i matches.len ( object entry = matches[i].assert(object) - if (entry.ownerId ?? "").toStr() != userId ( + if (entry.ownerType ?? "").toStr() != "org" and (entry.ownerId ?? "").toStr() != userId ( entry.ownerId = userId putDocument(projectSearchDocs, entry["_id"].toStr(), entry) auto loaded = loadProject(entry.id.toStr()) diff --git a/src/community/org-page.osl b/src/community/org-page.osl index df14d32..8ce3b52 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -43,7 +43,7 @@ def handleGetMistWarpOrg(*serve.Context c) ( array all = snapshot.members.assertElse(array, []) for i all.len ( object member = all[i].assertElse(object, {}) - if member.public == true or isMember ( + if member.public == true or isMember or contextBool(c, "isAdmin") ( members.append(orgMemberResponse(member)) ) ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 822b47b..b73c593 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -120,19 +120,19 @@ def creationOwner(*serve.Context c, object body, string noun) object ( ) object snapshot = roturOrgSnapshot(requestedOrg) if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( - return {ok: false, status: 503, error: "Rotur can't be reached right now. Try again soon."} + return {ok: false, status: 503, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."} ) if !snapshot.ok ( - return {ok: false, status: 400, error: "organisation not found"} + return {ok: false, status: 400, code: "org_not_found", error: "organisation not found"} ) if !contextBool(c, "isAdmin") and !orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) ( - return {ok: false, status: 403, error: "you cannot create " ++ noun ++ " for this organisation"} + return {ok: false, status: 403, code: "org_forbidden", error: "you cannot create " ++ noun ++ " for this organisation"} ) object org = snapshot.org.assertElse(object, {}) string orgId = (org.id ?? "").toStr() string orgName = (org.username ?? "").toStr() if orgId == "" or orgName == "" ( - return {ok: false, status: 503, error: "Rotur can't be reached right now. Try again soon."} + return {ok: false, status: 503, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."} ) return {ok: true, owner: orgName, ownerId: orgId, ownerType: "org"} ) @@ -162,7 +162,8 @@ def orgPublisherNames(object snapshot) array ( for i members.len ( object member = members[i].assertElse(object, {}) string username = (member.username ?? "").toStr().strip() - if username != "" and orgMemberCanPublish(snapshot, (member.id ?? "").toStr(), username) and !stringArrayContainsUser(names, username) ( + boolean publishes = member.admin == true or orgPermsAllowPublishing((member.perms ?? []).assertElse(array, [])) + if username != "" and publishes and !stringArrayContainsUser(names, username) ( names.append(username) ) ) @@ -189,7 +190,7 @@ def roturUserOrgs(string userId) object ( if response.status != 200 ( return {ok: false} ) - auto parsed = json.parse(response.body, {type: "object"}) + auto parsed = json.parse(response.body ?? "", {type: "object"}) if parsed.isErr() ( return {ok: false} ) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 6a43934..55fcdba 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -170,6 +170,7 @@ testing.assert(orgMemberPerms(snapshot, "", "BEA") == ["apps"], "a member is fou testing.assert(orgMemberPerms(snapshot, "u_zed", "zed") == [], "someone outside the org has none") testing.assert(orgHasMember(snapshot, "", "dee") and !orgHasMember(snapshot, "", "zed"), "membership includes private members") testing.assert(orgPublicMemberNames(snapshot) == ["ada", "cal"], "only public members are named") +testing.assert(orgPublisherNames(snapshot) == ["ada", "bea"], "publishers are the admins and app members, private ones included") testing.assert(orgMemberCanPublish(snapshot, "u_bea", "bea") and orgMemberCanPublish(snapshot, "u_ada", "ada"), "apps and admin may publish") testing.assert(!orgMemberCanPublish(snapshot, "u_cal", "cal") and !orgMemberCanPublish(snapshot, "u_dee", "dee"), "billing and plain members may not") diff --git a/src/community/social.osl b/src/community/social.osl index 598c5a8..495f422 100644 --- a/src/community/social.osl +++ b/src/community/social.osl @@ -51,7 +51,11 @@ def ownerIndexEntries(string owner, boolean includeUnshared) array ( for i keyMatches.len ( object entry = keyMatches[i].assert(object) string pid = entry.id.toStr() - if ownerId != "" and (entry.ownerId ?? "").toStr() != ownerId and (entry.ownerType ?? "").toStr() != "org" ( + boolean orgEntry = (entry.ownerType ?? "").toStr() == "org" + if orgEntry and (ownerId == "" or (entry.ownerId ?? "").toStr() != ownerId) ( + continue + ) + if ownerId != "" and (entry.ownerId ?? "").toStr() != ownerId ( entry.ownerId = ownerId putDocument(projectSearchDocs, entry["_id"].toStr(), entry) auto loaded = loadProject(pid) diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 3305027..571d859 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -124,9 +124,6 @@ def canManageSpace(object space,*serve.Context c) boolean ( if isSpaceOwner(space, c) ( return true ) - if canManageOrgContent(space, c) ( - return true - ) return stringArrayContainsUser(spaceManagers(space), username) ) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index d1de72e..9ae294d 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -102,7 +102,7 @@ def handleCreateSpace(*serve.Context c) ( object body = requestJSON(c) object owner = creationOwner(c, body, "spaces") if !owner.ok ( - c.json(owner.status.toNum(), {ok: false, error: owner.error}) + c.json(owner.status.toNum(), {ok: false, code: owner.code, error: owner.error}) return ) number ownedSpaces = spaceDocs.where("ownerId", "==", owner.ownerId.toStr()).count() @@ -437,8 +437,12 @@ def handleAddSpaceProject(*serve.Context c) ( submissions.append({projectId: project.id, owner: project.owner, submittedAt: timestamp}) space.submissions = submissions array participants = challengeArray(space, "participants") - if !stringArrayContainsUser(participants, project.owner.toStr()) ( - participants.append(project.owner) + string participant = project.owner.toStr() + if isOrgOwned(project) ( + participant = if ownsProject then contextString(c, "username") else "" + ) + if participant != "" and !stringArrayContainsUser(participants, participant) ( + participants.append(participant) ) space.participants = participants ) diff --git a/src/projects/project-create.osl b/src/projects/project-create.osl index 6e6a8fa..ff6cc5e 100644 --- a/src/projects/project-create.osl +++ b/src/projects/project-create.osl @@ -2,7 +2,7 @@ def handleCreateProject(*serve.Context c) ( object body = requestJSON(c) object owner = creationOwner(c, body, "projects") if !owner.ok ( - c.json(owner.status.toNum(), {ok: false, error: owner.error}) + c.json(owner.status.toNum(), {ok: false, code: owner.code, error: owner.error}) return ) number projectLimit = mistwarpBenefitsForUserId(owner.ownerId.toStr()).maxProjects.toNum() From 2ab716f5ab14e706a6b9567b1d54ae632fb87c8a Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:42:58 +0000 Subject: [PATCH 07/28] Only org admins move content out of an org, count org project limits by id, keep renames and erasure off org records, and retry org fan-outs after an outage --- scripts/e2e_smoke.py | 2 ++ src/auth/user-identity.osl | 9 ++++-- src/community/community-user-records.osl | 2 +- src/community/notifications.osl | 8 +++-- src/community/orgs.osl | 37 ++++++++++++++++++++++-- src/community/space-responses.osl | 1 + src/community/spaces.osl | 11 +++++++ src/projects/project-create.osl | 7 ++++- src/projects/project-response.osl | 1 + src/projects/project-update.osl | 9 ++++++ 10 files changed, 78 insertions(+), 9 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index f986247..6c66d96 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1044,6 +1044,7 @@ def org_flow(server, step, steps, ids): status, given = step("org transfer by member", "POST", "/v1/projects", "dee", {"title": "Dee's game"}) ids[str(given.get("id", "")) if isinstance(given, dict) else ""] = "" step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) + step("org move out refused for a publisher", "PUT", "/v1/projects/", "dee", {"owner": "dee"}) step("org transfer back", "PUT", "/v1/projects/", "sam", {"owner": "dee"}) step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) status, own_space = step("org own space create", "POST", "/v1/spaces", "sam", {"title": "Sam's space", "kind": "collection"}) @@ -1053,6 +1054,7 @@ def org_flow(server, step, steps, ids): step("org space move to an org Rotur can't vouch for", "PUT", "/v1/spaces/", "sam", {"owner": "ghoststudio"}) step("org space move", "PUT", "/v1/spaces/", "sam", {"owner": "studio"}) step("org space managed by publisher", "PUT", "/v1/spaces/", "dee", {"title": "Studio collection"}) + step("org space move out refused for a publisher", "PUT", "/v1/spaces/", "dee", {"owner": "dee"}) step("org page", "GET", "/v1/orgs/studio") step("org page as member", "GET", "/v1/orgs/studio", "dee") step("org project delete by billing", "DELETE", path, "alice") diff --git a/src/auth/user-identity.osl b/src/auth/user-identity.osl index 597f17b..5f4552c 100644 --- a/src/auth/user-identity.osl +++ b/src/auth/user-identity.osl @@ -147,7 +147,7 @@ def renameUserInProjects(string oldKey, string newKey, string newName, string us if res.ok ( object project = res.project.assert(object) boolean changed = false - if normalizeUsername(project.owner.toStr()) == oldKey ( + if normalizeUsername(project.owner.toStr()) == oldKey and !ownedByAnotherOrg(project, userId) ( project.owner = newName project.ownerId = userId changed = true @@ -212,11 +212,16 @@ def renameUserInProjects(string oldKey, string newKey, string newName, string us ) ) +def ownedByAnotherOrg(object record, string userId) boolean ( + string ownerId = (record.ownerId ?? "").toStr() + return (record.ownerType ?? "").toStr() == "org" and ownerId != "" and ownerId != userId +) + def renameIdentityFieldInCollection(*db.Collection collection, string nameField, string idField, string oldKey, string newName, string userId) ( array documents = collection.all() for i documents.len ( object document = documents[i].assert(object) - if document.contains(nameField) and document[nameField] != null and normalizeUsername(document[nameField].toStr()) == oldKey ( + if document.contains(nameField) and document[nameField] != null and normalizeUsername(document[nameField].toStr()) == oldKey and !ownedByAnotherOrg(document, userId) ( document[nameField] = newName document[idField] = userId putDocument(collection, document["_id"].toStr(), document) diff --git a/src/community/community-user-records.osl b/src/community/community-user-records.osl index 474b9d9..dd941ed 100644 --- a/src/community/community-user-records.osl +++ b/src/community/community-user-records.osl @@ -9,7 +9,7 @@ def purgeUserFromSpaces(string username) boolean ( for i spaces.len ( object space = spaces[i].assert(object) string spaceId = space["_id"].toStr() - if normalizeUsername(space.owner.toStr()) == key ( + if normalizeUsername(space.owner.toStr()) == key and !isOrgOwned(space) ( void spaceDocs.deleteOne({_id: space["_id"]}) deleteSpaceMemberships(spaceId) void fs.remove(commentsDir ++ spaceCommentKey(spaceId) ++ ".json") diff --git a/src/community/notifications.osl b/src/community/notifications.osl index a5f1cd7..4494b4c 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -462,14 +462,18 @@ def notifyContentOwner(object content, string actor, string notifType, object ex return ) recentOrgFanOuts.set(fanOutKey, true) - thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra) + thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra, fanOutKey) ) number orgNotificationLimit = 25 *cache.Cache recentOrgFanOuts = cache.new({capacity: 10000, ttl: 600000}) -def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra) ( +def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra, string fanOutKey) ( object snapshot = roturOrgSnapshot(owner) + if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( + recentOrgFanOuts.delete(fanOutKey) + return + ) if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index b73c593..c83b367 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -2,6 +2,8 @@ export { canManageOrgContent, creationOwner, isOrgOwned, + orgAdminAccess, + orgMoveOutAccess, orgAccess, orgHasMember, orgMemberCanPublish, @@ -12,6 +14,7 @@ export { *cache.Cache orgSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) *cache.Cache orgUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) +*cache.Cache orgMissingCache = cache.new({capacity: 10000, ttl: 10000}) *cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) def roturServiceGet(string path) object ( @@ -28,14 +31,16 @@ def roturOrgSnapshot(string rawName) object ( if cached.contains("ok") ( return cached ) + if orgMissingCache.get(name).assertElse(boolean, false) ( + return {ok: false, notOrg: true} + ) if commerceServiceKey == "" or orgUnavailableCache.get(name).assertElse(boolean, false) ( return {ok: false, unavailable: true} ) object response = roturServiceGet("/v2/integrations/mistwarp/orgs/" ++ url.escape(name)) if response.status == 404 ( - object missing = {ok: false, notOrg: true} - orgSnapshotCache.set(name, missing) - return missing + orgMissingCache.set(name, true) + return {ok: false, notOrg: true} ) auto parsed = json.parse(response.body ?? "", {type: "object"}) object data = if response.status == 200 and parsed.isOk() then parsed.unwrap().assert(object) else {} @@ -105,6 +110,32 @@ def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( return if orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) then "yes" else "no" ) +def orgAdminAccess(object snapshot, string expectedOrgId,*serve.Context c) string ( + if contextBool(c, "isAdmin") ( + return "yes" + ) + if !contextBool(c, "authenticated") ( + return "no" + ) + if !snapshot.ok ( + return if snapshot.contains("unavailable") and snapshot.unavailable == true then "unavailable" else "no" + ) + if expectedOrgId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != expectedOrgId ( + return "no" + ) + return if orgMemberPerms(snapshot, contextString(c, "userId"), contextString(c, "username")).contains("admin") then "yes" else "no" +) + +def orgMoveOutAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) or contextBool(c, "isAdmin") ( + return "yes" + ) + if !contextBool(c, "authenticated") ( + return "no" + ) + return orgAdminAccess(roturOrgSnapshot((value.owner ?? "").toStr()), (value.ownerId ?? "").toStr(), c) +) + def isOrgOwned(object value) boolean ( return (value.ownerType ?? "").toStr() == "org" ) diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index 51ab925..801784b 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -37,6 +37,7 @@ def spaceResponse(object space,*serve.Context c) object ( response.projectIds = if canManageSpace(space, c) then ids else visibleIds response.canManage = canManageSpace(space, c) response.isOwner = isSpaceOwner(space, c) + response.canMoveOut = response.isOwner == true and orgMoveOutAccess(space, c) == "yes" response.following = stringArrayContainsUser(spaceFollowers(space), contextString(c, "username")) response.followerCount = spaceFollowers(space).len response.invited = isSpaceInvitee(space, c) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 9ae294d..549d672 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -239,6 +239,17 @@ def handleUpdateSpace(*serve.Context c) ( c.badRequest("the new owner has reached their space limit") return ) + if isOrgOwned(space) and !sameOwner ( + string moveOut = orgMoveOutAccess(space, c) + if moveOut == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if moveOut != "yes" ( + c.forbidden("only an admin of the organisation can move this space out of it") + return + ) + ) object nextOrg = roturOrgSnapshot(nextOwner) boolean nextOwnerIsOrg = nextOrg.ok if (!nextOrg.ok and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( diff --git a/src/projects/project-create.osl b/src/projects/project-create.osl index ff6cc5e..abef012 100644 --- a/src/projects/project-create.osl +++ b/src/projects/project-create.osl @@ -86,7 +86,12 @@ def handleCreateProject(*serve.Context c) ( ) def ownedProjectSlotCount(string userId, string username) number ( - return ownerIndexCount(username, true) + trashedProjectsOwnedBy(userId, username).len + number byName = ownerIndexCount(username, true) + number byId = 0 + if userId != "" ( + byId = projectSearchDocs.where("ownerId", "==", userId).count() + ) + return (if byId > byName then byId else byName) + trashedProjectsOwnedBy(userId, username).len ) def projectFirstShared(object project) ( diff --git a/src/projects/project-response.osl b/src/projects/project-response.osl index fc1b943..4533342 100644 --- a/src/projects/project-response.osl +++ b/src/projects/project-response.osl @@ -283,6 +283,7 @@ def projectResponse(object project,*serve.Context c) object ( acceptedChanges: searchEntry.acceptedChanges } response.myRole = projectRoleFor(project, c) + response.canMoveOut = response.myRole == "owner" and orgMoveOutAccess(project, c) == "yes" response.canSaveDirectly = canSaveLiveProject(project, c) if isOwner ( response.collaborators = collaborators diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index 8dfa323..26273bf 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -176,6 +176,15 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans if !sameOwner and ownedProjectSlotCount(nextOwnerId, nextOwner) >= nextOwnerLimit ( return refuse(400, "the new owner has reached their project limit") ) + if isOrgOwned(project) and !sameOwner ( + string moveOut = orgAdminAccess(lookupOrgSnapshot(lookups, project.owner.toStr()), (project.ownerId ?? "").toStr(), c) + if moveOut == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) + if moveOut != "yes" ( + return refuse(403, "only an admin of the organisation can move this project out of it") + ) + ) object nextOrg = lookupOrgSnapshot(lookups, nextOwner) if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" ( return roturUnavailableRefusal(requestedOwner) From c1ee79a3c531a053841aa35422be6ee6504d45d2 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:32:02 +0000 Subject: [PATCH 08/28] Erase an org's own spaces with it, share one Rotur org lookup between concurrent callers, list only org-owned spaces, and say who may move a listed space out --- src/auth/account-controls.osl | 2 +- src/auth/user-identity.osl | 2 +- src/community/community-user-records.osl | 5 +++-- src/community/org-page.osl | 2 +- src/community/orgs.osl | 18 ++++++++++++++++++ src/community/orgs.test.osl | 8 +++++--- src/community/project-feedback.osl | 2 +- src/community/space-responses.osl | 1 + 8 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/auth/account-controls.osl b/src/auth/account-controls.osl index be48568..f68e7b5 100644 --- a/src/auth/account-controls.osl +++ b/src/auth/account-controls.osl @@ -236,7 +236,7 @@ def eraseUser(string userId, string username) ( for i ownedProjectIds.len ( deleteProjectCommunityRecords(ownedProjectIds[i].toStr()) ) - purgeUserFromSpaces(username) + purgeUserFromSpaces(username, userId) removeProjectsFromSpaces(ownedProjectIds) purgeUserCommunityRecords(username, userId) purgeUserFromNews(username) diff --git a/src/auth/user-identity.osl b/src/auth/user-identity.osl index 5f4552c..ec42c87 100644 --- a/src/auth/user-identity.osl +++ b/src/auth/user-identity.osl @@ -820,7 +820,7 @@ def purgeUser(string userId, string username) ( purgeUserFromNotifications(key) purgeGameDataForUser(userId) purgeBackpackForUser(userId) - purgeUserFromSpaces(username) + purgeUserFromSpaces(username, userId) purgeUserCommunityRecords(username, userId) purgeUserFromNews(username) removeUserFromSafetyLists(username) diff --git a/src/community/community-user-records.osl b/src/community/community-user-records.osl index dd941ed..c2c1a94 100644 --- a/src/community/community-user-records.osl +++ b/src/community/community-user-records.osl @@ -3,13 +3,14 @@ export { purgeUserFromSpaces } -def purgeUserFromSpaces(string username) boolean ( +def purgeUserFromSpaces(string username, string userId) boolean ( string key = normalizeUsername(username) array spaces = spaceDocs.all() for i spaces.len ( object space = spaces[i].assert(object) string spaceId = space["_id"].toStr() - if normalizeUsername(space.owner.toStr()) == key and !isOrgOwned(space) ( + boolean anotherOrg = isOrgOwned(space) and (space.ownerId ?? "").toStr() != userId + if normalizeUsername(space.owner.toStr()) == key and !anotherOrg ( void spaceDocs.deleteOne({_id: space["_id"]}) deleteSpaceMemberships(spaceId) void fs.remove(commentsDir ++ spaceCommentKey(spaceId) ++ ".json") diff --git a/src/community/org-page.osl b/src/community/org-page.osl index 8ce3b52..7b00b70 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -85,7 +85,7 @@ def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( for i entries.len ( object space = entries[i].assertElse(object, {}) string visibility = (space.visibility ?? "").toStr() - if visibility == "public" or visibility == "unlisted" or canManage ( + if (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or visibility == "unlisted" or canManage) ( spaces.append(spaceListResponse(space, c)) ) ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index c83b367..427767f 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -27,6 +27,16 @@ def roturOrgSnapshot(string rawName) object ( if name == "" or !isSafePathPart(name) ( return {ok: false, notOrg: true} ) + object known = cachedOrgSnapshot(name) + if known.len > 0 ( + return known + ) + sync.lock("rotur-org:" ++ name) + defer sync.unlock("rotur-org:" ++ name) + return fetchOrgSnapshot(name) +) + +def cachedOrgSnapshot(string name) object ( object cached = orgSnapshotCache.get(name).assertElse(object, {}) if cached.contains("ok") ( return cached @@ -37,6 +47,14 @@ def roturOrgSnapshot(string rawName) object ( if commerceServiceKey == "" or orgUnavailableCache.get(name).assertElse(boolean, false) ( return {ok: false, unavailable: true} ) + return {} +) + +def fetchOrgSnapshot(string name) object ( + object known = cachedOrgSnapshot(name) + if known.len > 0 ( + return known + ) object response = roturServiceGet("/v2/integrations/mistwarp/orgs/" ++ url.escape(name)) if response.status == 404 ( orgMissingCache.set(name, true) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 55fcdba..51490ee 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -1,4 +1,5 @@ import "std:testing" +import "std:sync" import "std:json" import "std:requests" import "std:serve" @@ -60,9 +61,10 @@ def contextBool(*serve.Context c, string key) boolean ( string spaceDbPath = "/tmp/mistwarp-org-page-" ++ timestamp.toStr() ++ ".db" *db.DB orgPageDb = db.open(spaceDbPath) *db.Collection spaceDocs = orgPageDb.collection("spaces") -void spaceDocs.insertOne({_id: "s_pub", ownerId: "org_studio", visibility: "public", edited: 3}) -void spaceDocs.insertOne({_id: "s_unl", ownerId: "org_studio", visibility: "unlisted", edited: 2}) -void spaceDocs.insertOne({_id: "s_pri", ownerId: "org_studio", visibility: "private", edited: 1}) +void spaceDocs.insertOne({_id: "s_pub", ownerId: "org_studio", ownerType: "org", visibility: "public", edited: 3}) +void spaceDocs.insertOne({_id: "s_unl", ownerId: "org_studio", ownerType: "org", visibility: "unlisted", edited: 2}) +void spaceDocs.insertOne({_id: "s_pri", ownerId: "org_studio", ownerType: "org", visibility: "private", edited: 1}) +void spaceDocs.insertOne({_id: "s_own", ownerId: "org_studio", ownerType: "", visibility: "public", edited: 0}) *db.Collection projectSearchDocs = orgPageDb.collection("projects") void projectSearchDocs.insertOne({_id: "p_org", id: "p_org", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: true, edited: 4}) diff --git a/src/community/project-feedback.osl b/src/community/project-feedback.osl index 55e6d64..ee703de 100644 --- a/src/community/project-feedback.osl +++ b/src/community/project-feedback.osl @@ -23,7 +23,7 @@ def handleCreateProjectFeedback(*serve.Context c) ( string feedbackId = project.id.toStr() ++ ":" ++ randomString(16) object feedback = {_id: feedbackId, projectId: project.id, type: feedbackType, message: message, status: "open", author: contextString(c, "username"), authorId: contextString(c, "userId"), created: timestamp, edited: timestamp} void feedbackDocs.insertOne(feedback) - notifyContentOwner(project, contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType}) + notifyContentOwner(project, contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType, feedbackId: feedbackId}) c.json(201, {ok: true}) ) diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index 801784b..dbe5ebf 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -128,6 +128,7 @@ def spaceListResponse(object space,*serve.Context c) object ( thumbnailUrl: thumbnailURL, canManage: canManage, isOwner: isSpaceOwner(space, c), + canMoveOut: isSpaceOwner(space, c) and orgMoveOutAccess(space, c) == "yes", following: stringArrayContainsUser(followers, contextString(c, "username")), invited: isSpaceInvitee(space, c) } From e24cdf1d7c69d21a93428dfac07c2464589808e3 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:03:37 +0000 Subject: [PATCH 09/28] Look orgs up by id so renames keep access, check the viewer's own org list before asking Rotur about an org, cap the org page lists, and let a publisher leave a challenge another publisher entered --- scripts/e2e_smoke.py | 3 +- src/community/challenges.osl | 15 ++++++++-- src/community/notifications.osl | 2 +- src/community/notifications.test.osl | 2 +- src/community/org-page.osl | 6 ++-- src/community/orgs.osl | 44 +++++++++++++++++++++++----- src/community/orgs.test.osl | 8 ++--- src/community/spaces.osl | 2 +- src/projects/project-access.osl | 2 +- src/projects/project-update.osl | 3 +- 10 files changed, 66 insertions(+), 21 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 6c66d96..d81cc6f 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -134,7 +134,8 @@ def answer_org_integration(self): return parts = self.path.split("?", 1)[0].split("/") if parts[4] == "orgs" and len(parts) == 6: - org = ORGS.get(urllib.parse.unquote(parts[5])) + wanted = urllib.parse.unquote(parts[5]) + org = ORGS.get(wanted) or next((value for value in ORGS.values() if value["id"] == wanted), None) self.answer(200, org) if org else self.answer(404, {"code": "not_org", "not_org": True}) return if parts[4] == "users" and len(parts) == 7 and parts[6] == "orgs": diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 50d64a6..7969cb0 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -60,7 +60,7 @@ def challengeOrgSnapshot(object space) object ( if challengeAudienceJudged(space) or !isOrgOwned(space) ( return {ok: false} ) - object snapshot = roturOrgSnapshot((space.owner ?? "").toStr()) + object snapshot = ownerOrgSnapshot(space) string ownerId = (space.ownerId ?? "").toStr() if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return {ok: false} @@ -325,7 +325,7 @@ def handleLeaveChallenge(*serve.Context c) ( array ids = spaceProjectIds(space) for i ids.len ( object project = (projectSearchDocs.findById(ids[i].toStr()) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( + if project.len > 0 and searchEntryOwnedByContext(project, c) and (!isOrgOwned(project) or submittedBy(space, project.id.toStr(), username)) ( c.badRequest("remove your submission before leaving the challenge") return ) @@ -336,6 +336,17 @@ def handleLeaveChallenge(*serve.Context c) ( c.json(200, {ok: true, joined: false, participantCount: space.participants.len}) ) +def submittedBy(object space, string projectId, string username) boolean ( + array submissions = challengeArray(space, "submissions") + for i submissions.len ( + object entry = submissions[i].assertElse(object, {}) + if (entry.projectId ?? "").toStr() == projectId and normalizeUsername((entry.submittedBy ?? "").toStr()) == normalizeUsername(username) ( + return true + ) + ) + return false +) + def handleRespondChallengeJudgeInvite(*serve.Context c) ( object space = (spaceDocs.findById(c.param("id")) ?? {}) if space.len == 0 or !isChallengeJudgeInvitee(space, contextString(c, "username")) ( diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 4494b4c..365b474 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -469,7 +469,7 @@ number orgNotificationLimit = 25 *cache.Cache recentOrgFanOuts = cache.new({capacity: 10000, ttl: 600000}) def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra, string fanOutKey) ( - object snapshot = roturOrgSnapshot(owner) + object snapshot = roturOrgSnapshot(if ownerId != "" then ownerId else owner) if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( recentOrgFanOuts.delete(fanOutKey) return diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index b58047d..45745fe 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -91,7 +91,7 @@ def isOrgOwned(object value) boolean ( ) def roturOrgSnapshot(string name) object ( - if name == "studio" ( + if name == "studio" or name == "o_studio" ( return {ok: true, org: {id: "o_studio"}} ) return {ok: false, notOrg: true} diff --git a/src/community/org-page.osl b/src/community/org-page.osl index 7b00b70..9b059c1 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -60,6 +60,8 @@ def handleGetMistWarpOrg(*serve.Context c) ( }) ) +number orgPageLimit = 100 + def orgProjectEntries(object org, boolean canManage) array ( string orgId = (org.id ?? "").toStr() array owned = [] @@ -69,7 +71,7 @@ def orgProjectEntries(object org, boolean canManage) array ( array entries = projectSearchDocs.where("ownerId", "==", orgId).sort("edited", "desc").all() for i entries.len ( object entry = entries[i].assertElse(object, {}) - if (entry.ownerType ?? "").toStr() == "org" and (entry.shared == true or canManage) ( + if (entry.ownerType ?? "").toStr() == "org" and (entry.shared == true or canManage) and owned.len < orgPageLimit ( owned.append(entry) ) ) @@ -85,7 +87,7 @@ def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( for i entries.len ( object space = entries[i].assertElse(object, {}) string visibility = (space.visibility ?? "").toStr() - if (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or visibility == "unlisted" or canManage) ( + if spaces.len < orgPageLimit and (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or visibility == "unlisted" or canManage) ( spaces.append(spaceListResponse(space, c)) ) ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 427767f..cd4e5b2 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -2,6 +2,7 @@ export { canManageOrgContent, creationOwner, isOrgOwned, + ownerOrgSnapshot, orgAdminAccess, orgMoveOutAccess, orgAccess, @@ -16,6 +17,7 @@ export { *cache.Cache orgUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) *cache.Cache orgMissingCache = cache.new({capacity: 10000, ttl: 10000}) *cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) +*cache.Cache userOrgsUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) def roturServiceGet(string path) object ( object failed = {body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false} @@ -110,6 +112,28 @@ def orgMemberCanPublish(object snapshot, string userId, string username) boolean return orgPermsAllowPublishing(orgMemberPerms(snapshot, userId, username)) ) +def ownerOrgSnapshot(object value) object ( + string ownerId = (value.ownerId ?? "").toStr() + return roturOrgSnapshot(if ownerId != "" then ownerId else (value.owner ?? "").toStr()) +) + +def viewerOrgListing(string name, string expectedOrgId,*serve.Context c) string ( + object mine = roturUserOrgs(contextString(c, "userId")) + if !mine.ok ( + return "unavailable" + ) + array orgs = mine.orgs.assertElse(array, []) + for i orgs.len ( + object org = orgs[i].assertElse(object, {}) + boolean idMatches = expectedOrgId != "" and (org.id ?? "").toStr() == expectedOrgId + boolean nameMatches = expectedOrgId == "" and normalizeUsername((org.username ?? "").toStr()) == normalizeUsername(name) + if idMatches or nameMatches ( + return "yes" + ) + ) + return "no" +) + def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( if !contextBool(c, "authenticated") ( return "no" @@ -117,7 +141,11 @@ def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( if contextBool(c, "isAdmin") ( return "yes" ) - object snapshot = roturOrgSnapshot(name) + string listed = viewerOrgListing(name, expectedOrgId, c) + if listed != "yes" ( + return listed + ) + object snapshot = roturOrgSnapshot(if expectedOrgId != "" then expectedOrgId else name) if !snapshot.ok ( return if snapshot.contains("unavailable") and snapshot.unavailable == true then "unavailable" else "no" ) @@ -151,7 +179,11 @@ def orgMoveOutAccess(object value,*serve.Context c) string ( if !contextBool(c, "authenticated") ( return "no" ) - return orgAdminAccess(roturOrgSnapshot((value.owner ?? "").toStr()), (value.ownerId ?? "").toStr(), c) + string listed = viewerOrgListing((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) + if listed != "yes" ( + return listed + ) + return orgAdminAccess(ownerOrgSnapshot(value), (value.ownerId ?? "").toStr(), c) ) def isOrgOwned(object value) boolean ( @@ -227,7 +259,7 @@ def roturUserOrgs(string userId) object ( if cached.contains("ok") ( return cached ) - if commerceServiceKey == "" ( + if commerceServiceKey == "" or userOrgsUnavailableCache.get(userId).assertElse(boolean, false) ( return {ok: false} ) object response = roturServiceGet("/v2/integrations/mistwarp/users/" ++ url.escape(userId) ++ "/orgs") @@ -236,11 +268,9 @@ def roturUserOrgs(string userId) object ( userOrgsCache.set(userId, none) return none ) - if response.status != 200 ( - return {ok: false} - ) auto parsed = json.parse(response.body ?? "", {type: "object"}) - if parsed.isErr() ( + if response.status != 200 or parsed.isErr() ( + userOrgsUnavailableCache.set(userId, true) return {ok: false} ) object data = parsed.unwrap().assert(object) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 51490ee..8773223 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -111,7 +111,7 @@ def handleFakeOrg(*serve.Context c) ( c.json(200, {error: "half an answer"}) return ) - if c.param("name") != "studio" ( + if c.param("name") != "studio" and c.param("name") != "org_studio" ( c.json(404, {error: "Not an organisation", code: "not_org", not_org: true}) return ) @@ -206,9 +206,9 @@ object mine = ask("/check/create", "bea", "u_bea") testing.assert(mine.ok and mine.owner == "bea" and mine.ownerType == "", "without an org, content is the creator's") askedRotur = [] -object orgs = roturUserOrgs("u_bea") -testing.assert(orgs.ok and orgs.orgs.len == 2 and askedRotur == ["orgs of u_bea"], "a person's orgs come from Rotur") -void roturUserOrgs("u_bea") +object orgs = roturUserOrgs("u_eve") +testing.assert(orgs.ok and orgs.orgs.len == 2 and askedRotur == ["orgs of u_eve"], "a person's orgs come from Rotur") +void roturUserOrgs("u_eve") testing.assert(askedRotur.len == 1, "and are cached") testing.assert(orgPermsAllowPublishing(["apps"]) and !orgPermsAllowPublishing([]), "the org list says where someone can publish") diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 549d672..b60f966 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -445,7 +445,7 @@ def handleAddSpaceProject(*serve.Context c) ( space.projects = ids if space.kind.toStr() == "challenge" ( array submissions = challengeArray(space, "submissions") - submissions.append({projectId: project.id, owner: project.owner, submittedAt: timestamp}) + submissions.append({projectId: project.id, owner: project.owner, submittedBy: contextString(c, "username"), submittedAt: timestamp}) space.submissions = submissions array participants = challengeArray(space, "participants") string participant = project.owner.toStr() diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 794c73b..3d0b018 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -86,7 +86,7 @@ def projectRoleForName(object project, string username) string ( if role == "owner" or username == "" or !isOrgOwned(project) ( return role ) - object snapshot = roturOrgSnapshot(project.owner.toStr()) + object snapshot = ownerOrgSnapshot(project) string ownerId = (project.ownerId ?? "").toStr() if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return role diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index 26273bf..5627c36 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -177,7 +177,8 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans return refuse(400, "the new owner has reached their project limit") ) if isOrgOwned(project) and !sameOwner ( - string moveOut = orgAdminAccess(lookupOrgSnapshot(lookups, project.owner.toStr()), (project.ownerId ?? "").toStr(), c) + string ownerKey = if (project.ownerId ?? "").toStr() != "" then project.ownerId.toStr() else project.owner.toStr() + string moveOut = orgAdminAccess(lookupOrgSnapshot(lookups, ownerKey), (project.ownerId ?? "").toStr(), c) if moveOut == "unavailable" ( return roturUnavailableRefusal(project.owner.toStr()) ) From 3a035f488e7ab03569060a7a7f2152a83ec9c5a4 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:36:54 +0000 Subject: [PATCH 10/28] Keep live broadcasts off Rotur by reading cached org snapshots, and cache an org under its name and id --- src/community/orgs.osl | 21 +++++++++++++++++++++ src/community/orgs.test.osl | 1 + src/projects/project-access.osl | 14 ++++++++++++++ src/realtime/site-realtime.osl | 4 ++-- 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index cd4e5b2..5aba3de 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -3,6 +3,7 @@ export { creationOwner, isOrgOwned, ownerOrgSnapshot, + ownerOrgSnapshotCached, orgAdminAccess, orgMoveOutAccess, orgAccess, @@ -70,6 +71,8 @@ def fetchOrgSnapshot(string name) object ( ) object snapshot = {ok: true, org: data, members: (data.members ?? []).assertElse(array, [])} orgSnapshotCache.set(name, snapshot) + orgSnapshotCache.set(normalizeUsername((data.id ?? "").toStr()), snapshot) + orgSnapshotCache.set(normalizeUsername((data.username ?? "").toStr()), snapshot) return snapshot ) @@ -117,6 +120,24 @@ def ownerOrgSnapshot(object value) object ( return roturOrgSnapshot(if ownerId != "" then ownerId else (value.owner ?? "").toStr()) ) +def ownerOrgSnapshotCached(object value) object ( + string ownerId = (value.ownerId ?? "").toStr() + string key = normalizeUsername(if ownerId != "" then ownerId else (value.owner ?? "").toStr()) + if key == "" or !isSafePathPart(key) ( + return {ok: false, notOrg: true} + ) + object known = cachedOrgSnapshot(key) + if known.len > 0 ( + return known + ) + thread.new(warmOrgSnapshot, key) + return {ok: false, unavailable: true} +) + +def warmOrgSnapshot(string key) ( + void roturOrgSnapshot(key) +) + def viewerOrgListing(string name, string expectedOrgId,*serve.Context c) string ( object mine = roturUserOrgs(contextString(c, "userId")) if !mine.ok ( diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 8773223..4a5e365 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -166,6 +166,7 @@ testing.assert(snapshot.ok and snapshot.org.id == "org_studio", "an org comes ba testing.assert(askedRotur == ["studio mw-key"], "MistWarp asks with its service key, by the lowercased name") void roturOrgSnapshot("studio") testing.assert(askedRotur.len == 1, "a second look within the minute is cached") +testing.assert(roturOrgSnapshot("org_studio").ok and askedRotur.len == 1, "the same org asked for by id is already known") testing.assert(orgMemberPerms(snapshot, "u_ada", "ada") == ["admin"], "an admin has every permission") testing.assert(orgMemberPerms(snapshot, "", "BEA") == ["apps"], "a member is found by name too") diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 3d0b018..368305f 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -10,6 +10,7 @@ export { projectRole, projectRoleFor, projectRoleForName, + projectRoleForNameCached, removeString } @@ -94,6 +95,19 @@ def projectRoleForName(object project, string username) string ( return if orgMemberCanPublish(snapshot, "", username) then "owner" else role ) +def projectRoleForNameCached(object project, string username) string ( + string role = projectRole(project, username) + if role == "owner" or username == "" or !isOrgOwned(project) ( + return role + ) + object snapshot = ownerOrgSnapshotCached(project) + string ownerId = (project.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return role + ) + return if orgMemberCanPublish(snapshot, "", username) then "owner" else role +) + def canViewForkProject(object project,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false diff --git a/src/realtime/site-realtime.osl b/src/realtime/site-realtime.osl index cb5bfa8..dbb9804 100644 --- a/src/realtime/site-realtime.osl +++ b/src/realtime/site-realtime.osl @@ -36,7 +36,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return false ) if isStudentUserId((conn.Get("userId") ?? "").toStr()) ( - return projectRoleForName(project, conn.Get("username").toStr()) != "" + return projectRoleForNameCached(project, conn.Get("username").toStr()) != "" ) if projectIsViewable(project) ( return true @@ -45,7 +45,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return true ) if conn.Get("authenticated") == true ( - return projectRoleForName(project, conn.Get("username").toStr()) != "" + return projectRoleForNameCached(project, conn.Get("username").toStr()) != "" ) return false ) From fba467332ef850161adcb0af02a4032ce518a8be Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:46:37 +0000 Subject: [PATCH 11/28] Check team and remix-share access through update lookups, wait for Rotur on subscribe, match broadcast viewers by id, warm each org once, and refuse moves into an org that can't own content --- scripts/e2e_smoke.py | 6 +++--- src/community/orgs.osl | 7 ++++++- src/community/spaces.osl | 4 ++++ src/projects/project-access.osl | 19 +++++-------------- src/projects/project-update.osl | 28 ++++++++++++++++++---------- src/realtime/site-realtime.osl | 15 ++++++++------- 6 files changed, 44 insertions(+), 35 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index d81cc6f..cb28f84 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -51,7 +51,7 @@ SLOW_USERS = {"slow_user": "u_slow"} SLOW_LEDGER_USERS = {"u_lena"} ROTUR_DELAY = 4 -EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure", "org transfer to an org Rotur can't vouch for", "org space move to an org Rotur can't vouch for"} +EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} CHECK_STEPS = {"sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} @@ -1041,7 +1041,7 @@ def org_flow(server, step, steps, ids): status, mine = step("org own create", "POST", "/v1/projects", "bob", {"title": "Bob's game"}) ids[str(mine.get("id", "")) if isinstance(mine, dict) else ""] = "" step("org transfer refused for an outsider", "PUT", "/v1/projects/", "bob", {"owner": "studio"}) - step("org transfer to an org Rotur can't vouch for", "PUT", "/v1/projects/", "bob", {"owner": "ghoststudio"}) + step("org transfer to an org that can't own content", "PUT", "/v1/projects/", "bob", {"owner": "ghoststudio"}) status, given = step("org transfer by member", "POST", "/v1/projects", "dee", {"title": "Dee's game"}) ids[str(given.get("id", "")) if isinstance(given, dict) else ""] = "" step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) @@ -1052,7 +1052,7 @@ def org_flow(server, step, steps, ids): own_space = own_space.get("space", {}) if isinstance(own_space, dict) else {} ids[str(own_space.get("_id", own_space.get("id", "")))] = "" step("org space move refused for billing", "PUT", "/v1/spaces/", "alice", {"owner": "studio"}) - step("org space move to an org Rotur can't vouch for", "PUT", "/v1/spaces/", "sam", {"owner": "ghoststudio"}) + step("org space move to an org that can't own content", "PUT", "/v1/spaces/", "sam", {"owner": "ghoststudio"}) step("org space move", "PUT", "/v1/spaces/", "sam", {"owner": "studio"}) step("org space managed by publisher", "PUT", "/v1/spaces/", "dee", {"title": "Studio collection"}) step("org space move out refused for a publisher", "PUT", "/v1/spaces/", "dee", {"owner": "dee"}) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 5aba3de..46a2107 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -17,6 +17,7 @@ export { *cache.Cache orgSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) *cache.Cache orgUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) *cache.Cache orgMissingCache = cache.new({capacity: 10000, ttl: 10000}) +*cache.Cache orgWarmingCache = cache.new({capacity: 10000, ttl: 12000}) *cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) *cache.Cache userOrgsUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) @@ -130,12 +131,16 @@ def ownerOrgSnapshotCached(object value) object ( if known.len > 0 ( return known ) - thread.new(warmOrgSnapshot, key) + if !orgWarmingCache.get(key).assertElse(boolean, false) ( + orgWarmingCache.set(key, true) + thread.new(warmOrgSnapshot, key) + ) return {ok: false, unavailable: true} ) def warmOrgSnapshot(string key) ( void roturOrgSnapshot(key) + orgWarmingCache.delete(key) ) def viewerOrgListing(string name, string expectedOrgId,*serve.Context c) string ( diff --git a/src/community/spaces.osl b/src/community/spaces.osl index b60f966..70224ee 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -252,6 +252,10 @@ def handleUpdateSpace(*serve.Context c) ( ) object nextOrg = roturOrgSnapshot(nextOwner) boolean nextOwnerIsOrg = nextOrg.ok + if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" and nextOrg.contains("notOrg") and nextOrg.notOrg == true ( + c.json(403, {ok: false, code: "org_unavailable", error: "that organisation can't own spaces right now"}) + return + ) if (!nextOrg.ok and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) return diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 368305f..981e0b8 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -10,7 +10,7 @@ export { projectRole, projectRoleFor, projectRoleForName, - projectRoleForNameCached, + projectRoleForUser, removeString } @@ -83,29 +83,20 @@ def projectModerator(object project,*serve.Context c) string ( ) def projectRoleForName(object project, string username) string ( - string role = projectRole(project, username) - if role == "owner" or username == "" or !isOrgOwned(project) ( - return role - ) - object snapshot = ownerOrgSnapshot(project) - string ownerId = (project.ownerId ?? "").toStr() - if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( - return role - ) - return if orgMemberCanPublish(snapshot, "", username) then "owner" else role + return projectRoleForUser(project, "", username, true) ) -def projectRoleForNameCached(object project, string username) string ( +def projectRoleForUser(object project, string userId, string username, boolean waitForRotur) string ( string role = projectRole(project, username) if role == "owner" or username == "" or !isOrgOwned(project) ( return role ) - object snapshot = ownerOrgSnapshotCached(project) + object snapshot = if waitForRotur then ownerOrgSnapshot(project) else ownerOrgSnapshotCached(project) string ownerId = (project.ownerId ?? "").toStr() if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return role ) - return if orgMemberCanPublish(snapshot, "", username) then "owner" else role + return if orgMemberCanPublish(snapshot, userId, username) then "owner" else role ) def canViewForkProject(object project,*serve.Context c) boolean ( diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index 5627c36..a2ab36e 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -108,7 +108,7 @@ def applyContentChanges(*serve.Context c, object project, object body, UpdateLoo applyProjectFlags(project, body) refusal = projectSaleRefusal(body) if isRefused(refusal) return refusal - refusal = applyRemixShareUpdate(c, project, body) + refusal = applyRemixShareUpdate(c, project, body, lookups) if isRefused(refusal) return refusal refusal = applyTags(project, body) if isRefused(refusal) return refusal @@ -146,8 +146,15 @@ def updateScopeRefusal(*serve.Context c, object project, object body) Refusal ( return noRefusal() ) -def isOwnerOrAdmin(*serve.Context c, object project) boolean ( - return projectRoleFor(project, c) == "owner" or contextBool(c, "isAdmin") +def ownerOrAdminRefusal(*serve.Context c, object project, UpdateLookups lookups, string message) Refusal ( + if contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" ( + return noRefusal() + ) + string access = lookupOrgContentAccess(lookups, c, project) + if access == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) + return if access == "yes" then noRefusal() else refuse(403, message) ) def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTransfer transfer, UpdateLookups lookups) Refusal ( @@ -188,6 +195,9 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans ) object nextOrg = lookupOrgSnapshot(lookups, nextOwner) if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" ( + if nextOrg.contains("notOrg") and nextOrg.notOrg == true ( + return refuseWithBody(403, {ok: false, code: "org_unavailable", error: "that organisation can't own projects right now"}) + ) return roturUnavailableRefusal(requestedOwner) ) boolean nextOwnerIsOrg = nextOrg.ok @@ -254,13 +264,12 @@ def applyVanitySlug(object project, object body, object creatorBenefits, UpdateL return noRefusal() ) -def applyRemixShareUpdate(*serve.Context c, object project, object body) Refusal ( +def applyRemixShareUpdate(*serve.Context c, object project, object body, UpdateLookups lookups) Refusal ( if !body.contains("remixShare") ( return noRefusal() ) - if !isOwnerOrAdmin(c, project) ( - return refuse(403, "only the owner can change the remix share") - ) + Refusal ownerRefusal = ownerOrAdminRefusal(c, project, lookups, "only the owner can change the remix share") + if isRefused(ownerRefusal) return ownerRefusal return applyRemixShare(project, body.remixShare.toNum()) ) @@ -268,9 +277,8 @@ def applyTeamUpdate(*serve.Context c, object project, object body, UpdateLookups if !body.contains("collaborators") ( return noRefusal() ) - if !isOwnerOrAdmin(c, project) ( - return refuse(403, "only the owner can manage the project team") - ) + Refusal teamRefusal = ownerOrAdminRefusal(c, project, lookups, "only the owner can manage the project team") + if isRefused(teamRefusal) return teamRefusal if typeof(body.collaborators) != "array" ( return refuse(400, "collaborators must be a list") ) diff --git a/src/realtime/site-realtime.osl b/src/realtime/site-realtime.osl index dbb9804..81f7b80 100644 --- a/src/realtime/site-realtime.osl +++ b/src/realtime/site-realtime.osl @@ -28,15 +28,16 @@ def siteAllows(*ws.Connection conn, string field, number maximum, number windowM return true ) -def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( +def siteCanView(object project,*ws.Connection conn, string accessKey, boolean waitForRotur) boolean ( + string viewerId = (conn.Get("userId") ?? "").toStr() if conn.Get("isAdmin") == true ( return true ) if projectOwnerBanned(project) ( return false ) - if isStudentUserId((conn.Get("userId") ?? "").toStr()) ( - return projectRoleForNameCached(project, conn.Get("username").toStr()) != "" + if isStudentUserId(viewerId) ( + return projectRoleForUser(project, viewerId, conn.Get("username").toStr(), waitForRotur) != "" ) if projectIsViewable(project) ( return true @@ -45,7 +46,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return true ) if conn.Get("authenticated") == true ( - return projectRoleForNameCached(project, conn.Get("username").toStr()) != "" + return projectRoleForUser(project, viewerId, conn.Get("username").toStr(), waitForRotur) != "" ) return false ) @@ -91,7 +92,7 @@ def siteBroadcastProject(string projectId, object message) ( for conn in siteRealtimeSocket.Connections() ( if !siteSubscribed(conn, projectId) continue string accessKey = siteProjectKey(conn, projectId) - if siteCanView(project, conn, accessKey) ( + if siteCanView(project, conn, accessKey, false) ( conn.Send(encoded) ) ) @@ -120,7 +121,7 @@ def siteBroadcastStats(string projectId, string actor, object viewerState) ( string actorKey = normalizeUsername(actor) for conn in siteRealtimeSocket.Connections() ( if !siteSubscribed(conn, projectId) continue - if !siteCanView(project, conn, siteProjectKey(conn, projectId)) continue + if !siteCanView(project, conn, siteProjectKey(conn, projectId), false) continue if conn.Get("authenticated") == true and normalizeUsername(conn.Get("username").toStr()) == actorKey ( conn.Send(actorMessage) ) else ( @@ -175,7 +176,7 @@ def siteSubscribe(*ws.Connection conn, object message) ( string projectId = message.projectId.assertElse(string, "").strip() string accessKey = message.accessKey.assertElse(string, "").strip() auto res = loadProject(projectId) - if !res.ok or !siteCanView(res.project.assert(object), conn, accessKey) ( + if !res.ok or !siteCanView(res.project.assert(object), conn, accessKey, true) ( siteError(conn, "project not found") return ) From 3490bf0f2d862033f009f0d8ce0a8ca1a2ddf0c7 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:20:10 +0000 Subject: [PATCH 12/28] Check org access before taking the project save lock, cap org notifications at 25, send every purchase, and answer 503 on own-content guards while Rotur is down --- src/community/challenges.osl | 14 ++++++++++++-- src/community/notifications.osl | 10 ++++++---- src/community/notifications.test.osl | 10 ++++++++++ src/community/orgs.osl | 10 +++++++++- src/community/project-feedback.osl | 7 ++++++- src/community/space-model.osl | 11 +++++++++-- src/git/pulls.osl | 1 + src/git/pulls.test.osl | 3 +++ src/history/commit-management.osl | 1 + src/projects/project-access.osl | 10 +++++++++- src/projects/project-upload.osl | 1 + 11 files changed, 67 insertions(+), 11 deletions(-) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 7969cb0..2f76382 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -431,7 +431,12 @@ def handleScoreChallengeEntry(*serve.Context c) ( return ) object project = (projectSearchDocs.findById(projectId) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( + string ownership = if project.len > 0 then searchEntryOwnership(project, c) else "no" + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( c.forbidden("you cannot score your own entry") return ) @@ -486,7 +491,12 @@ def handleVoteChallengeEntry(*serve.Context c) ( return ) object project = (projectSearchDocs.findById(projectId) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( + string ownership = if project.len > 0 then searchEntryOwnership(project, c) else "no" + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( c.forbidden("you cannot vote for your own entry") return ) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 365b474..d3ae5dd 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -458,10 +458,12 @@ def notifyContentOwner(object content, string actor, string notifType, object ex ) string ownerId = (content.ownerId ?? "").toStr() string fanOutKey = ownerId ++ ":" ++ owner ++ ":" ++ actor ++ ":" ++ notifType ++ ":" ++ extra.toStr() - if recentOrgFanOuts.get(fanOutKey).assertElse(boolean, false) ( - return + if notifType != "purchase" ( + if recentOrgFanOuts.get(fanOutKey).assertElse(boolean, false) ( + return + ) + recentOrgFanOuts.set(fanOutKey, true) ) - recentOrgFanOuts.set(fanOutKey, true) thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra, fanOutKey) ) @@ -479,7 +481,7 @@ def notifyOrgPublishers(string owner, string ownerId, string actor, string notif ) array names = orgPublisherNames(snapshot) for i names.len ( - if i > orgNotificationLimit ( + if i >= orgNotificationLimit ( return ) addNotification(names[i].toStr(), actor, notifType, extra) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index 45745fe..c995332 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -172,3 +172,13 @@ for i 50 ( wait 0.05 ) testing.assert(askedRotur.len == 1, "a love on another of the org's projects still fans out") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "purchase", {projectId: "p8", productId: "x", amount: 5}) +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "purchase", {projectId: "p8", productId: "x", amount: 5}) +for i 50 ( + if askedRotur.len > 1 ( + break + ) + wait 0.05 +) +testing.assert(askedRotur.len == 2, "buying the same product twice tells the publishers about both purchases") diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 46a2107..720910b 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -7,6 +7,7 @@ export { orgAdminAccess, orgMoveOutAccess, orgAccess, + orgContentAccess, orgHasMember, orgMemberCanPublish, orgPublisherNames, @@ -216,8 +217,15 @@ def isOrgOwned(object value) boolean ( return (value.ownerType ?? "").toStr() == "org" ) +def orgContentAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) ( + return "no" + ) + return orgAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) +) + def canManageOrgContent(object value,*serve.Context c) boolean ( - return isOrgOwned(value) and orgAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) == "yes" + return orgContentAccess(value, c) == "yes" ) def creationOwner(*serve.Context c, object body, string noun) object ( diff --git a/src/community/project-feedback.osl b/src/community/project-feedback.osl index ee703de..cd6ae48 100644 --- a/src/community/project-feedback.osl +++ b/src/community/project-feedback.osl @@ -121,7 +121,12 @@ def handleSaveProjectReview(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRoleFor(project, c) == "owner" ( + string orgOwnership = if projectRole(project, contextString(c, "username")) == "owner" then "yes" else orgContentAccess(project, c) + if orgOwnership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if orgOwnership == "yes" ( c.badRequest("you cannot review your own project") return ) diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 571d859..0c9a9b1 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -97,12 +97,19 @@ def isSpaceOwner(object space,*serve.Context c) boolean ( return contextBool(c, "isAdmin") or identityMatches(ownerId, space.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) or canManageOrgContent(space, c) ) -def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( +def searchEntryOwnership(object project,*serve.Context c) string ( string ownerId = "" if project.contains("ownerId") and project.ownerId != null ( ownerId = project.ownerId.toStr() ) - return identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) or canManageOrgContent(project, c) + if identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) ( + return "yes" + ) + return orgContentAccess(project, c) +) + +def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( + return searchEntryOwnership(project, c) == "yes" ) def isSpaceInvitee(object space,*serve.Context c) boolean ( diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 5893962..f7dd546 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -370,6 +370,7 @@ def handleProjectBranchMutation(*serve.Context c, string action) ( ) def mutateProjectBranchesLocked(*serve.Context c, string action) object ( + warmProjectOrgAccess(c.param("id"), c) string lockName = "project-history-" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index ee7e275..e2240d8 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -101,6 +101,9 @@ def canEditProject(object project,*serve.Context c) boolean ( def canSeeInsideProject(object project,*serve.Context c) boolean ( return false ) +def warmProjectOrgAccess(string id,*serve.Context c) ( + return +) def canViewProject(object project,*serve.Context c) boolean ( return false ) diff --git a/src/history/commit-management.osl b/src/history/commit-management.osl index 2b0ded4..d2b6600 100644 --- a/src/history/commit-management.osl +++ b/src/history/commit-management.osl @@ -107,6 +107,7 @@ def handlePatchCommit(*serve.Context c) ( ) def applyCommitPatchLocked(*serve.Context c) object ( + warmProjectOrgAccess(c.param("id"), c) string lockName = "project-history-" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index 981e0b8..dafafdd 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -11,7 +11,8 @@ export { projectRoleFor, projectRoleForName, projectRoleForUser, - removeString + removeString, + warmProjectOrgAccess } def removeString(array items, string value) array ( @@ -75,6 +76,13 @@ def projectRoleFor(object project,*serve.Context c) string ( return role ) +def warmProjectOrgAccess(string id,*serve.Context c) ( + auto loaded = loadProject(id) + if loaded.ok and isOrgOwned(loaded.project.assert(object)) ( + void canManageOrgContent(loaded.project.assert(object), c) + ) +) + def projectModerator(object project,*serve.Context c) string ( if canManageOrgContent(project, c) ( return contextString(c, "username") diff --git a/src/projects/project-upload.osl b/src/projects/project-upload.osl index 1fff723..354c3b9 100644 --- a/src/projects/project-upload.osl +++ b/src/projects/project-upload.osl @@ -55,6 +55,7 @@ def remixSyncAccessRefusal(*serve.Context c, object project, UploadRequest reque ) def handleUploadProject(*serve.Context c) ( + warmProjectOrgAccess(c.param("id"), c) runLocked(projectSaveLock(c.param("id")), def() -> ( handleUploadProjectLocked(c) )) From 9097fb7bec8d3a81c86baab7f4f5db8d122aed93 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:32:15 +0000 Subject: [PATCH 13/28] Keep unlisted org spaces off the public org page, keep private publishers out of judge invite answers, and skip the org fan-out for whoever already got the reply --- src/community/challenges.osl | 2 +- src/community/comments.osl | 4 ++-- src/community/notifications.osl | 13 ++++++++++--- src/community/notifications.test.osl | 19 +++++++++++++++++++ src/community/org-page.osl | 2 +- src/community/orgs.test.osl | 6 +++--- src/community/space-comments.osl | 2 +- src/git/pulls.osl | 2 +- src/git/pulls.test.osl | 3 +++ 9 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 2f76382..8676e55 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -268,7 +268,7 @@ def handleInviteChallengeJudge(*serve.Context c) ( c.notFound("user not found") return ) - if normalizeUsername(space.owner.toStr()) == usernameKey or isChallengeJudge(space, requested) or isChallengeJudgeInvitee(space, requested) ( + if normalizeUsername(space.owner.toStr()) == usernameKey or stringArrayContainsUser(challengeJudges(space), requested) or isChallengeJudgeInvitee(space, requested) ( c.badRequest("this user is already on the challenge team") return ) diff --git a/src/community/comments.osl b/src/community/comments.osl index f29884b..38b88b8 100644 --- a/src/community/comments.osl +++ b/src/community/comments.osl @@ -621,9 +621,9 @@ def handleCreateProjectComment(*serve.Context c) ( ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(parentAuthor) ( if donationAmount > 0 ( - notifyContentOwner(project, commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}) + notifyContentOwnerExcept(project, commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}, [parentAuthor]) ) else ( - notifyContentOwner(project, commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) + notifyContentOwnerExcept(project, commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}, [parentAuthor]) ) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), parentAuthor], {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index d3ae5dd..83423ea 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -1,6 +1,7 @@ export { addNotification, notifyContentOwner, + notifyContentOwnerExcept, loadNotifications, saveNotifications } @@ -451,6 +452,10 @@ def markNotificationsReadLocked(string username) ( ) def notifyContentOwner(object content, string actor, string notifType, object extra) ( + notifyContentOwnerExcept(content, actor, notifType, extra, []) +) + +def notifyContentOwnerExcept(object content, string actor, string notifType, object extra, array skip) ( string owner = (content.owner ?? "").toStr() if !isOrgOwned(content) ( addNotification(owner, actor, notifType, extra) @@ -464,13 +469,13 @@ def notifyContentOwner(object content, string actor, string notifType, object ex ) recentOrgFanOuts.set(fanOutKey, true) ) - thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra, fanOutKey) + thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra, fanOutKey, skip) ) number orgNotificationLimit = 25 *cache.Cache recentOrgFanOuts = cache.new({capacity: 10000, ttl: 600000}) -def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra, string fanOutKey) ( +def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra, string fanOutKey, array skip) ( object snapshot = roturOrgSnapshot(if ownerId != "" then ownerId else owner) if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( recentOrgFanOuts.delete(fanOutKey) @@ -484,6 +489,8 @@ def notifyOrgPublishers(string owner, string ownerId, string actor, string notif if i >= orgNotificationLimit ( return ) - addNotification(names[i].toStr(), actor, notifType, extra) + if !stringArrayContainsUser(skip, names[i].toStr()) ( + addNotification(names[i].toStr(), actor, notifType, extra) + ) ) ) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index c995332..5b77da3 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -86,6 +86,15 @@ def rewriteNotificationIdentityFields(object data, string oldKey, string newName return false ) +def stringArrayContainsUser(array users, string username) boolean ( + for i users.len ( + if users[i].toStr().toLower() == username.toLower() ( + return true + ) + ) + return false +) + def isOrgOwned(object value) boolean ( return (value.ownerType ?? "").toStr() == "org" ) @@ -182,3 +191,13 @@ for i 50 ( wait 0.05 ) testing.assert(askedRotur.len == 2, "buying the same product twice tells the publishers about both purchases") +askedRotur = [] +notifyContentOwnerExcept({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "zed", "comment", {projectId: "p9", commentId: "c1"}, ["ada"]) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) +wait 0.2 +testing.assert(askedRotur.len == 1 and !askedRotur[1].toStr().contains("ada"), "a publisher who already got the reply is not sent the comment again") diff --git a/src/community/org-page.osl b/src/community/org-page.osl index 9b059c1..c381ab5 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -87,7 +87,7 @@ def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( for i entries.len ( object space = entries[i].assertElse(object, {}) string visibility = (space.visibility ?? "").toStr() - if spaces.len < orgPageLimit and (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or visibility == "unlisted" or canManage) ( + if spaces.len < orgPageLimit and (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or canManage) ( spaces.append(spaceListResponse(space, c)) ) ) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 4a5e365..bf2a100 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -228,14 +228,14 @@ array anonymousMembers = anonymous.members.assert(array) testing.assert(anonymousMembers.len == 2 and anonymousMembers[1].username == "ada" and anonymousMembers[2].username == "cal", "a visitor sees only the listed members") testing.assert(anonymous.isMember == false and anonymous.canManage == false, "a visitor is neither member nor publisher") testing.assert(anonymous.projects.assert(array).len == 1 and anonymous.projects[1].id == "p_org", "a visitor sees the org's shared projects, not an old org's or a person's") -testing.assert(anonymous.spaces.assert(array).len == 2, "a visitor sees public and unlisted spaces") +testing.assert(anonymous.spaces.assert(array).len == 1 and anonymous.spaces[1].id == "s_pub", "a visitor sees only public spaces, not unlisted ones") object member = page("dee", "u_dee") testing.assert(member.members.assert(array).len == 4 and member.isMember == true and member.canManage == false, "a member sees every member but cannot manage") -testing.assert(member.projects.assert(array).len == 1 and member.spaces.assert(array).len == 2, "a member without apps sees what visitors see") +testing.assert(member.projects.assert(array).len == 1 and member.spaces.assert(array).len == 1, "a member without apps sees what visitors see") object publisher = page("bea", "u_bea") -testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts and private spaces") +testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts, unlisted and private spaces") orgPageDb.close() void fs.remove(spaceDbPath) diff --git a/src/community/space-comments.osl b/src/community/space-comments.osl index 4760b07..288f9bf 100644 --- a/src/community/space-comments.osl +++ b/src/community/space-comments.osl @@ -43,7 +43,7 @@ def handleCreateSpaceComment(*serve.Context c) ( addNotification(parentAuthor, commenter, "reply", notificationData) ) if normalizeUsername(space.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(space.owner.toStr()) != normalizeUsername(parentAuthor) ( - notifyContentOwner(space, commenter, "space_comment", notificationData) + notifyContentOwnerExcept(space, commenter, "space_comment", notificationData, [parentAuthor]) ) notifyMentions(created.comment.content.toStr(), commenter, [space.owner.toStr(), parentAuthor], notificationData) c.json(201, created) diff --git a/src/git/pulls.osl b/src/git/pulls.osl index f7dd546..be4ad87 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -644,7 +644,7 @@ def handleCreatePullComment(*serve.Context c) ( addNotification(pull.author.toStr(), commenter, "comment", notificationData) ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(project.owner.toStr()) != normalizeUsername(pull.author.toStr()) ( - notifyContentOwner(project, commenter, "comment", notificationData) + notifyContentOwnerExcept(project, commenter, "comment", notificationData, [pull.author.toStr()]) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), pull.author.toStr()], notificationData) created.comment = commentResponse(created.comment.assert(object), commenter) diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index e2240d8..f7b61f1 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -88,6 +88,9 @@ def addNotification(string target, string actor, string kind, object payload) ( def notifyContentOwner(object content, string actor, string kind, object payload) ( return ) +def notifyContentOwnerExcept(object content, string actor, string kind, object payload, array skip) ( + return +) def projectModerator(object project,*serve.Context c) string ( return project.owner.toStr() ) From c0b746d1b769f2dc6f0f23e198ca9f47b6618df0 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:42:39 +0000 Subject: [PATCH 14/28] Key private org project thumbnails for publishers on the org page and count only sent org notifications toward the cap --- src/community/notifications.osl | 4 +++- src/community/org-page.osl | 3 ++- src/community/orgs.test.osl | 14 ++++++++++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 83423ea..eae491b 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -485,12 +485,14 @@ def notifyOrgPublishers(string owner, string ownerId, string actor, string notif return ) array names = orgPublisherNames(snapshot) + number sent = 0 for i names.len ( - if i >= orgNotificationLimit ( + if sent >= orgNotificationLimit ( return ) if !stringArrayContainsUser(skip, names[i].toStr()) ( addNotification(names[i].toStr(), actor, notifType, extra) + sent += 1 ) ) ) diff --git a/src/community/org-page.osl b/src/community/org-page.osl index c381ab5..d264414 100644 --- a/src/community/org-page.osl +++ b/src/community/org-page.osl @@ -49,11 +49,12 @@ def handleGetMistWarpOrg(*serve.Context c) ( ) object org = snapshot.org.assertElse(object, {}) boolean canManage = signedIn and (contextBool(c, "isAdmin") or orgMemberCanPublish(snapshot, userId, username)) + array projects = projectsVisibleTo(orgProjectEntries(org, canManage), c) c.json(200, { ok: true, org: orgProfileResponse(org), members: members, - projects: projectsVisibleTo(orgProjectEntries(org, canManage), c), + projects: if canManage then viewerThumbEntries(projects) else projects, spaces: orgSpaces((org.id ?? "").toStr(), canManage, c), isMember: isMember, canManage: canManage diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index bf2a100..2122a84 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -72,6 +72,16 @@ void projectSearchDocs.insertOne({_id: "p_old", id: "p_old", ownerId: "org_gone" void projectSearchDocs.insertOne({_id: "p_person", id: "p_person", ownerId: "u_studio", ownerKey: "studio", ownerType: "", shared: true, edited: 2}) void projectSearchDocs.insertOne({_id: "p_draft", id: "p_draft", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: false, edited: 1}) +def viewerThumbEntries(array entries) array ( + array out = [] + for i entries.len ( + object keyed = entries[i].assert(object).clone() + keyed.thumbUrl = "keyed" + out.append(keyed) + ) + return out +) + def projectsVisibleTo(array entries,*serve.Context c) array ( return entries ) @@ -227,7 +237,7 @@ object anonymous = page("", "") array anonymousMembers = anonymous.members.assert(array) testing.assert(anonymousMembers.len == 2 and anonymousMembers[1].username == "ada" and anonymousMembers[2].username == "cal", "a visitor sees only the listed members") testing.assert(anonymous.isMember == false and anonymous.canManage == false, "a visitor is neither member nor publisher") -testing.assert(anonymous.projects.assert(array).len == 1 and anonymous.projects[1].id == "p_org", "a visitor sees the org's shared projects, not an old org's or a person's") +testing.assert(anonymous.projects.assert(array).len == 1 and anonymous.projects[1].id == "p_org" and anonymous.projects[1].thumbUrl != "keyed", "a visitor sees the org's shared projects, not an old org's or a person's") testing.assert(anonymous.spaces.assert(array).len == 1 and anonymous.spaces[1].id == "s_pub", "a visitor sees only public spaces, not unlisted ones") object member = page("dee", "u_dee") @@ -235,7 +245,7 @@ testing.assert(member.members.assert(array).len == 4 and member.isMember == true testing.assert(member.projects.assert(array).len == 1 and member.spaces.assert(array).len == 1, "a member without apps sees what visitors see") object publisher = page("bea", "u_bea") -testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts, unlisted and private spaces") +testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.projects[1].thumbUrl == "keyed" and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts, unlisted and private spaces") orgPageDb.close() void fs.remove(spaceDbPath) From 7faf2c5cc70fcfc66feb9d8f7c595caa39d163fb Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:53:55 +0000 Subject: [PATCH 15/28] Judge own-work guards and the trash listing by org publishing, not site admin, skip Rotur for students, and leave the actor out of the org notification count --- src/community/notifications.osl | 2 +- src/community/orgs.osl | 22 +++++++++++++++++----- src/community/orgs.test.osl | 17 +++++++++++++++++ src/community/project-feedback.osl | 2 +- src/community/space-model.osl | 2 +- src/projects/project-trash.osl | 2 +- 6 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index eae491b..c3a59c0 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -490,7 +490,7 @@ def notifyOrgPublishers(string owner, string ownerId, string actor, string notif if sent >= orgNotificationLimit ( return ) - if !stringArrayContainsUser(skip, names[i].toStr()) ( + if normalizeUsername(names[i].toStr()) != normalizeUsername(actor) and !stringArrayContainsUser(skip, names[i].toStr()) ( addNotification(names[i].toStr(), actor, notifType, extra) sent += 1 ) diff --git a/src/community/orgs.osl b/src/community/orgs.osl index 720910b..2d162bf 100644 --- a/src/community/orgs.osl +++ b/src/community/orgs.osl @@ -8,6 +8,7 @@ export { orgMoveOutAccess, orgAccess, orgContentAccess, + orgContentPublisherAccess, orgHasMember, orgMemberCanPublish, orgPublisherNames, @@ -162,12 +163,16 @@ def viewerOrgListing(string name, string expectedOrgId,*serve.Context c) string ) def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( - if !contextBool(c, "authenticated") ( - return "no" - ) - if contextBool(c, "isAdmin") ( + if contextBool(c, "authenticated") and contextBool(c, "isAdmin") ( return "yes" ) + return orgPublisherAccess(name, expectedOrgId, c) +) + +def orgPublisherAccess(string name, string expectedOrgId,*serve.Context c) string ( + if !contextBool(c, "authenticated") or isStudentUserId(contextString(c, "userId")) ( + return "no" + ) string listed = viewerOrgListing(name, expectedOrgId, c) if listed != "yes" ( return listed @@ -203,7 +208,7 @@ def orgMoveOutAccess(object value,*serve.Context c) string ( if !isOrgOwned(value) or contextBool(c, "isAdmin") ( return "yes" ) - if !contextBool(c, "authenticated") ( + if !contextBool(c, "authenticated") or isStudentUserId(contextString(c, "userId")) ( return "no" ) string listed = viewerOrgListing((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) @@ -224,6 +229,13 @@ def orgContentAccess(object value,*serve.Context c) string ( return orgAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) ) +def orgContentPublisherAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) ( + return "no" + ) + return orgPublisherAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) +) + def canManageOrgContent(object value,*serve.Context c) boolean ( return orgContentAccess(value, c) == "yes" ) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl index 2122a84..b68a9b8 100644 --- a/src/community/orgs.test.osl +++ b/src/community/orgs.test.osl @@ -38,6 +38,10 @@ def stringArrayContainsUser(array users, string username) boolean ( return false ) +def isStudentUserId(string userId) boolean ( + return userId.startsWith("stu_") +) + def contextString(*serve.Context c, string key) string ( if key == "username" ( return (c.header("X-Test-User") ?? "") @@ -141,6 +145,11 @@ def handleCheckContent(*serve.Context c) ( c.json(200, {ok: canManageOrgContent({owner: "studio", ownerId: (c.query("id") ?? ""), ownerType: (c.query("kind") ?? "")}, c)}) ) +def handleCheckOwnWork(*serve.Context c) ( + object content = {owner: "studio", ownerId: "org_studio", ownerType: "org"} + c.json(200, {ok: true, manage: orgContentAccess(content, c), publisher: orgContentPublisherAccess(content, c)}) +) + def handleCheckCreation(*serve.Context c) ( c.json(200, creationOwner(c, {org: (c.query("org") ?? "")}, "projects")) ) @@ -151,6 +160,7 @@ fakeRotur.GET("/v2/integrations/mistwarp/users/:id/orgs", handleFakeUserOrgs) fakeRotur.GET("/check/publish/:name", handleCheckPublish) fakeRotur.GET("/check/content", handleCheckContent) fakeRotur.GET("/check/create", handleCheckCreation) +fakeRotur.GET("/check/own", handleCheckOwnWork) fakeRotur.GET("/ready", handleFakeUserOrgs) fakeRotur.GET("/page/:name", handleGetMistWarpOrg) @@ -229,6 +239,13 @@ testing.assert(ask("/check/content?kind=org&id=org_gone", "zed", "u_zed").ok == object broken = roturOrgSnapshot("broken") testing.assert(!broken.ok and broken.unavailable == true, "a 200 without an org in it is unavailable, not an empty org") +object adminCheck = json.parse(requests.get(roturBase ++ "/check/own", {headers: {"X-Test-User": "root", "X-Test-Id": "u_root", "X-Test-Admin": "1"}}).unwrap().body, {type: "object"}).unwrap().assert(object) +testing.assert(adminCheck.manage == "yes" and adminCheck.publisher == "no", "a site admin manages an org's content but is not one of its publishers") +askedRotur = [] +object studentCheck = ask("/check/own", "kid", "stu_kid") +testing.assert(studentCheck.manage == "no" and studentCheck.publisher == "no" and askedRotur.len == 0, "a student never publishes for an org and Rotur is not asked") +testing.assert(ask("/check/own", "bea", "u_bea").publisher == "yes", "a publisher's own org work counts as theirs") + def page(string user, string id) object ( return ask("/page/studio", user, id) ) diff --git a/src/community/project-feedback.osl b/src/community/project-feedback.osl index cd6ae48..490c6a7 100644 --- a/src/community/project-feedback.osl +++ b/src/community/project-feedback.osl @@ -121,7 +121,7 @@ def handleSaveProjectReview(*serve.Context c) ( return ) object project = res.project.assert(object) - string orgOwnership = if projectRole(project, contextString(c, "username")) == "owner" then "yes" else orgContentAccess(project, c) + string orgOwnership = if projectRole(project, contextString(c, "username")) == "owner" then "yes" else orgContentPublisherAccess(project, c) if orgOwnership == "unavailable" ( c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) return diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 0c9a9b1..705f3a7 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -105,7 +105,7 @@ def searchEntryOwnership(object project,*serve.Context c) string ( if identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) ( return "yes" ) - return orgContentAccess(project, c) + return orgContentPublisherAccess(project, c) ) def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( diff --git a/src/projects/project-trash.osl b/src/projects/project-trash.osl index 72196c0..68cfbfc 100644 --- a/src/projects/project-trash.osl +++ b/src/projects/project-trash.osl @@ -197,7 +197,7 @@ def handleGetMyTrash(*serve.Context c) ( if res.ok ( object project = res.data.assert(object) string ownerId = (project.ownerId ?? "").toStr() - if identityMatches(ownerId, project.owner.toStr(), userId, username) or canManageOrgContent(project, c) ( + if identityMatches(ownerId, project.owner.toStr(), userId, username) or orgContentPublisherAccess(project, c) == "yes" ( projects.append({ id: project.id, title: project.title, From 05cdc0bd98df98cd7fdfa692eb23a4f7d2c050ca Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:04:28 +0000 Subject: [PATCH 16/28] Warm remix ancestors and org snapshots before the save lock, skip the org lookup for live hosts who already edit, hide private publishers' scores from curators outside the org, rename submittedBy, and check space visibility before the reaction lock --- src/community/challenges.osl | 36 +++++++++++++++++++- src/community/community-user-records.osl | 5 +++ src/community/spaces.osl | 5 +++ src/projects/live-collaboration.osl | 3 +- src/projects/project-access.osl | 42 ++++++++++++++++++++++-- 5 files changed, 87 insertions(+), 4 deletions(-) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 8676e55..ce85f60 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -188,6 +188,39 @@ def challengeScoreSummary(object space, string projectId, string viewer) object return {judgeScore: judgeScore, judgeScoreCount: scoreCount, audienceScore: audienceScore, audienceVoteCount: audienceCount, myScore: myScore, myVote: myVote, scores: entryScores} ) +def challengeHiddenJudges(object space,*serve.Context c) array ( + if !isOrgOwned(space) or contextBool(c, "isAdmin") ( + return [] + ) + object snapshot = challengeOrgSnapshot(space) + if orgHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")) ( + return [] + ) + array shown = challengeJudges(space) + array publishers = orgPublisherNames(snapshot) + array hidden = [] + for i publishers.len ( + if !stringArrayContainsUser(shown, publishers[i].toStr()) ( + hidden.append(publishers[i].toStr()) + ) + ) + return hidden +) + +def scoresWithoutJudges(array scores, array hidden) array ( + if hidden.len == 0 ( + return scores + ) + array kept = [] + for i scores.len ( + object score = scores[i].assertElse(object, {}) + if !stringArrayContainsUser(hidden, (score.judge ?? "").toStr()) ( + kept.append(score) + ) + ) + return kept +) + def challengeProjects(object space,*serve.Context c) array ( array projects = [] array ids = spaceProjectIds(space) @@ -195,6 +228,7 @@ def challengeProjects(object space,*serve.Context c) array ( boolean audienceJudged = challengeAudienceJudged(space) string phase = challengePhase(space) boolean revealRatings = phase == "awaiting-results" or phase == "results" or canManageSpace(space, c) + array hiddenJudges = if canManageSpace(space, c) then challengeHiddenJudges(space, c) else [] for i ids.len ( auto loaded = loadProject(ids[i].toStr()) if loaded.ok == true ( @@ -212,7 +246,7 @@ def challengeProjects(object space,*serve.Context c) array ( ) entry.myVote = summary.myVote entry.myScore = if isChallengeJudge(space, contextString(c, "username")) then summary.myScore else {} - entry.scoreBreakdown = if canManageSpace(space, c) then summary.scores else [] + entry.scoreBreakdown = if canManageSpace(space, c) then scoresWithoutJudges(summary.scores, hiddenJudges) else [] projects.append(entry) ) ) diff --git a/src/community/community-user-records.osl b/src/community/community-user-records.osl index c2c1a94..c1ea161 100644 --- a/src/community/community-user-records.osl +++ b/src/community/community-user-records.osl @@ -207,6 +207,11 @@ def renameUserCommunityRecords(string oldKey, string newKey, string newName) boo submissions[j] = submission changed = true ) + if normalizeUsername((submission.submittedBy ?? "").toStr()) == oldKey ( + submission.submittedBy = newName + submissions[j] = submission + changed = true + ) ) space.submissions = submissions ) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 70224ee..5444705 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -711,6 +711,11 @@ def handleCancelSpaceCuratorInvite(*serve.Context c) ( ) def handleReactSpace(*serve.Context c) ( + object visible = (spaceDocs.findById(c.param("id")) ?? {}) + if visible.len == 0 or !canViewSpace(visible, c) ( + c.notFound("space not found") + return + ) string lockName = "space-reactions:" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) diff --git a/src/projects/live-collaboration.osl b/src/projects/live-collaboration.osl index 1a77302..a9de787 100644 --- a/src/projects/live-collaboration.osl +++ b/src/projects/live-collaboration.osl @@ -39,7 +39,8 @@ def liveSession(object project, string branch) object ( if session.getKeys().len == 0 or session.expires.toNum() <= timestamp ( return {} ) - string role = projectRoleForName(project, session.host.toStr()) + string hostRole = projectRole(project, session.host.toStr()) + string role = if isSharedEditorRole(hostRole) then hostRole else projectRoleForName(project, session.host.toStr()) if !isSharedEditorRole(role) ( return {} ) diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index dafafdd..aba095e 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -78,8 +78,46 @@ def projectRoleFor(object project,*serve.Context c) string ( def warmProjectOrgAccess(string id,*serve.Context c) ( auto loaded = loadProject(id) - if loaded.ok and isOrgOwned(loaded.project.assert(object)) ( - void canManageOrgContent(loaded.project.assert(object), c) + if !loaded.ok ( + return + ) + object project = loaded.project.assert(object) + warmOneProjectOrg(project, c) + string parentId = remixLinkId(project, "remixParent") + string rootId = remixLinkId(project, "remixRoot") + if parentId != "" and parentId != id ( + auto parent = loadProject(parentId) + if parent.ok ( + object parentProject = parent.project.assert(object) + warmOneProjectOrg(parentProject, c) + string grandparentId = remixLinkId(parentProject, "remixParent") + if grandparentId != "" and grandparentId != parentId and grandparentId != rootId ( + auto grandparent = loadProject(grandparentId) + if grandparent.ok ( + warmOneProjectOrg(grandparent.project.assert(object), c) + ) + ) + ) + ) + if rootId != "" and rootId != id and rootId != parentId ( + auto root = loadProject(rootId) + if root.ok ( + warmOneProjectOrg(root.project.assert(object), c) + ) + ) +) + +def remixLinkId(object project, string field) string ( + if !project.contains(field) or project[field] == null ( + return "" + ) + return project[field].toStr() +) + +def warmOneProjectOrg(object project,*serve.Context c) ( + if isOrgOwned(project) ( + void ownerOrgSnapshot(project) + void canManageOrgContent(project, c) ) ) From 5bb61deab81b14c6bf5f1411f9ff0edbdb33c79b Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:15:40 +0000 Subject: [PATCH 17/28] Keep only listed judges' scores in breakdowns for curators outside the org, and use the plain project role for students on subscribe --- src/community/challenges.osl | 29 +++++++++++------------------ src/realtime/site-realtime.osl | 2 +- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index ce85f60..f3e3fa6 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -188,33 +188,26 @@ def challengeScoreSummary(object space, string projectId, string viewer) object return {judgeScore: judgeScore, judgeScoreCount: scoreCount, audienceScore: audienceScore, audienceVoteCount: audienceCount, myScore: myScore, myVote: myVote, scores: entryScores} ) -def challengeHiddenJudges(object space,*serve.Context c) array ( +def challengeShownJudges(object space,*serve.Context c) object ( if !isOrgOwned(space) or contextBool(c, "isAdmin") ( - return [] + return {all: true, names: []} ) object snapshot = challengeOrgSnapshot(space) - if orgHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")) ( - return [] - ) - array shown = challengeJudges(space) - array publishers = orgPublisherNames(snapshot) - array hidden = [] - for i publishers.len ( - if !stringArrayContainsUser(shown, publishers[i].toStr()) ( - hidden.append(publishers[i].toStr()) - ) + if snapshot.ok and orgHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")) ( + return {all: true, names: []} ) - return hidden + return {all: false, names: challengeJudges(space)} ) -def scoresWithoutJudges(array scores, array hidden) array ( - if hidden.len == 0 ( +def scoresByShownJudges(array scores, object shown) array ( + if shown.all == true ( return scores ) + array names = shown.names.assertElse(array, []) array kept = [] for i scores.len ( object score = scores[i].assertElse(object, {}) - if !stringArrayContainsUser(hidden, (score.judge ?? "").toStr()) ( + if stringArrayContainsUser(names, (score.judge ?? "").toStr()) ( kept.append(score) ) ) @@ -228,7 +221,7 @@ def challengeProjects(object space,*serve.Context c) array ( boolean audienceJudged = challengeAudienceJudged(space) string phase = challengePhase(space) boolean revealRatings = phase == "awaiting-results" or phase == "results" or canManageSpace(space, c) - array hiddenJudges = if canManageSpace(space, c) then challengeHiddenJudges(space, c) else [] + object shownJudges = if canManageSpace(space, c) then challengeShownJudges(space, c) else {all: false, names: []} for i ids.len ( auto loaded = loadProject(ids[i].toStr()) if loaded.ok == true ( @@ -246,7 +239,7 @@ def challengeProjects(object space,*serve.Context c) array ( ) entry.myVote = summary.myVote entry.myScore = if isChallengeJudge(space, contextString(c, "username")) then summary.myScore else {} - entry.scoreBreakdown = if canManageSpace(space, c) then scoresWithoutJudges(summary.scores, hiddenJudges) else [] + entry.scoreBreakdown = if canManageSpace(space, c) then scoresByShownJudges(summary.scores, shownJudges) else [] projects.append(entry) ) ) diff --git a/src/realtime/site-realtime.osl b/src/realtime/site-realtime.osl index 81f7b80..b1bc6ff 100644 --- a/src/realtime/site-realtime.osl +++ b/src/realtime/site-realtime.osl @@ -37,7 +37,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey, boolean wa return false ) if isStudentUserId(viewerId) ( - return projectRoleForUser(project, viewerId, conn.Get("username").toStr(), waitForRotur) != "" + return projectRole(project, conn.Get("username").toStr()) != "" ) if projectIsViewable(project) ( return true From 35046be0c16755fc64bc3344cf324571a1b1a2d6 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:26:29 +0000 Subject: [PATCH 18/28] Warm org access before the remix save lock, write challenge scores, votes and submissions under a per-space lock after the Rotur checks, and smoke test an org challenge --- scripts/e2e_smoke.py | 32 +++++++++++++- src/community/challenges.osl | 62 ++++++++++++++++++++------- src/community/spaces.osl | 65 +++++++++++++++++++---------- src/projects/project-remix.osl | 1 + src/projects/project-remix.test.osl | 4 ++ 5 files changed, 127 insertions(+), 37 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index cb28f84..b486529 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -52,7 +52,7 @@ SLOW_LEDGER_USERS = {"u_lena"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} -CHECK_STEPS = {"sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} +CHECK_STEPS = {"org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} UNORDERED = {"largest"} @@ -1058,10 +1058,40 @@ def org_flow(server, step, steps, ids): step("org space move out refused for a publisher", "PUT", "/v1/spaces/", "dee", {"owner": "dee"}) step("org page", "GET", "/v1/orgs/studio") step("org page as member", "GET", "/v1/orgs/studio", "dee") + org_challenge_flow(server, step, steps, ids, path) step("org project delete by billing", "DELETE", path, "alice") step("org project delete by publisher", "DELETE", path, "dee") +def org_challenge_flow(server, step, steps, ids, project_path): + step("org challenge entry save", "POST", project_path + "/upload", "dee", form=({}, {"project": sb3_archive(project_with_costumes([]))})) + step("org challenge entry share", "POST", project_path + "/visibility", "dee", {"visibility": "public"}) + now = int(time.time() * 1000) + status, created = step("org challenge create", "POST", "/v1/spaces", "dee", {"title": "Studio jam", "kind": "challenge", "org": "studio", "visibility": "public", "openSubmissions": True, "votingMode": "audience", "startsAt": now - 3600000, "endsAt": now + 3600000}) + created = created.get("space", {}) if isinstance(created, dict) else {} + ids[str(created.get("_id", created.get("id", "")))] = "" + challenge = "/v1/spaces/" + entered, _ = step("org challenge entry by publisher", "POST", challenge + "/projects/", "sam") + step("org challenge to judging", "PUT", challenge, "dee", {"endsAt": now - 1000, "judgingEndsAt": now + 3600000}) + own, _ = step("org challenge vote on own entry", "PUT", challenge + "/entries//vote", "dee", {"value": 4}) + vote = challenge + "/entries//vote" + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + bob = pool.submit(step, "org challenge vote by an outsider", "PUT", vote, "bob", {"value": 5}) + alice = pool.submit(step, "org challenge vote by a member who can't publish", "PUT", vote, "alice", {"value": 3}) + votes = [bob.result()[0], alice.result()[0]] + status, got = step("org challenge after votes", "GET", challenge, "dee") + space = got.get("space", {}) if isinstance(got, dict) else {} + entries = [entry for entry in space.get("projects", []) if isinstance(entry, dict)] + counted = sum(int(entry.get("audienceVoteCount", 0)) for entry in entries) + steps.append({"step": "org challenge checks", "status": 0, "body": { + "publisher entered the org project": entered == 200 and len(entries) == 1, + "one participant recorded": space.get("participantCount") == 1, + "own entry vote refused": own == 403, + "outside votes saved": votes == [200, 200], + "both votes counted": counted == 2, + }}) + + def remix_sync_flow(server, step, steps, ids): plain = sb3_archive(project_with_costumes([])) status, created = step("sync original create", "POST", "/v1/projects", "sam", {"title": "Sync original"}) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index f3e3fa6..55e266f 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -489,21 +489,61 @@ def handleScoreChallengeEntry(*serve.Context c) ( c.badRequest("feedback is too long") return ) - string judge = contextString(c, "username") + object score = {projectId: projectId, judge: contextString(c, "username"), ratings: ratings, feedback: feedback, edited: timestamp} + if !saveChallengeScore(space["_id"].toStr(), score) ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while your score was being saved. Try again."}) + return + ) + c.json(200, {ok: true, score: score}) +) + +def spaceWriteLock(string id) string ( + return "space-write:" ++ id +) + +def saveChallengeScore(string spaceId, object score) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string projectId = score.projectId.toStr() + if space.len == 0 or challengePhase(space) != "judging" or !spaceProjectIds(space).contains(projectId) ( + return false + ) array scores = challengeArray(space, "scores") array nextScores = [] for i scores.len ( object existing = scores[i].assert(object) - if existing.projectId.toStr() != projectId or normalizeUsername(existing.judge.toStr()) != normalizeUsername(judge) ( + if existing.projectId.toStr() != projectId or normalizeUsername(existing.judge.toStr()) != normalizeUsername(score.judge.toStr()) ( nextScores.append(existing) ) ) - object score = {projectId: projectId, judge: judge, ratings: ratings, feedback: feedback, edited: timestamp} nextScores.append(score) space.scores = nextScores space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, score: score}) + return true +) + +def saveChallengeVote(string spaceId, object vote) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string projectId = vote.projectId.toStr() + if space.len == 0 or !challengeAudienceVotingEnabled(space) or challengePhase(space) != "judging" or !spaceProjectIds(space).contains(projectId) ( + return false + ) + array votes = challengeArray(space, "audienceVotes") + array nextVotes = [] + for i votes.len ( + object existing = votes[i].assert(object) + if existing.projectId.toStr() != projectId or normalizeUsername(existing.username.toStr()) != normalizeUsername(vote.username.toStr()) ( + nextVotes.append(existing) + ) + ) + nextVotes.append(vote) + space.audienceVotes = nextVotes + putSpaceDocument(space) + return true ) def handleVoteChallengeEntry(*serve.Context c) ( @@ -532,18 +572,10 @@ def handleVoteChallengeEntry(*serve.Context c) ( c.badRequest("rating must be between 1 and 5") return ) - string username = contextString(c, "username") - array votes = challengeArray(space, "audienceVotes") - array nextVotes = [] - for i votes.len ( - object vote = votes[i].assert(object) - if vote.projectId.toStr() != projectId or normalizeUsername(vote.username.toStr()) != normalizeUsername(username) ( - nextVotes.append(vote) - ) + if !saveChallengeVote(space["_id"].toStr(), {projectId: projectId, username: contextString(c, "username"), value: value, edited: timestamp}) ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while your vote was being saved. Try again."}) + return ) - nextVotes.append({projectId: projectId, username: username, value: value, edited: timestamp}) - space.audienceVotes = nextVotes - putSpaceDocument(space) c.json(200, {ok: true, value: value}) ) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 5444705..a84da27 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -432,7 +432,8 @@ def handleAddSpaceProject(*serve.Context c) ( c.forbidden("only shared or unlisted projects can be added") return ) - boolean allowed = canManageSpace(space, c) + boolean manages = canManageSpace(space, c) + boolean allowed = manages boolean ownsProject = searchEntryOwnedByContext(project, c) boolean participantCanSubmit = space.openSubmissions == true and ownsProject if space.kind.toStr() == "challenge" ( @@ -443,29 +444,51 @@ def handleAddSpaceProject(*serve.Context c) ( c.forbidden("submissions are closed") return ) + string participant = project.owner.toStr() + if isOrgOwned(project) ( + participant = if ownsProject then contextString(c, "username") else "" + ) + object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages) + if added.len == 0 ( + c.json(409, {ok: false, code: "space_changed", error: "The space changed while this project was being added. Try again."}) + return + ) + object fresh = added.space.assert(object) + if added.added == true ( + notifyContentOwner(fresh, contextString(c, "username"), "space_project", {spaceId: fresh["_id"], spaceTitle: fresh.title, projectId: project.id, projectTitle: project.title}) + ) + c.json(200, {ok: true, space: spaceResponse(fresh, c)}) +) + +def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean asManager) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return {} + ) + if !asManager and (space.openSubmissions != true or (space.kind.toStr() == "challenge" and challengePhase(space) != "submissions")) ( + return {} + ) array ids = spaceProjectIds(space) - if !ids.contains(project.id.toStr()) ( - ids.append(project.id.toStr()) - space.projects = ids - if space.kind.toStr() == "challenge" ( - array submissions = challengeArray(space, "submissions") - submissions.append({projectId: project.id, owner: project.owner, submittedBy: contextString(c, "username"), submittedAt: timestamp}) - space.submissions = submissions - array participants = challengeArray(space, "participants") - string participant = project.owner.toStr() - if isOrgOwned(project) ( - participant = if ownsProject then contextString(c, "username") else "" - ) - if participant != "" and !stringArrayContainsUser(participants, participant) ( - participants.append(participant) - ) - space.participants = participants + if ids.contains(project.id.toStr()) ( + return {space: space, added: false} + ) + ids.append(project.id.toStr()) + space.projects = ids + if space.kind.toStr() == "challenge" ( + array submissions = challengeArray(space, "submissions") + submissions.append({projectId: project.id, owner: project.owner, submittedBy: submitter, submittedAt: timestamp}) + space.submissions = submissions + array participants = challengeArray(space, "participants") + if participant != "" and !stringArrayContainsUser(participants, participant) ( + participants.append(participant) ) - space.edited = timestamp - putSpaceDocument(space) - notifyContentOwner(space, contextString(c, "username"), "space_project", {spaceId: space["_id"], spaceTitle: space.title, projectId: project.id, projectTitle: project.title}) + space.participants = participants ) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + space.edited = timestamp + putSpaceDocument(space) + return {space: space, added: true} ) def handleRemoveSpaceProject(*serve.Context c) ( diff --git a/src/projects/project-remix.osl b/src/projects/project-remix.osl index 9f88900..e02c4a5 100644 --- a/src/projects/project-remix.osl +++ b/src/projects/project-remix.osl @@ -144,6 +144,7 @@ class ForkOutcome ( ) def handleRemixProject(*serve.Context c) ( + warmProjectOrgAccess(c.param("id"), c) object benefits = mistwarpBenefitsForUserId(contextString(c, "userId")) object body = requestJSON(c) string forkId = generateId() diff --git a/src/projects/project-remix.test.osl b/src/projects/project-remix.test.osl index 45858b5..86426e9 100644 --- a/src/projects/project-remix.test.osl +++ b/src/projects/project-remix.test.osl @@ -139,6 +139,10 @@ def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( def roturOrgSnapshot(string name) object ( return {ok: false, notOrg: true} ) +def warmProjectOrgAccess(string id,*serve.Context c) ( + return +) + def isOrgOwned(object value) boolean ( return false ) From cf2e8838fc21da224c956fe8bd10a3f788fc1519 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:37:02 +0000 Subject: [PATCH 19/28] Recheck the judge and criteria under the space lock, answer 503 to org judges while Rotur is down, and make the smoke votes really overlap --- scripts/e2e_smoke.py | 13 ++++++++---- src/community/challenges.osl | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index b486529..068f573 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -32,7 +32,7 @@ "monitors": [], "extensions": [], "meta": {"semver": "3.0.0", "vm": "0.2.0", "agent": "smoke"}, } -USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena"} +USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena", "vic": "u_vic"} FULL_STORAGE = {"u_dee"} ORGS = { "studio": { @@ -50,6 +50,7 @@ BANNED_USERS = {"banned_user"} SLOW_USERS = {"slow_user": "u_slow"} SLOW_LEDGER_USERS = {"u_lena"} +SLOW_ORG_LISTS = {"u_vic"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} CHECK_STEPS = {"org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} @@ -139,6 +140,8 @@ def answer_org_integration(self): self.answer(200, org) if org else self.answer(404, {"code": "not_org", "not_org": True}) return if parts[4] == "users" and len(parts) == 7 and parts[6] == "orgs": + if parts[5] in SLOW_ORG_LISTS: + time.sleep(ROTUR_DELAY) mine = [] for org in ORGS.values(): for member in org["members"]: @@ -1064,6 +1067,7 @@ def org_flow(server, step, steps, ids): def org_challenge_flow(server, step, steps, ids, project_path): + step("accept agreement vic", "POST", "/v1/agreement/accept", "vic", {}) step("org challenge entry save", "POST", project_path + "/upload", "dee", form=({}, {"project": sb3_archive(project_with_costumes([]))})) step("org challenge entry share", "POST", project_path + "/visibility", "dee", {"visibility": "public"}) now = int(time.time() * 1000) @@ -1076,9 +1080,10 @@ def org_challenge_flow(server, step, steps, ids, project_path): own, _ = step("org challenge vote on own entry", "PUT", challenge + "/entries//vote", "dee", {"value": 4}) vote = challenge + "/entries//vote" with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: - bob = pool.submit(step, "org challenge vote by an outsider", "PUT", vote, "bob", {"value": 5}) - alice = pool.submit(step, "org challenge vote by a member who can't publish", "PUT", vote, "alice", {"value": 3}) - votes = [bob.result()[0], alice.result()[0]] + slow = pool.submit(step, "org challenge vote while Rotur is slow", "PUT", vote, "vic", {"value": 3}) + time.sleep(ROTUR_DELAY / 4) + fast = pool.submit(step, "org challenge vote by an outsider", "PUT", vote, "bob", {"value": 5}) + votes = [slow.result()[0], fast.result()[0]] status, got = step("org challenge after votes", "GET", challenge, "dee") space = got.get("space", {}) if isinstance(got, dict) else {} entries = [entry for entry in space.get("projects", []) if isinstance(entry, dict)] diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 55e266f..49b268b 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -450,6 +450,11 @@ def handleScoreChallengeEntry(*serve.Context c) ( return ) if !isChallengeJudge(space, contextString(c, "username")) ( + object judgeSnapshot = if isOrgOwned(space) and !challengeAudienceJudged(space) then ownerOrgSnapshot(space) else {ok: true} + if !judgeSnapshot.ok and judgeSnapshot.contains("unavailable") and judgeSnapshot.unavailable == true ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) c.forbidden("only invited judges can score entries") return ) @@ -501,6 +506,36 @@ def spaceWriteLock(string id) string ( return "space-write:" ++ id ) +def stillChallengeJudge(object space, string judge) boolean ( + if challengeAudienceJudged(space) ( + return false + ) + if stringArrayContainsUser(challengeArray(space, "judges"), judge) ( + return true + ) + if !isOrgOwned(space) ( + return false + ) + object snapshot = ownerOrgSnapshotCached(space) + string ownerId = (space.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return false + ) + return stringArrayContainsUser(orgPublisherNames(snapshot), judge) +) + +def ratingsMatchCriteria(object space, array ratings) boolean ( + if ratings.len != challengeCriteria(space).len ( + return false + ) + for i ratings.len ( + if !validChallengeCriterion(space, ratings[i].assertElse(object, {}).criterionId.toStr()) ( + return false + ) + ) + return true +) + def saveChallengeScore(string spaceId, object score) boolean ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) @@ -509,6 +544,9 @@ def saveChallengeScore(string spaceId, object score) boolean ( if space.len == 0 or challengePhase(space) != "judging" or !spaceProjectIds(space).contains(projectId) ( return false ) + if !stillChallengeJudge(space, score.judge.toStr()) or !ratingsMatchCriteria(space, score.ratings.assertElse(array, [])) ( + return false + ) array scores = challengeArray(space, "scores") array nextScores = [] for i scores.len ( From fc42be5ca8e2adc2e10cc4a76e8d7e69ed2e83a6 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:46:20 +0000 Subject: [PATCH 20/28] Join and leave challenges under the space lock after the Rotur checks, and refuse leaving with 503 while Rotur can't tell --- scripts/e2e_smoke.py | 5 +++ src/community/challenges.osl | 73 +++++++++++++++++++++++++++++------- 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 068f573..900b61d 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1076,6 +1076,9 @@ def org_challenge_flow(server, step, steps, ids, project_path): ids[str(created.get("_id", created.get("id", "")))] = "" challenge = "/v1/spaces/" entered, _ = step("org challenge entry by publisher", "POST", challenge + "/projects/", "sam") + joined, _ = step("org challenge join", "POST", challenge + "/join", "bob", {}) + submitter_left, _ = step("org challenge leave refused for the submitter", "DELETE", challenge + "/join", "sam") + left, left_body = step("org challenge leave", "DELETE", challenge + "/join", "bob") step("org challenge to judging", "PUT", challenge, "dee", {"endsAt": now - 1000, "judgingEndsAt": now + 3600000}) own, _ = step("org challenge vote on own entry", "PUT", challenge + "/entries//vote", "dee", {"value": 4}) vote = challenge + "/entries//vote" @@ -1091,6 +1094,8 @@ def org_challenge_flow(server, step, steps, ids, project_path): steps.append({"step": "org challenge checks", "status": 0, "body": { "publisher entered the org project": entered == 200 and len(entries) == 1, "one participant recorded": space.get("participantCount") == 1, + "an outsider joins and leaves": joined == 200 and left == 200 and isinstance(left_body, dict) and left_body.get("joined") is False, + "the submitter cannot leave": submitter_left == 400, "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], "both votes counted": counted == 2, diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 49b268b..829cc3c 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -320,17 +320,34 @@ def handleJoinChallenge(*serve.Context c) ( c.badRequest("this challenge is no longer open to new participants") return ) + object joined = joinChallengeLocked(space["_id"].toStr(), contextString(c, "username")) + if joined.len == 0 ( + c.badRequest("this challenge is no longer open to new participants") + return + ) + if joined.added == true and !isSpaceOwner(space, c) ( + notifyContentOwner(space, contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) + ) + c.json(200, {ok: true, joined: true, participantCount: joined.count}) +) + +def joinChallengeLocked(string spaceId, string username) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string phase = if space.len > 0 then challengePhase(space) else "" + if phase != "upcoming" and phase != "submissions" ( + return {} + ) array participants = challengeArray(space, "participants") - if !stringArrayContainsUser(participants, contextString(c, "username")) ( - participants.append(contextString(c, "username")) - space.participants = participants - space.edited = timestamp - putSpaceDocument(space) - if !isSpaceOwner(space, c) ( - notifyContentOwner(space, contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) - ) + if stringArrayContainsUser(participants, username) ( + return {added: false, count: participants.len} ) - c.json(200, {ok: true, joined: true, participantCount: participants.len}) + participants.append(username) + space.participants = participants + space.edited = timestamp + putSpaceDocument(space) + return {added: true, count: participants.len} ) def handleLeaveChallenge(*serve.Context c) ( @@ -352,15 +369,45 @@ def handleLeaveChallenge(*serve.Context c) ( array ids = spaceProjectIds(space) for i ids.len ( object project = (projectSearchDocs.findById(ids[i].toStr()) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) and (!isOrgOwned(project) or submittedBy(space, project.id.toStr(), username)) ( - c.badRequest("remove your submission before leaving the challenge") - return + if project.len > 0 and (!isOrgOwned(project) or submittedBy(space, project.id.toStr(), username)) ( + string ownership = searchEntryOwnership(project, c) + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( + c.badRequest("remove your submission before leaving the challenge") + return + ) ) ) + object left = leaveChallengeLocked(space["_id"].toStr(), username, ids) + if left.len == 0 ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while you were leaving. Try again."}) + return + ) + c.json(200, {ok: true, joined: false, participantCount: left.count}) +) + +def leaveChallengeLocked(string spaceId, string username, array checkedIds) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string phase = if space.len > 0 then challengePhase(space) else "" + if phase != "upcoming" and phase != "submissions" ( + return {} + ) + array ids = spaceProjectIds(space) + for i ids.len ( + if !checkedIds.contains(ids[i].toStr()) and submittedBy(space, ids[i].toStr(), username) ( + return {} + ) + ) + array participants = challengeArray(space, "participants") space.participants = removeUser(participants, username) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, joined: false, participantCount: space.participants.len}) + return {count: space.participants.len} ) def submittedBy(object space, string projectId, string username) boolean ( From d9eeecd53e3dfbed8073e0b8b6badb50ac61aa39 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:52:47 +0000 Subject: [PATCH 21/28] Remove space projects under the space lock after the Rotur checks, and keep locked challenge fields when saving a space edit --- scripts/e2e_smoke.py | 3 +++ src/community/spaces.osl | 47 +++++++++++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 900b61d..3753fa3 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1091,11 +1091,14 @@ def org_challenge_flow(server, step, steps, ids, project_path): space = got.get("space", {}) if isinstance(got, dict) else {} entries = [entry for entry in space.get("projects", []) if isinstance(entry, dict)] counted = sum(int(entry.get("audienceVoteCount", 0)) for entry in entries) + removed, removed_body = step("org challenge entry removed by the submitter", "DELETE", challenge + "/projects/", "sam") + remaining = ((removed_body or {}).get("space") or {}).get("projects", []) if isinstance(removed_body, dict) else None steps.append({"step": "org challenge checks", "status": 0, "body": { "publisher entered the org project": entered == 200 and len(entries) == 1, "one participant recorded": space.get("participantCount") == 1, "an outsider joins and leaves": joined == 200 and left == 200 and isinstance(left_body, dict) and left_body.get("joined") is False, "the submitter cannot leave": submitter_left == 400, + "the submitter removes the entry": removed == 200 and remaining == [], "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], "both votes counted": counted == 2, diff --git a/src/community/spaces.osl b/src/community/spaces.osl index a84da27..eaa0d32 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -367,8 +367,23 @@ def handleUpdateSpace(*serve.Context c) ( return ) space.edited = timestamp + object saved = saveEditedSpace(space) + c.json(200, {ok: true, space: spaceResponse(saved, c)}) +) + +def saveEditedSpace(object space) object ( + sync.lock(spaceWriteLock(space["_id"].toStr())) + defer sync.unlock(spaceWriteLock(space["_id"].toStr())) + object fresh = (spaceDocs.findById(space["_id"].toStr()) ?? {}) + array lockedFields = ["projects", "submissions", "participants", "scores", "audienceVotes"] + for i lockedFields.len ( + string field = lockedFields[i].toStr() + if fresh.contains(field) ( + space[field] = fresh[field] + ) + ) putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + return space ) def handleDeleteSpace(*serve.Context c) ( @@ -499,20 +514,40 @@ def handleRemoveSpaceProject(*serve.Context c) ( ) object project = (projectSearchDocs.findById(c.param("project")) ?? {}) boolean allowed = canManageSpace(space, c) - if project.len > 0 ( - allowed = allowed or searchEntryOwnedByContext(project, c) + if !allowed and project.len > 0 ( + string ownership = searchEntryOwnership(project, c) + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + allowed = ownership == "yes" ) if !allowed ( c.forbidden("you cannot remove this project") return ) - space.projects = removeString(spaceProjectIds(space), c.param("project")) + object saved = removeProjectFromSpaceLocked(space["_id"].toStr(), c.param("project")) + if saved.len == 0 ( + c.notFound("space not found") + return + ) + c.json(200, {ok: true, space: spaceResponse(saved, c)}) +) + +def removeProjectFromSpaceLocked(string spaceId, string projectId) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return {} + ) + space.projects = removeString(spaceProjectIds(space), projectId) if space.kind.toStr() == "challenge" ( array submissions = challengeArray(space, "submissions") array nextSubmissions = [] for i submissions.len ( object submission = submissions[i].assert(object) - if submission.projectId.toStr() != c.param("project") ( + if submission.projectId.toStr() != projectId ( nextSubmissions.append(submission) ) ) @@ -520,7 +555,7 @@ def handleRemoveSpaceProject(*serve.Context c) ( ) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + return space ) def handleFollowSpace(*serve.Context c) ( From 7eda42379d7caf885e24b7731c3411632aa1380d Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:00:59 +0000 Subject: [PATCH 22/28] Refuse space edits when the space is gone or criteria would change after scoring, delete spaces under the space lock, and smoke test deleting an org challenge --- scripts/e2e_smoke.py | 3 +++ src/community/spaces.osl | 28 ++++++++++++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 3753fa3..2bfede9 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1093,12 +1093,15 @@ def org_challenge_flow(server, step, steps, ids, project_path): counted = sum(int(entry.get("audienceVoteCount", 0)) for entry in entries) removed, removed_body = step("org challenge entry removed by the submitter", "DELETE", challenge + "/projects/", "sam") remaining = ((removed_body or {}).get("space") or {}).get("projects", []) if isinstance(removed_body, dict) else None + deleted, _ = step("org challenge delete", "DELETE", challenge, "sam") + gone, _ = step("org challenge after delete", "GET", challenge, "sam") steps.append({"step": "org challenge checks", "status": 0, "body": { "publisher entered the org project": entered == 200 and len(entries) == 1, "one participant recorded": space.get("participantCount") == 1, "an outsider joins and leaves": joined == 200 and left == 200 and isinstance(left_body, dict) and left_body.get("joined") is False, "the submitter cannot leave": submitter_left == 400, "the submitter removes the entry": removed == 200 and remaining == [], + "an org admin deletes the challenge": deleted == 200 and gone == 404, "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], "both votes counted": counted == 2, diff --git a/src/community/spaces.osl b/src/community/spaces.osl index eaa0d32..42b1dc5 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -367,14 +367,28 @@ def handleUpdateSpace(*serve.Context c) ( return ) space.edited = timestamp - object saved = saveEditedSpace(space) + object saved = saveEditedSpace(space, body.contains("criteria") and space.kind.toStr() == "challenge") + if saved.len == 0 ( + c.notFound("space not found") + return + ) + if saved.contains("refused") ( + c.badRequest("judging criteria cannot change after scoring begins") + return + ) c.json(200, {ok: true, space: spaceResponse(saved, c)}) ) -def saveEditedSpace(object space) object ( +def saveEditedSpace(object space, boolean changesCriteria) object ( sync.lock(spaceWriteLock(space["_id"].toStr())) defer sync.unlock(spaceWriteLock(space["_id"].toStr())) object fresh = (spaceDocs.findById(space["_id"].toStr()) ?? {}) + if fresh.len == 0 ( + return {} + ) + if changesCriteria and challengeArray(fresh, "scores").len > 0 ( + return {refused: "criteria"} + ) array lockedFields = ["projects", "submissions", "participants", "scores", "audienceVotes"] for i lockedFields.len ( string field = lockedFields[i].toStr() @@ -396,8 +410,7 @@ def handleDeleteSpace(*serve.Context c) ( c.forbidden("only the owner can delete this space") return ) - void spaceDocs.deleteOne({_id: space["_id"]}) - deleteSpaceMemberships(space["_id"].toStr()) + deleteSpaceLocked(space["_id"].toStr()) void fs.remove(commentsDir ++ spaceCommentKey(space["_id"].toStr()) ++ ".json") void fs.remove(commentsDir ++ spaceCommentKey(space["_id"].toStr()) ++ ".jsonl") if fs.exists(spaceThumbnailPath(space["_id"].toStr())) ( @@ -406,6 +419,13 @@ def handleDeleteSpace(*serve.Context c) ( c.json(200, {ok: true}) ) +def deleteSpaceLocked(string spaceId) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + void spaceDocs.deleteOne({_id: spaceId}) + deleteSpaceMemberships(spaceId) +) + def handleSetSpaceThumbnail(*serve.Context c) ( object space = (spaceDocs.findById(c.param("id")) ?? {}) if space.len == 0 ( From 5eb17eb6da6f6b5da0a0ce5046c21f3b0595bb40 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:03:23 +0000 Subject: [PATCH 23/28] Apply only the changed fields of a space edit onto the locked re-read, refuse it if the owner moved, and remove judges and publish results under the space lock --- src/community/challenges.osl | 33 +++++++++++++++++++-- src/community/spaces.osl | 57 ++++++++++++++++++++++++++---------- 2 files changed, 72 insertions(+), 18 deletions(-) diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 829cc3c..24cd004 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -455,7 +455,17 @@ def handleRemoveChallengeJudge(*serve.Context c) ( c.forbidden("you cannot manage this challenge") return ) - string username = c.param("username") + removeChallengeJudgeLocked(space["_id"].toStr(), c.param("username")) + c.json(200, {ok: true}) +) + +def removeChallengeJudgeLocked(string spaceId, string username) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return + ) array judges = challengeArray(space, "judges") boolean changed = stringArrayContainsUser(judges, username) space.judges = removeUser(judges, username) @@ -475,7 +485,6 @@ def handleRemoveChallengeJudge(*serve.Context c) ( space.edited = timestamp putSpaceDocument(space) ) - c.json(200, {ok: true}) ) def validChallengeCriterion(object space, string criterionId) boolean ( @@ -683,8 +692,26 @@ def handlePublishChallengeResults(*serve.Context c) ( c.badRequest("at least one entry needs a judge score") return ) + object published = publishChallengeResultsLocked(space["_id"].toStr()) + if published.len == 0 ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while results were being published. Try again."}) + return + ) + c.json(200, {ok: true, space: spaceResponse(published, c)}) +) + +def publishChallengeResultsLocked(string spaceId) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 or timestamp <= space.endsAt.toNum() ( + return {} + ) + if challengeArray(space, if challengeAudienceJudged(space) then "audienceVotes" else "scores").len == 0 ( + return {} + ) space.resultsPublishedAt = timestamp space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + return space ) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 42b1dc5..f182e3f 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -202,6 +202,7 @@ def handleUpdateSpace(*serve.Context c) ( c.notFound("space not found") return ) + string readJson = json.stringify(space) if !canManageSpace(space, c) ( if isOrgOwned(space) and orgAccess(space.owner.toStr(), (space.ownerId ?? "").toStr(), c) == "unavailable" ( c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) @@ -367,37 +368,63 @@ def handleUpdateSpace(*serve.Context c) ( return ) space.edited = timestamp - object saved = saveEditedSpace(space, body.contains("criteria") and space.kind.toStr() == "challenge") + object read = json.parse(readJson, {type: "object"}).unwrap().assert(object) + object saved = saveEditedSpace(read, space) if saved.len == 0 ( c.notFound("space not found") return ) if saved.contains("refused") ( - c.badRequest("judging criteria cannot change after scoring begins") + string refusal = saved.refused.toStr() + if refusal == "criteria" ( + c.badRequest("judging criteria cannot change after scoring begins") + ) else if refusal == "votingMode" ( + c.badRequest("the voting mode cannot change after results are published") + ) else ( + c.json(409, {ok: false, code: "space_changed", error: "This space changed while your edit was being saved. Reload it and try again."}) + ) return ) c.json(200, {ok: true, space: spaceResponse(saved, c)}) ) -def saveEditedSpace(object space, boolean changesCriteria) object ( - sync.lock(spaceWriteLock(space["_id"].toStr())) - defer sync.unlock(spaceWriteLock(space["_id"].toStr())) - object fresh = (spaceDocs.findById(space["_id"].toStr()) ?? {}) +def saveEditedSpace(object read, object edited) object ( + string spaceId = read["_id"].toStr() + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object fresh = (spaceDocs.findById(spaceId) ?? {}) if fresh.len == 0 ( return {} ) - if changesCriteria and challengeArray(fresh, "scores").len > 0 ( - return {refused: "criteria"} + array ownerFields = ["owner", "ownerId", "ownerType"] + for i ownerFields.len ( + string field = ownerFields[i].toStr() + if json.stringify(fresh[field] ?? "") != json.stringify(read[field] ?? "") ( + return {refused: "owner"} + ) ) - array lockedFields = ["projects", "submissions", "participants", "scores", "audienceVotes"] - for i lockedFields.len ( - string field = lockedFields[i].toStr() - if fresh.contains(field) ( - space[field] = fresh[field] + array changed = [] + array keys = edited.getKeys() + for i keys.len ( + string key = keys[i].toStr() + if key != "edited" and (!read.contains(key) or json.stringify(read[key]) != json.stringify(edited[key])) ( + changed.append(key) ) ) - putSpaceDocument(space) - return space + boolean isChallenge = fresh.kind.toStr() == "challenge" + if isChallenge and changed.contains("criteria") and challengeArray(fresh, "scores").len > 0 ( + return {refused: "criteria"} + ) + if isChallenge and changed.contains("votingMode") and challengePhase(fresh) == "results" ( + return {refused: "votingMode"} + ) + for i changed.len ( + string key = changed[i].toStr() + fresh[key] = edited[key] + ) + fresh.edited = edited.edited + putSpaceDocument(fresh) + return fresh ) def handleDeleteSpace(*serve.Context c) ( From 97c3428dfc04af525d301116bf0483ba670c4068 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:12:54 +0000 Subject: [PATCH 24/28] Compare effective voting modes when saving an edit, and invite, remove and cancel curators and invite judges under the space lock --- scripts/e2e_smoke.py | 6 +++ src/community/challenges.osl | 19 ++++++- src/community/spaces.osl | 101 ++++++++++++++++++++++++----------- 3 files changed, 94 insertions(+), 32 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 2bfede9..2e324cb 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1076,6 +1076,11 @@ def org_challenge_flow(server, step, steps, ids, project_path): ids[str(created.get("_id", created.get("id", "")))] = "" challenge = "/v1/spaces/" entered, _ = step("org challenge entry by publisher", "POST", challenge + "/projects/", "sam") + invited, _ = step("org challenge curator invite", "POST", challenge + "/curators", "sam", {"username": "bob"}) + invited_again, _ = step("org challenge curator invite again", "POST", challenge + "/curators", "sam", {"username": "bob"}) + cancelled, _ = step("org challenge curator invite cancel", "DELETE", challenge + "/invitations/bob", "sam") + not_curator, _ = step("org challenge curator remove when not one", "DELETE", challenge + "/curators/bob", "sam") + reinvited, _ = step("org challenge curator invite after cancel", "POST", challenge + "/curators", "sam", {"username": "bob"}) joined, _ = step("org challenge join", "POST", challenge + "/join", "bob", {}) submitter_left, _ = step("org challenge leave refused for the submitter", "DELETE", challenge + "/join", "sam") left, left_body = step("org challenge leave", "DELETE", challenge + "/join", "bob") @@ -1102,6 +1107,7 @@ def org_challenge_flow(server, step, steps, ids, project_path): "the submitter cannot leave": submitter_left == 400, "the submitter removes the entry": removed == 200 and remaining == [], "an org admin deletes the challenge": deleted == 200 and gone == 404, + "curator invites are kept once and can be cancelled": [invited, invited_again, cancelled, not_curator, reinvited] == [201, 400, 200, 200, 201], "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], "both votes counted": counted == 2, diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 24cd004..1deadcb 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -300,13 +300,28 @@ def handleInviteChallengeJudge(*serve.Context c) ( return ) object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} + if !inviteChallengeJudgeLocked(space["_id"].toStr(), invite) ( + c.badRequest("this user is already on the challenge team") + return + ) + addNotification(profile.username.toStr(), contextString(c, "username"), "challenge_judge_invite", {spaceId: space["_id"], spaceTitle: space.title}) + c.json(201, {ok: true, invitation: invite}) +) + +def inviteChallengeJudgeLocked(string spaceId, object invite) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string username = invite.username.toStr() + if space.len == 0 or stringArrayContainsUser(challengeArray(space, "judges"), username) or isChallengeJudgeInvitee(space, username) ( + return false + ) array invites = challengeArray(space, "judgeInvites") invites.append(invite) space.judgeInvites = invites space.edited = timestamp putSpaceDocument(space) - addNotification(profile.username.toStr(), contextString(c, "username"), "challenge_judge_invite", {spaceId: space["_id"], spaceTitle: space.title}) - c.json(201, {ok: true, invitation: invite}) + return true ) def handleJoinChallenge(*serve.Context c) ( diff --git a/src/community/spaces.osl b/src/community/spaces.osl index f182e3f..14efd03 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -415,7 +415,7 @@ def saveEditedSpace(object read, object edited) object ( if isChallenge and changed.contains("criteria") and challengeArray(fresh, "scores").len > 0 ( return {refused: "criteria"} ) - if isChallenge and changed.contains("votingMode") and challengePhase(fresh) == "results" ( + if isChallenge and changed.contains("votingMode") and challengeVotingMode(edited) != challengeVotingMode(fresh) and challengePhase(fresh) == "results" ( return {refused: "votingMode"} ) for i changed.len ( @@ -702,25 +702,86 @@ def handleInviteSpaceCurator(*serve.Context c) ( c.notFound("user not found") return ) - if stringArrayContainsUser(spaceManagers(space), username) ( + object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} + string outcome = inviteCuratorLocked(space["_id"].toStr(), invite) + if outcome == "missing" ( + c.notFound("space not found") + return + ) + if outcome == "curator" ( c.badRequest("this user is already a curator") return ) + if outcome == "invited" ( + c.badRequest("this user already has an invitation") + return + ) + addNotification(profile.username.toStr(), contextString(c, "username"), "space_curator_invite", {spaceId: space["_id"], spaceTitle: space.title}) + c.json(201, {ok: true, invitation: invite}) +) + +def inviteCuratorLocked(string spaceId, object invite) string ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return "missing" + ) + string username = invite.username.toStr() + if stringArrayContainsUser(spaceManagers(space), username) ( + return "curator" + ) array invites = spaceCuratorInvites(space) for i invites.len ( object existing = invites[i].assert(object) - if normalizeUsername(existing.username.toStr()) == usernameKey ( - c.badRequest("this user already has an invitation") - return + if normalizeUsername(existing.username.toStr()) == normalizeUsername(username) ( + return "invited" ) ) - object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} invites.append(invite) space.curatorInvites = invites space.edited = timestamp putSpaceDocument(space) - addNotification(profile.username.toStr(), contextString(c, "username"), "space_curator_invite", {spaceId: space["_id"], spaceTitle: space.title}) - c.json(201, {ok: true, invitation: invite}) + return "saved" +) + +def removeCuratorLocked(string spaceId, string username) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + array managers = if space.len > 0 then spaceManagers(space) else [] + if !stringArrayContainsUser(managers, username) ( + return false + ) + space.managers = removeUser(managers, username) + space.edited = timestamp + putSpaceDocument(space) + return true +) + +def cancelCuratorInviteLocked(string spaceId, string username) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return + ) + array remaining = [] + array invites = spaceCuratorInvites(space) + boolean found = false + for i invites.len ( + object invite = invites[i].assert(object) + if normalizeUsername(invite.username.toStr()) != normalizeUsername(username) ( + remaining.append(invite) + ) else ( + found = true + ) + ) + if found ( + space.curatorInvites = remaining + space.edited = timestamp + putSpaceDocument(space) + ) ) def handleRespondSpaceCuratorInvite(*serve.Context c) ( @@ -775,11 +836,7 @@ def handleRemoveSpaceCurator(*serve.Context c) ( return ) string username = c.param("username") - array managers = spaceManagers(space) - if stringArrayContainsUser(managers, username) ( - space.managers = removeUser(managers, username) - space.edited = timestamp - putSpaceDocument(space) + if removeCuratorLocked(space["_id"].toStr(), username) ( addNotification(username, contextString(c, "username"), "space_curator_removed", {spaceId: space["_id"], spaceTitle: space.title}) ) c.json(200, {ok: true}) @@ -795,23 +852,7 @@ def handleCancelSpaceCuratorInvite(*serve.Context c) ( c.forbidden("only the owner can cancel invitations") return ) - string username = c.param("username") - array remaining = [] - array invites = spaceCuratorInvites(space) - boolean found = false - for i invites.len ( - object invite = invites[i].assert(object) - if normalizeUsername(invite.username.toStr()) != normalizeUsername(username) ( - remaining.append(invite) - ) else ( - found = true - ) - ) - if found ( - space.curatorInvites = remaining - space.edited = timestamp - putSpaceDocument(space) - ) + cancelCuratorInviteLocked(space["_id"].toStr(), c.param("username")) c.json(200, {ok: true}) ) From a48aa359b83ebb1f7b06b64eb42e6d31c463e04a Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:25:05 +0000 Subject: [PATCH 25/28] Recheck curator authority under the space lock, read org snapshots from cache for public challenge views, and smoke test a curator removed during an edit --- scripts/e2e_smoke.py | 14 +++++++-- src/community/challenges.osl | 47 ++++++++++++++++++++++--------- src/community/space-model.osl | 11 ++++++++ src/community/space-responses.osl | 3 ++ src/community/spaces.osl | 24 ++++++++++++---- 5 files changed, 77 insertions(+), 22 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 2e324cb..e9b87ed 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -32,7 +32,7 @@ "monitors": [], "extensions": [], "meta": {"semver": "3.0.0", "vm": "0.2.0", "agent": "smoke"}, } -USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena", "vic": "u_vic"} +USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena", "vic": "u_vic", "wes": "u_wes"} FULL_STORAGE = {"u_dee"} ORGS = { "studio": { @@ -50,7 +50,7 @@ BANNED_USERS = {"banned_user"} SLOW_USERS = {"slow_user": "u_slow"} SLOW_LEDGER_USERS = {"u_lena"} -SLOW_ORG_LISTS = {"u_vic"} +SLOW_ORG_LISTS = {"u_vic", "u_wes"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} CHECK_STEPS = {"org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} @@ -1068,6 +1068,8 @@ def org_flow(server, step, steps, ids): def org_challenge_flow(server, step, steps, ids, project_path): step("accept agreement vic", "POST", "/v1/agreement/accept", "vic", {}) + step("accept agreement wes", "POST", "/v1/agreement/accept", "wes", {}) + step("profile wes", "PUT", "/v1/me/profile", "wes", {"bio": "Curator"}) step("org challenge entry save", "POST", project_path + "/upload", "dee", form=({}, {"project": sb3_archive(project_with_costumes([]))})) step("org challenge entry share", "POST", project_path + "/visibility", "dee", {"visibility": "public"}) now = int(time.time() * 1000) @@ -1081,6 +1083,13 @@ def org_challenge_flow(server, step, steps, ids, project_path): cancelled, _ = step("org challenge curator invite cancel", "DELETE", challenge + "/invitations/bob", "sam") not_curator, _ = step("org challenge curator remove when not one", "DELETE", challenge + "/curators/bob", "sam") reinvited, _ = step("org challenge curator invite after cancel", "POST", challenge + "/curators", "sam", {"username": "bob"}) + step("org challenge curator invite for wes", "POST", challenge + "/curators", "sam", {"username": "wes"}) + accepted, _ = step("org challenge curator accepts", "POST", challenge + "/invitations/respond", "wes", {"accepted": True}) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + slow_edit = pool.submit(step, "org challenge edit by a curator removed meanwhile", "PUT", challenge, "wes", {"rules": "Be kind"}) + time.sleep(ROTUR_DELAY / 4) + removal = pool.submit(step, "org challenge curator removed", "DELETE", challenge + "/curators/wes", "sam") + stale_curator = [slow_edit.result()[0], removal.result()[0]] joined, _ = step("org challenge join", "POST", challenge + "/join", "bob", {}) submitter_left, _ = step("org challenge leave refused for the submitter", "DELETE", challenge + "/join", "sam") left, left_body = step("org challenge leave", "DELETE", challenge + "/join", "bob") @@ -1107,6 +1116,7 @@ def org_challenge_flow(server, step, steps, ids, project_path): "the submitter cannot leave": submitter_left == 400, "the submitter removes the entry": removed == 200 and remaining == [], "an org admin deletes the challenge": deleted == 200 and gone == 404, + "a curator removed during their edit cannot save it": accepted == 200 and stale_curator == [409, 200], "curator invites are kept once and can be cancelled": [invited, invited_again, cancelled, not_curator, reinvited] == [201, 400, 200, 200, 201], "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 1deadcb..ce1841a 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -60,7 +60,7 @@ def challengeOrgSnapshot(object space) object ( if challengeAudienceJudged(space) or !isOrgOwned(space) ( return {ok: false} ) - object snapshot = ownerOrgSnapshot(space) + object snapshot = ownerOrgSnapshotCached(space) string ownerId = (space.ownerId ?? "").toStr() if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( return {ok: false} @@ -300,7 +300,16 @@ def handleInviteChallengeJudge(*serve.Context c) ( return ) object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} - if !inviteChallengeJudgeLocked(space["_id"].toStr(), invite) ( + string invited = inviteChallengeJudgeLocked(space["_id"].toStr(), invite, spaceCuratorOnly(space, c)) + if invited == "missing" ( + c.notFound("challenge not found") + return + ) + if invited == "curator" ( + c.forbidden("you cannot manage this challenge") + return + ) + if invited == "taken" ( c.badRequest("this user is already on the challenge team") return ) @@ -308,20 +317,26 @@ def handleInviteChallengeJudge(*serve.Context c) ( c.json(201, {ok: true, invitation: invite}) ) -def inviteChallengeJudgeLocked(string spaceId, object invite) boolean ( +def inviteChallengeJudgeLocked(string spaceId, object invite, string curator) string ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) string username = invite.username.toStr() - if space.len == 0 or stringArrayContainsUser(challengeArray(space, "judges"), username) or isChallengeJudgeInvitee(space, username) ( - return false + if space.len == 0 ( + return "missing" + ) + if !stillSpaceCurator(space, curator) ( + return "curator" + ) + if stringArrayContainsUser(challengeArray(space, "judges"), username) or isChallengeJudgeInvitee(space, username) ( + return "taken" ) array invites = challengeArray(space, "judgeInvites") invites.append(invite) space.judgeInvites = invites space.edited = timestamp putSpaceDocument(space) - return true + return "saved" ) def handleJoinChallenge(*serve.Context c) ( @@ -470,16 +485,19 @@ def handleRemoveChallengeJudge(*serve.Context c) ( c.forbidden("you cannot manage this challenge") return ) - removeChallengeJudgeLocked(space["_id"].toStr(), c.param("username")) + if !removeChallengeJudgeLocked(space["_id"].toStr(), c.param("username"), spaceCuratorOnly(space, c)) ( + c.forbidden("you cannot manage this challenge") + return + ) c.json(200, {ok: true}) ) -def removeChallengeJudgeLocked(string spaceId, string username) ( +def removeChallengeJudgeLocked(string spaceId, string username, string curator) boolean ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) - if space.len == 0 ( - return + if space.len == 0 or !stillSpaceCurator(space, curator) ( + return false ) array judges = challengeArray(space, "judges") boolean changed = stringArrayContainsUser(judges, username) @@ -500,6 +518,7 @@ def removeChallengeJudgeLocked(string spaceId, string username) ( space.edited = timestamp putSpaceDocument(space) ) + return true ) def validChallengeCriterion(object space, string criterionId) boolean ( @@ -520,8 +539,8 @@ def handleScoreChallengeEntry(*serve.Context c) ( c.notFound("challenge entry not found") return ) + object judgeSnapshot = if isOrgOwned(space) and !challengeAudienceJudged(space) then ownerOrgSnapshot(space) else {ok: true} if !isChallengeJudge(space, contextString(c, "username")) ( - object judgeSnapshot = if isOrgOwned(space) and !challengeAudienceJudged(space) then ownerOrgSnapshot(space) else {ok: true} if !judgeSnapshot.ok and judgeSnapshot.contains("unavailable") and judgeSnapshot.unavailable == true ( c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) return @@ -707,7 +726,7 @@ def handlePublishChallengeResults(*serve.Context c) ( c.badRequest("at least one entry needs a judge score") return ) - object published = publishChallengeResultsLocked(space["_id"].toStr()) + object published = publishChallengeResultsLocked(space["_id"].toStr(), spaceCuratorOnly(space, c)) if published.len == 0 ( c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while results were being published. Try again."}) return @@ -715,11 +734,11 @@ def handlePublishChallengeResults(*serve.Context c) ( c.json(200, {ok: true, space: spaceResponse(published, c)}) ) -def publishChallengeResultsLocked(string spaceId) object ( +def publishChallengeResultsLocked(string spaceId, string curator) object ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) - if space.len == 0 or timestamp <= space.endsAt.toNum() ( + if space.len == 0 or !stillSpaceCurator(space, curator) or timestamp <= space.endsAt.toNum() ( return {} ) if challengeArray(space, if challengeAudienceJudged(space) then "audienceVotes" else "scores").len == 0 ( diff --git a/src/community/space-model.osl b/src/community/space-model.osl index 705f3a7..44764fd 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -134,6 +134,17 @@ def canManageSpace(object space,*serve.Context c) boolean ( return stringArrayContainsUser(spaceManagers(space), username) ) +def spaceCuratorOnly(object space,*serve.Context c) string ( + if contextBool(c, "isAdmin") or isSpaceOwner(space, c) ( + return "" + ) + return contextString(c, "username") +) + +def stillSpaceCurator(object space, string curator) boolean ( + return curator == "" or stringArrayContainsUser(spaceManagers(space), curator) +) + def canViewSpace(object space,*serve.Context c) boolean ( if space.visibility.toStr() == "public" or space.visibility.toStr() == "unlisted" ( return true diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index dbe5ebf..86caf5a 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -14,6 +14,9 @@ def spaceResponse(object space,*serve.Context c) object ( array projects = [] array ids = spaceProjectIds(space) if space.kind.toStr() == "challenge" ( + if contextBool(c, "authenticated") and isOrgOwned(space) and !challengeAudienceJudged(space) ( + void ownerOrgSnapshot(space) + ) projects = challengeProjects(space, c) ) else ( for i ids.len ( diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 14efd03..fad6968 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -369,7 +369,7 @@ def handleUpdateSpace(*serve.Context c) ( ) space.edited = timestamp object read = json.parse(readJson, {type: "object"}).unwrap().assert(object) - object saved = saveEditedSpace(read, space) + object saved = saveEditedSpace(read, space, spaceCuratorOnly(read, c)) if saved.len == 0 ( c.notFound("space not found") return @@ -388,7 +388,7 @@ def handleUpdateSpace(*serve.Context c) ( c.json(200, {ok: true, space: spaceResponse(saved, c)}) ) -def saveEditedSpace(object read, object edited) object ( +def saveEditedSpace(object read, object edited, string curator) object ( string spaceId = read["_id"].toStr() sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) @@ -396,6 +396,9 @@ def saveEditedSpace(object read, object edited) object ( if fresh.len == 0 ( return {} ) + if !stillSpaceCurator(fresh, curator) ( + return {refused: "owner"} + ) array ownerFields = ["owner", "ownerId", "ownerType"] for i ownerFields.len ( string field = ownerFields[i].toStr() @@ -510,7 +513,7 @@ def handleAddSpaceProject(*serve.Context c) ( if isOrgOwned(project) ( participant = if ownsProject then contextString(c, "username") else "" ) - object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages) + object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages, if manages then spaceCuratorOnly(space, c) else "") if added.len == 0 ( c.json(409, {ok: false, code: "space_changed", error: "The space changed while this project was being added. Try again."}) return @@ -522,13 +525,14 @@ def handleAddSpaceProject(*serve.Context c) ( c.json(200, {ok: true, space: spaceResponse(fresh, c)}) ) -def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean asManager) object ( +def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean manages, string curator) object ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) if space.len == 0 ( return {} ) + boolean asManager = manages and stillSpaceCurator(space, curator) if !asManager and (space.openSubmissions != true or (space.kind.toStr() == "challenge" and challengePhase(space) != "submissions")) ( return {} ) @@ -561,6 +565,7 @@ def handleRemoveSpaceProject(*serve.Context c) ( ) object project = (projectSearchDocs.findById(c.param("project")) ?? {}) boolean allowed = canManageSpace(space, c) + string curator = if allowed then spaceCuratorOnly(space, c) else "" if !allowed and project.len > 0 ( string ownership = searchEntryOwnership(project, c) if ownership == "unavailable" ( @@ -573,21 +578,28 @@ def handleRemoveSpaceProject(*serve.Context c) ( c.forbidden("you cannot remove this project") return ) - object saved = removeProjectFromSpaceLocked(space["_id"].toStr(), c.param("project")) + object saved = removeProjectFromSpaceLocked(space["_id"].toStr(), c.param("project"), curator) if saved.len == 0 ( c.notFound("space not found") return ) + if saved.contains("refused") ( + c.forbidden("you cannot remove this project") + return + ) c.json(200, {ok: true, space: spaceResponse(saved, c)}) ) -def removeProjectFromSpaceLocked(string spaceId, string projectId) object ( +def removeProjectFromSpaceLocked(string spaceId, string projectId, string curator) object ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) if space.len == 0 ( return {} ) + if !stillSpaceCurator(space, curator) ( + return {refused: "curator"} + ) space.projects = removeString(spaceProjectIds(space), projectId) if space.kind.toStr() == "challenge" ( array submissions = challengeArray(space, "submissions") From 50156b6fe40b1ffabcd690c42522db696d76ddb1 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:34:14 +0000 Subject: [PATCH 26/28] Require ownership when a removed curator's add falls back to participant rules, recheck challenge date order under the space lock, and let an entry's owner remove it without the curator recheck --- src/community/spaces.osl | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index fad6968..48a5395 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -378,6 +378,8 @@ def handleUpdateSpace(*serve.Context c) ( string refusal = saved.refused.toStr() if refusal == "criteria" ( c.badRequest("judging criteria cannot change after scoring begins") + ) else if refusal == "dates" ( + c.badRequest("challenge dates must be in order") ) else if refusal == "votingMode" ( c.badRequest("the voting mode cannot change after results are published") ) else ( @@ -425,6 +427,9 @@ def saveEditedSpace(object read, object edited, string curator) object ( string key = changed[i].toStr() fresh[key] = edited[key] ) + if isChallenge and (fresh.startsAt.toNum() <= 0 or fresh.endsAt.toNum() <= fresh.startsAt.toNum() or (fresh.judgingEndsAt ?? 0).toNum() <= fresh.endsAt.toNum()) ( + return {refused: "dates"} + ) fresh.edited = edited.edited putSpaceDocument(fresh) return fresh @@ -513,7 +518,7 @@ def handleAddSpaceProject(*serve.Context c) ( if isOrgOwned(project) ( participant = if ownsProject then contextString(c, "username") else "" ) - object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages, if manages then spaceCuratorOnly(space, c) else "") + object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages, if manages then spaceCuratorOnly(space, c) else "", ownsProject) if added.len == 0 ( c.json(409, {ok: false, code: "space_changed", error: "The space changed while this project was being added. Try again."}) return @@ -525,7 +530,7 @@ def handleAddSpaceProject(*serve.Context c) ( c.json(200, {ok: true, space: spaceResponse(fresh, c)}) ) -def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean manages, string curator) object ( +def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean manages, string curator, boolean ownsProject) object ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) @@ -533,7 +538,7 @@ def addProjectToSpace(string spaceId, object project, string submitter, string p return {} ) boolean asManager = manages and stillSpaceCurator(space, curator) - if !asManager and (space.openSubmissions != true or (space.kind.toStr() == "challenge" and challengePhase(space) != "submissions")) ( + if !asManager and (!ownsProject or space.openSubmissions != true or (space.kind.toStr() == "challenge" and challengePhase(space) != "submissions")) ( return {} ) array ids = spaceProjectIds(space) @@ -566,6 +571,9 @@ def handleRemoveSpaceProject(*serve.Context c) ( object project = (projectSearchDocs.findById(c.param("project")) ?? {}) boolean allowed = canManageSpace(space, c) string curator = if allowed then spaceCuratorOnly(space, c) else "" + if curator != "" and project.len > 0 and searchEntryOwnership(project, c) == "yes" ( + curator = "" + ) if !allowed and project.len > 0 ( string ownership = searchEntryOwnership(project, c) if ownership == "unavailable" ( From 7334ab1bfb13ed3d904db195b9e9009d9b6dcee1 Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:45:03 +0000 Subject: [PATCH 27/28] Count comments, follow spaces and set studio thumbnails under the space lock on a fresh read, and smoke test comments and follows --- scripts/e2e_smoke.py | 9 +++++ src/community/space-comments.osl | 37 ++++++++++++----- src/community/space-responses.osl | 3 +- src/community/spaces.osl | 67 ++++++++++++++++++++++++++----- 4 files changed, 94 insertions(+), 22 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index e9b87ed..9510b2c 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -1090,6 +1090,14 @@ def org_challenge_flow(server, step, steps, ids, project_path): time.sleep(ROTUR_DELAY / 4) removal = pool.submit(step, "org challenge curator removed", "DELETE", challenge + "/curators/wes", "sam") stale_curator = [slow_edit.result()[0], removal.result()[0]] + commented, comment_body = step("org challenge comment", "POST", challenge + "/comments", "bob", {"content": "Good luck"}) + comment_id = ((comment_body or {}).get("comment") or {}).get("id", "") if isinstance(comment_body, dict) else "" + step("org challenge second comment", "POST", challenge + "/comments", "alice", {"content": "Have fun"}) + uncommented, _ = step("org challenge comment delete", "DELETE", challenge + "/comments/" + str(comment_id), "bob") + followed, follow_body = step("org challenge follow", "POST", challenge + "/follow", "bob", {}) + unfollowed, unfollow_body = step("org challenge unfollow", "DELETE", challenge + "/follow", "bob") + status, counted_space = step("org challenge counts", "GET", challenge, "bob") + counted_space = counted_space.get("space", {}) if isinstance(counted_space, dict) else {} joined, _ = step("org challenge join", "POST", challenge + "/join", "bob", {}) submitter_left, _ = step("org challenge leave refused for the submitter", "DELETE", challenge + "/join", "sam") left, left_body = step("org challenge leave", "DELETE", challenge + "/join", "bob") @@ -1117,6 +1125,7 @@ def org_challenge_flow(server, step, steps, ids, project_path): "the submitter removes the entry": removed == 200 and remaining == [], "an org admin deletes the challenge": deleted == 200 and gone == 404, "a curator removed during their edit cannot save it": accepted == 200 and stale_curator == [409, 200], + "comments and follows keep their counts": [commented, uncommented, followed, unfollowed] == [201, 200, 200, 200] and counted_space.get("commentCount") == 1 and (follow_body or {}).get("followers") == 1 and (unfollow_body or {}).get("followers") == 0, "curator invites are kept once and can be cancelled": [invited, invited_again, cancelled, not_curator, reinvited] == [201, 400, 200, 200, 201], "own entry vote refused": own == 403, "outside votes saved": votes == [200, 200], diff --git a/src/community/space-comments.osl b/src/community/space-comments.osl index 288f9bf..dd6bb42 100644 --- a/src/community/space-comments.osl +++ b/src/community/space-comments.osl @@ -29,12 +29,7 @@ def handleCreateSpaceComment(*serve.Context c) ( c.badRequest(created.error.toStr()) return ) - if space.contains("commentCount") ( - space.commentCount = space.commentCount.toNum() + 1 - ) else ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len - ) - putSpaceDocument(space) + adjustSpaceCommentCountLocked(space["_id"].toStr(), 1) string commenter = contextString(c, "username") string parentAuthor = created.parentAuthor.toStr() string newCommentId = created.comment.id.toStr() @@ -64,13 +59,37 @@ def handleDeleteSpaceComment(*serve.Context c) ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return ) + adjustSpaceCommentCountLocked(space["_id"].toStr(), 0 - deleted.removed.toNum()) + c.json(200, {ok: true}) +) + +def adjustSpaceCommentCountLocked(string spaceId, number delta) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return + ) if space.contains("commentCount") ( - space.commentCount = clampNumber(space.commentCount.toNum() - deleted.removed.toNum(), 0, space.commentCount.toNum()) + space.commentCount = clampNumber(space.commentCount.toNum() + delta, 0, space.commentCount.toNum() + 1000000) ) else ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len + space.commentCount = loadComments(spaceCommentKey(spaceId)).len ) putSpaceDocument(space) - c.json(200, {ok: true}) +) + +def ensureSpaceCommentCountLocked(string spaceId) number ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return loadComments(spaceCommentKey(spaceId)).len + ) + if !space.contains("commentCount") ( + space.commentCount = loadComments(spaceCommentKey(spaceId)).len + putSpaceDocument(space) + ) + return space.commentCount.toNum() ) def handleEditSpaceComment(*serve.Context c) ( diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index 86caf5a..f9f499c 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -8,8 +8,7 @@ def spaceTotalPlaytime(array ids) number ( def spaceResponse(object space,*serve.Context c) object ( if !space.contains("commentCount") ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len - putSpaceDocument(space) + space.commentCount = ensureSpaceCommentCountLocked(space["_id"].toStr()) ) array projects = [] array ids = spaceProjectIds(space) diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 48a5395..8e97f66 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -471,6 +471,7 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.forbidden("you cannot change this studio thumbnail") return ) + string curator = spaceCuratorOnly(space, c) auto fileResult = c.formFile("thumbnail") if fileResult.isErr() ( c.badRequest("missing thumbnail file") @@ -481,13 +482,38 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.badRequest("thumbnail too large") return ) - if !fs.writeFileBytes(spaceThumbnailPath(space["_id"].toStr()), thumbnail.data) ( + string outcome = saveSpaceThumbnailLocked(space["_id"].toStr(), curator, thumbnail.data) + if outcome == "missing" ( + c.notFound("space not found") + return + ) + if outcome == "curator" ( + c.forbidden("you cannot change this studio thumbnail") + return + ) + if outcome == "failed" ( c.internalError("thumbnail save failed") return ) + c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(space)}) +) + +def saveSpaceThumbnailLocked(string spaceId, string curator, byte[] data) string ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return "missing" + ) + if !stillSpaceCurator(space, curator) ( + return "curator" + ) + if !fs.writeFileBytes(spaceThumbnailPath(spaceId), data) ( + return "failed" + ) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(space)}) + return "saved" ) def handleAddSpaceProject(*serve.Context c) ( @@ -631,13 +657,33 @@ def handleFollowSpace(*serve.Context c) ( c.notFound("space not found") return ) + number count = followSpaceLocked(space["_id"].toStr(), contextString(c, "username"), true) + if count < 0 ( + c.notFound("space not found") + return + ) + c.json(200, {ok: true, following: true, followers: count}) +) + +def followSpaceLocked(string spaceId, string username, boolean follow) number ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return -1 + ) array followers = spaceFollowers(space) - if !stringArrayContainsUser(followers, contextString(c, "username")) ( - followers.append(contextString(c, "username")) + boolean present = stringArrayContainsUser(followers, username) + if follow and !present ( + followers.append(username) + space.followers = followers + putSpaceDocument(space) + ) else if !follow and present ( + followers = removeUser(followers, username) space.followers = followers putSpaceDocument(space) ) - c.json(200, {ok: true, following: true, followers: followers.len}) + return followers.len ) def handleUnfollowSpace(*serve.Context c) ( @@ -646,13 +692,12 @@ def handleUnfollowSpace(*serve.Context c) ( c.notFound("space not found") return ) - array followers = spaceFollowers(space) - if stringArrayContainsUser(followers, contextString(c, "username")) ( - followers = removeUser(followers, contextString(c, "username")) - space.followers = followers - putSpaceDocument(space) + number count = followSpaceLocked(space["_id"].toStr(), contextString(c, "username"), false) + if count < 0 ( + c.notFound("space not found") + return ) - c.json(200, {ok: true, following: false, followers: followers.len}) + c.json(200, {ok: true, following: false, followers: count}) ) def handleMySpaces(*serve.Context c) ( From e793e56fd8a71b92727fcaf609a43ee17080370a Mon Sep 17 00:00:00 2001 From: Mistium <92952823+Mistium@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:54:02 +0000 Subject: [PATCH 28/28] Return the saved studio thumbnail url and smoke test studio thumbnails --- scripts/e2e_smoke.py | 14 ++++++++++++-- src/community/spaces.osl | 15 ++++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index 9510b2c..6d5518a 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -53,7 +53,7 @@ SLOW_ORG_LISTS = {"u_vic", "u_wes"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} -CHECK_STEPS = {"org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} +CHECK_STEPS = {"org studio thumbnail checks", "org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} UNORDERED = {"largest"} @@ -1050,7 +1050,17 @@ def org_flow(server, step, steps, ids): step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) step("org move out refused for a publisher", "PUT", "/v1/projects/", "dee", {"owner": "dee"}) step("org transfer back", "PUT", "/v1/projects/", "sam", {"owner": "dee"}) - step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) + status, studio = step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) + studio = studio.get("space", {}) if isinstance(studio, dict) else {} + ids[str(studio.get("_id", studio.get("id", "")))] = "" + time.sleep(0.01) + status, thumbed = step("org studio thumbnail by publisher", "POST", "/v1/spaces//thumbnail", "sam", form=({}, {"thumbnail": b"\x89PNG studio thumbnail"})) + status, studio_after = step("org studio after thumbnail", "GET", "/v1/spaces/", "sam") + studio_after = studio_after.get("space", {}) if isinstance(studio_after, dict) else {} + steps.append({"step": "org studio thumbnail checks", "status": 0, "body": { + "the thumbnail is saved": status == 200 and isinstance(thumbed, dict) and bool(thumbed.get("thumbnailUrl")), + "the returned url matches the saved space": isinstance(thumbed, dict) and thumbed.get("thumbnailUrl") == studio_after.get("thumbnailUrl"), + }}) status, own_space = step("org own space create", "POST", "/v1/spaces", "sam", {"title": "Sam's space", "kind": "collection"}) own_space = own_space.get("space", {}) if isinstance(own_space, dict) else {} ids[str(own_space.get("_id", own_space.get("id", "")))] = "" diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 8e97f66..d97dfd7 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -482,7 +482,8 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.badRequest("thumbnail too large") return ) - string outcome = saveSpaceThumbnailLocked(space["_id"].toStr(), curator, thumbnail.data) + object saved = saveSpaceThumbnailLocked(space["_id"].toStr(), curator, thumbnail.data) + string outcome = saved.outcome.toStr() if outcome == "missing" ( c.notFound("space not found") return @@ -495,25 +496,25 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.internalError("thumbnail save failed") return ) - c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(space)}) + c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(saved.space.assert(object))}) ) -def saveSpaceThumbnailLocked(string spaceId, string curator, byte[] data) string ( +def saveSpaceThumbnailLocked(string spaceId, string curator, byte[] data) object ( sync.lock(spaceWriteLock(spaceId)) defer sync.unlock(spaceWriteLock(spaceId)) object space = (spaceDocs.findById(spaceId) ?? {}) if space.len == 0 ( - return "missing" + return {outcome: "missing"} ) if !stillSpaceCurator(space, curator) ( - return "curator" + return {outcome: "curator"} ) if !fs.writeFileBytes(spaceThumbnailPath(spaceId), data) ( - return "failed" + return {outcome: "failed"} ) space.edited = timestamp putSpaceDocument(space) - return "saved" + return {outcome: "saved", space: space} ) def handleAddSpaceProject(*serve.Context c) (