Add page-level permissions and guests

Pages can now be shared with people and groups beyond their space, and
restricted so that only those grants count. A grant covers the page and
everything under it. Space admins always keep access, and an editor who
restricts a page keeps editor through a grant of their own.

Sharing a page with someone from the organization who is outside the
workspace adds them as a guest. Anyone else gets a guest invite that
carries the page grant, which is made when they accept. Guests see a
"limited" space holding only the pages shared with them.

The page tree, breadcrumbs, search, favorites, recents, trash and import
all follow the page role. Public links skip restricted subtrees. Grants
are cleaned up when a member leaves or a group is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 21:39:50 +01:00
1 parent 8aeebbff12
commit 7968e82cc2
29 files changed
+2277 -119

No files matched your search

@@ -0,0 +1,56 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// Page-level permissions. A grant gives a user or group a role on a page and
// its subtree (on top of their space role); pages.restricted makes a subtree
// ignore the space role, so only its own grants count (see
// Server/internal/access/pages.go). space is copied from the page so one
// query finds a caller's grants in a space. Invites can carry a page grant:
// sharing a page with someone outside the workspace invites them as a guest.
migrate(
(app) => {
const pages = app.findCollectionByNameOrId("pages");
const spaces = app.findCollectionByNameOrId("spaces");
pages.fields.add(new BoolField({ name: "restricted" }));
app.save(pages);
app.save(
new Collection({
type: "base",
name: "page_permissions",
fields: [
{ name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "space", type: "relation", collectionId: spaces.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "principal_type", type: "select", values: ["user", "group"], maxSelect: 1, required: true },
{ name: "principal_id", type: "text", required: true },
{ name: "role", type: "select", values: ["editor", "commenter", "viewer"], maxSelect: 1, required: true },
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_pp_unique ON page_permissions (page, principal_type, principal_id)",
"CREATE INDEX idx_pp_space ON page_permissions (space, principal_type, principal_id)",
],
}),
);
const invites = app.findCollectionByNameOrId("invites");
invites.fields.add(new RelationField({ name: "page", collectionId: pages.id, maxSelect: 1, cascadeDelete: true }));
invites.fields.add(new SelectField({ name: "page_role", values: ["editor", "commenter", "viewer"], maxSelect: 1 }));
app.save(invites);
},
(app) => {
const invites = app.findCollectionByNameOrId("invites");
invites.fields.removeByName("page_role");
invites.fields.removeByName("page");
app.save(invites);
try {
app.delete(app.findCollectionByNameOrId("page_permissions"));
} catch (_) {}
const pages = app.findCollectionByNameOrId("pages");
pages.fields.removeByName("restricted");
app.save(pages);
},
);
+28
View File
@@ -44,6 +44,11 @@ export type AdminHealth = Schemas["AdminHealth"];
export type Job = Schemas["Job"];
export type Backup = Schemas["Backup"];
export type SharedPage = Schemas["SharedPage"];
export type PageGrantRole = Schemas["PageGrantRole"];
export type PageGrant = Schemas["PageGrant"];
export type PageInvite = Schemas["PageInvite"];
export type PageAccess = Schemas["PageAccess"];
export type SharePageResult = Schemas["SharePageResult"];
export type SearchResult = Schemas["SearchResult"];
export type GroupRequest = Schemas["GroupRequest"];
export type SpaceGroup = Schemas["SpaceGroup"];
@@ -339,6 +344,29 @@ export function createClient(opts: ClientOptions) {
setShareLink: (id: string, includeSubpages: boolean) =>
request<ShareLink>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/share`, { includeSubpages }),
deleteShareLink: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/share`),
/** Who has access beyond the space's members: grants and the restricted switch. */
access: (id: string) => request<PageAccess>("GET", `/api/v1/pages/${encodeURIComponent(id)}/access`),
setRestricted: (id: string, restricted: boolean) =>
request<PageAccess>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}/access`, { restricted }),
/** Shares with someone by email; people outside the workspace are invited as guests. */
shareWithUser: (id: string, email: string, role: PageGrantRole) =>
request<SharePageResult>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/access/users`, { email, role }),
unshareUser: (id: string, userId: string) =>
request<PageAccess>(
"DELETE",
`/api/v1/pages/${encodeURIComponent(id)}/access/users/${encodeURIComponent(userId)}`,
),
shareWithGroup: (id: string, groupId: string, role: PageGrantRole) =>
request<PageAccess>(
"PUT",
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
{ role },
),
unshareGroup: (id: string, groupId: string) =>
request<PageAccess>(
"DELETE",
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
),
export: (id: string, format: "markdown" | "html") =>
download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`),
/** Records that the user opened the page, for their recent list. */
+311 -3
View File
@@ -1190,6 +1190,92 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/access": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** Who has access to the page beyond the space's members (viewer) */
get: operations["getPageAccess"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
/**
* Restrict the page and its subpages to the people it is shared with, or lift that (editor)
* @description Space admins always keep access. An editor who restricts a page keeps editor on it through a grant.
*/
patch: operations["setPageRestricted"];
trace?: never;
};
"/api/v1/pages/{id}/access/users": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
/**
* Share the page and its subpages with someone by email (editor)
* @description A workspace member gets the role on the page. Someone from the workspace's organization who is not in the workspace joins it as a guest. Anyone else is invited as a guest (workspace members only).
*/
put: operations["sharePageWithUser"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/access/users/{userId}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
userId: string;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/** Remove someone's grant on the page (editor, or the person themselves) */
delete: operations["unsharePageWithUser"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/access/groups/{groupId}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
groupId: string;
};
cookie?: never;
};
get?: never;
/** Share the page and its subpages with a group of the workspace (editor) */
put: operations["sharePageWithGroup"];
post?: never;
/** Remove a group's grant on the page (editor) */
delete: operations["unsharePageWithGroup"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/share": {
parameters: {
query?: never;
@@ -1549,7 +1635,9 @@ export interface components {
description: string;
visibility: components["schemas"]["SpaceVisibility"];
defaultRole: components["schemas"]["SpaceDefaultRole"];
role: components["schemas"]["SpaceRole"];
role: components["schemas"]["SpaceCallerRole"];
/** @description The caller cannot open the space itself and sees only pages shared with them */
limited: boolean;
created: string;
};
SpaceMember: {
@@ -1562,12 +1650,14 @@ export interface components {
};
PageNode: {
id: string;
/** @description Parent page id; empty at the top level */
/** @description Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor. */
parent: string;
title: string;
icon: string;
/** @description Fractional sort key among siblings */
position: string;
/** @description This page itself is restricted */
restricted: boolean;
updated: string;
};
PageRef: {
@@ -1588,12 +1678,61 @@ export interface components {
deletedAt: string;
/** @description The page or one of its ancestors is in the trash */
inTrash: boolean;
/** @description Root first */
/** @description Root first; pages the caller cannot open are left out */
ancestors: components["schemas"]["PageRef"][];
/** @description The caller's role on this page */
role: components["schemas"]["SpaceRole"];
/** @description The page or one of its ancestors is restricted */
restricted: boolean;
/** @description In the caller's favorites */
favorite: boolean;
};
/** @enum {string} */
PageGrantRole: "editor" | "commenter" | "viewer";
/**
* @description The caller's space role; empty when they see only pages shared with them
* @enum {string}
*/
SpaceCallerRole: "admin" | "editor" | "commenter" | "viewer" | "";
PageGrant: {
/** @enum {string} */
type: "user" | "group";
id: string;
name: string;
/** @description Empty for groups */
email: string;
role: components["schemas"]["PageGrantRole"];
/** @description Where the grant was made */
page: components["schemas"]["PageRef"];
/** @description Granted on an ancestor */
inherited: boolean;
};
PageInvite: {
id: string;
email: string;
role: components["schemas"]["PageGrantRole"];
expires: string;
};
PageAccess: {
/** @description The page or an ancestor is restricted; space members then see it only through grants */
restricted: boolean;
/** @description The restricted ancestor, when the restriction comes from one */
inheritedFrom: components["schemas"]["PageRef"] | null;
/** @description This page's grants first */
grants: components["schemas"]["PageGrant"][];
/** @description Pending guest invites for this page (editors only) */
invites: components["schemas"]["PageInvite"][];
/** @description The caller's role on this page */
role: components["schemas"]["SpaceRole"];
canManage: boolean;
/** @description May share with people outside the workspace */
canInvite: boolean;
};
SharePageResult: {
access: components["schemas"]["PageAccess"];
/** @description Set when the person was invited as a guest; the grant is made when they accept */
invite: components["schemas"]["Invite"] | null;
};
PageContent: {
/** @description Tiptap JSON with type "doc"; null for a page that was never edited */
content: {
@@ -4045,6 +4184,175 @@ export interface operations {
404: components["responses"]["Error"];
};
};
getPageAccess: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageAccess"];
};
};
404: components["responses"]["Error"];
};
};
setPageRestricted: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
restricted: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageAccess"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
sharePageWithUser: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** Format: email */
email: string;
role: components["schemas"]["PageGrantRole"];
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["SharePageResult"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
409: components["responses"]["Error"];
};
};
unsharePageWithUser: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
userId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The page's access afterwards */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageAccess"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
sharePageWithGroup: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
groupId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
role: components["schemas"]["PageGrantRole"];
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageAccess"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
unsharePageWithGroup: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
groupId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The page's access afterwards */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageAccess"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
getShareLink: {
parameters: {
query?: never;
+233 -4
View File
@@ -469,6 +469,7 @@ class Space {
required this.visibility,
required this.defaultRole,
required this.role,
required this.limited,
required this.created,
});
@@ -481,7 +482,8 @@ class Space {
description: json['description'] as String,
visibility: SpaceVisibility.fromJson(json['visibility'] as String),
defaultRole: SpaceDefaultRole.fromJson(json['defaultRole'] as String),
role: SpaceRole.fromJson(json['role'] as String),
role: SpaceCallerRole.fromJson(json['role'] as String),
limited: json['limited'] as bool,
created: json['created'] as String,
);
@@ -501,7 +503,10 @@ class Space {
final SpaceDefaultRole defaultRole;
final SpaceRole role;
final SpaceCallerRole role;
/// The caller cannot open the space itself and sees only pages shared with them
final bool limited;
final String created;
@@ -515,6 +520,7 @@ class Space {
'visibility': visibility.toJson(),
'defaultRole': defaultRole.toJson(),
'role': role.toJson(),
'limited': limited,
'created': created,
};
}
@@ -567,6 +573,7 @@ class PageNode {
required this.title,
required this.icon,
required this.position,
required this.restricted,
required this.updated,
});
@@ -576,12 +583,13 @@ class PageNode {
title: json['title'] as String,
icon: json['icon'] as String,
position: json['position'] as String,
restricted: json['restricted'] as bool,
updated: json['updated'] as String,
);
final String id;
/// Parent page id; empty at the top level
/// Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor.
final String parent;
final String title;
@@ -591,6 +599,9 @@ class PageNode {
/// Fractional sort key among siblings
final String position;
/// This page itself is restricted
final bool restricted;
final String updated;
Map<String, dynamic> toJson() => {
@@ -599,6 +610,7 @@ class PageNode {
'title': title,
'icon': icon,
'position': position,
'restricted': restricted,
'updated': updated,
};
}
@@ -635,6 +647,7 @@ class Page {
required this.inTrash,
required this.ancestors,
required this.role,
required this.restricted,
required this.favorite,
});
@@ -653,6 +666,7 @@ class Page {
.map((e) => PageRef.fromJson(e as Map<String, dynamic>))
.toList(),
role: SpaceRole.fromJson(json['role'] as String),
restricted: json['restricted'] as bool,
favorite: json['favorite'] as bool,
);
@@ -678,11 +692,15 @@ class Page {
/// The page or one of its ancestors is in the trash
final bool inTrash;
/// Root first
/// Root first; pages the caller cannot open are left out
final List<PageRef> ancestors;
/// The caller's role on this page
final SpaceRole role;
/// The page or one of its ancestors is restricted
final bool restricted;
/// In the caller's favorites
final bool favorite;
@@ -699,10 +717,221 @@ class Page {
'inTrash': inTrash,
'ancestors': ancestors.map((e) => e.toJson()).toList(),
'role': role.toJson(),
'restricted': restricted,
'favorite': favorite,
};
}
enum PageGrantRole {
editor('editor'),
commenter('commenter'),
viewer('viewer');
const PageGrantRole(this.value);
final String value;
static PageGrantRole fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown PageGrantRole', value),
);
String toJson() => value;
}
/// The caller's space role; empty when they see only pages shared with them
enum SpaceCallerRole {
admin('admin'),
editor('editor'),
commenter('commenter'),
viewer('viewer'),
none('');
const SpaceCallerRole(this.value);
final String value;
static SpaceCallerRole fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown SpaceCallerRole', value),
);
String toJson() => value;
}
enum PageGrantType {
user('user'),
group('group');
const PageGrantType(this.value);
final String value;
static PageGrantType fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown PageGrantType', value),
);
String toJson() => value;
}
class PageGrant {
const PageGrant({
required this.type,
required this.id,
required this.name,
required this.email,
required this.role,
required this.page,
required this.inherited,
});
factory PageGrant.fromJson(Map<String, dynamic> json) => PageGrant(
type: PageGrantType.fromJson(json['type'] as String),
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
role: PageGrantRole.fromJson(json['role'] as String),
page: PageRef.fromJson(json['page'] as Map<String, dynamic>),
inherited: json['inherited'] as bool,
);
final PageGrantType type;
final String id;
final String name;
/// Empty for groups
final String email;
final PageGrantRole role;
/// Where the grant was made
final PageRef page;
/// Granted on an ancestor
final bool inherited;
Map<String, dynamic> toJson() => {
'type': type.toJson(),
'id': id,
'name': name,
'email': email,
'role': role.toJson(),
'page': page.toJson(),
'inherited': inherited,
};
}
class PageInvite {
const PageInvite({
required this.id,
required this.email,
required this.role,
required this.expires,
});
factory PageInvite.fromJson(Map<String, dynamic> json) => PageInvite(
id: json['id'] as String,
email: json['email'] as String,
role: PageGrantRole.fromJson(json['role'] as String),
expires: json['expires'] as String,
);
final String id;
final String email;
final PageGrantRole role;
final String expires;
Map<String, dynamic> toJson() => {
'id': id,
'email': email,
'role': role.toJson(),
'expires': expires,
};
}
class PageAccess {
const PageAccess({
required this.restricted,
required this.inheritedFrom,
required this.grants,
required this.invites,
required this.role,
required this.canManage,
required this.canInvite,
});
factory PageAccess.fromJson(Map<String, dynamic> json) => PageAccess(
restricted: json['restricted'] as bool,
inheritedFrom: json['inheritedFrom'] == null
? null
: PageRef.fromJson(json['inheritedFrom'] as Map<String, dynamic>),
grants: (json['grants'] as List)
.map((e) => PageGrant.fromJson(e as Map<String, dynamic>))
.toList(),
invites: (json['invites'] as List)
.map((e) => PageInvite.fromJson(e as Map<String, dynamic>))
.toList(),
role: SpaceRole.fromJson(json['role'] as String),
canManage: json['canManage'] as bool,
canInvite: json['canInvite'] as bool,
);
/// The page or an ancestor is restricted; space members then see it only through grants
final bool restricted;
/// The restricted ancestor, when the restriction comes from one
final PageRef? inheritedFrom;
/// This page's grants first
final List<PageGrant> grants;
/// Pending guest invites for this page (editors only)
final List<PageInvite> invites;
/// The caller's role on this page
final SpaceRole role;
final bool canManage;
/// May share with people outside the workspace
final bool canInvite;
Map<String, dynamic> toJson() => {
'restricted': restricted,
'inheritedFrom': inheritedFrom?.toJson(),
'grants': grants.map((e) => e.toJson()).toList(),
'invites': invites.map((e) => e.toJson()).toList(),
'role': role.toJson(),
'canManage': canManage,
'canInvite': canInvite,
};
}
class SharePageResult {
const SharePageResult({required this.access, required this.invite});
factory SharePageResult.fromJson(Map<String, dynamic> json) =>
SharePageResult(
access: PageAccess.fromJson(json['access'] as Map<String, dynamic>),
invite: json['invite'] == null
? null
: Invite.fromJson(json['invite'] as Map<String, dynamic>),
);
final PageAccess access;
/// Set when the person was invited as a guest; the grant is made when they accept
final Invite? invite;
Map<String, dynamic> toJson() => {
'access': access.toJson(),
'invite': invite?.toJson(),
};
}
class PageContent {
const PageContent({required this.content, required this.updated});
+2 -1
View File
@@ -101,7 +101,8 @@ class _Generator {
_doc(b, s['description'] as String?, '');
b.writeln('enum $name {');
for (final v in values) {
b.writeln(" ${_ident(v)}('$v'),");
// An empty value means "none" (e.g. SpaceCallerRole).
b.writeln(" ${v.isEmpty ? 'none' : _ident(v)}('$v'),");
}
b.writeln(' ;');
b.writeln();
+107
View File
@@ -0,0 +1,107 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package access
import "docwell/server/internal/apperr"
// ---- Page permissions ------------------------------------------------------
//
// Pages inherit their space's rights, and two things refine them per page:
//
// grant a user or group gets editor, commenter or viewer on a page and
// everything under it, on top of their space role. This is how a
// page is shared with a guest who cannot open the space.
// restricted a restricted page and its subtree ignore the space role and
// the grants above it: only grants on the restricted page or
// below it count. Space admins always keep admin.
//
// Page roles use the space role names; grants never give admin.
// PageNode is one step from a page up to its space root, as seen by one
// caller: whether the page is restricted and the caller's best grant on it
// ("" when none).
type PageNode struct {
Restricted bool
Grant string
}
// ValidPageGrant reports whether role can be granted on a page.
func ValidPageGrant(role string) bool { return ValidDefaultRole(role) }
// PageRole is the effective role on a page for someone with space role
// spaceRole ("" when they cannot open the space), given the chain from the
// page itself up to its top-level ancestor. "" = no access.
func PageRole(spaceRole string, chain []PageNode) string {
if SpaceAtLeast(spaceRole, SpaceAdmin) {
return SpaceAdmin
}
best := ""
for _, n := range chain {
if ValidPageGrant(n.Grant) {
best = HigherSpaceRole(best, n.Grant)
}
if n.Restricted {
return best
}
}
return HigherSpaceRole(spaceRole, best)
}
// ManagePageAccess (grants and the restricted switch) needs editor on the page.
func ManagePageAccess(pageRole string) error {
if err := ViewSpace(pageRole); err != nil {
return apperr.NotFound("page not found")
}
if !SpaceAtLeast(pageRole, SpaceEditor) {
return apperr.Forbidden("editor role required")
}
return nil
}
// SetPageGrant checks granting role on a page to a user whose workspace role
// is targetWsRole ("" for a group). Workspace admins already manage every
// page, so granting them anything is pointless.
func SetPageGrant(actorPageRole, targetWsRole string, isGroup bool, role string) error {
if !ValidPageGrant(role) {
return apperr.Invalid("role must be editor, commenter or viewer")
}
if err := ManagePageAccess(actorPageRole); err != nil {
return err
}
if isGroup {
return nil
}
if targetWsRole == "" {
return apperr.Invalid("that user is not a member of this workspace")
}
if AtLeast(targetWsRole, WorkspaceAdmin) {
return apperr.Invalid("workspace admins already manage every page")
}
return nil
}
// InvitePageGuest checks sharing a page with someone outside the workspace,
// who joins it as a guest. Workspace members and above may; guests may not
// bring in more people.
func InvitePageGuest(actorWsRole, actorPageRole string) error {
if err := ManagePageAccess(actorPageRole); err != nil {
return err
}
if !AtLeast(actorWsRole, WorkspaceMember) {
return apperr.Forbidden("guests cannot invite people")
}
return nil
}
// CreatePageUnder checks creating a page: under a parent it needs editor on
// the parent; at the top level, editor on the space.
func CreatePageUnder(spaceRole, parentRole string, topLevel bool) error {
if topLevel {
if spaceRole == "" {
// Someone who sees only shared pages still sees the space.
return apperr.Forbidden("only people with access to the whole space can add top-level pages")
}
return EditPages(spaceRole)
}
return EditPages(parentRole)
}
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package access
import (
"testing"
"docwell/server/internal/apperr"
)
func TestPageRole(t *testing.T) {
open := PageNode{}
locked := PageNode{Restricted: true}
grant := func(role string, restricted bool) PageNode { return PageNode{Grant: role, Restricted: restricted} }
cases := []struct {
name string
space string
chain []PageNode
want string
}{
{"plain page follows the space", SpaceEditor, []PageNode{open, open}, SpaceEditor},
{"no space access, no grant", "", []PageNode{open}, ""},
{"guest grant on the page", "", []PageNode{grant(SpaceViewer, false)}, SpaceViewer},
{"guest grant on an ancestor", "", []PageNode{open, open, grant(SpaceCommenter, false)}, SpaceCommenter},
{"grant raises a space viewer", SpaceViewer, []PageNode{grant(SpaceEditor, false)}, SpaceEditor},
{"grant never lowers", SpaceEditor, []PageNode{grant(SpaceViewer, false)}, SpaceEditor},
{"restricted hides from space members", SpaceEditor, []PageNode{open, locked}, ""},
{"grant on the restricted page", SpaceEditor, []PageNode{open, grant(SpaceViewer, true)}, SpaceViewer},
{"grant below the restriction", SpaceEditor, []PageNode{grant(SpaceCommenter, false), locked}, SpaceCommenter},
{"grant above the restriction is ignored", SpaceEditor, []PageNode{locked, grant(SpaceEditor, false)}, ""},
{"space admin sees restricted pages", SpaceAdmin, []PageNode{locked}, SpaceAdmin},
{"admin grant is ignored", "", []PageNode{grant(SpaceAdmin, false)}, ""},
}
for _, c := range cases {
if got := PageRole(c.space, c.chain); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestPageAccessActions(t *testing.T) {
cases := []struct {
name string
err error
want apperr.Kind
}{
{"commenter cannot share", ManagePageAccess(SpaceCommenter), forbidden},
{"no access hides the page", ManagePageAccess(""), notFound},
{"editor shares", ManagePageAccess(SpaceEditor), ok},
{"admin grant refused", SetPageGrant(SpaceAdmin, WorkspaceMember, false, SpaceAdmin), invalid},
{"grant to a member", SetPageGrant(SpaceEditor, WorkspaceMember, false, SpaceViewer), ok},
{"grant to a guest", SetPageGrant(SpaceEditor, WorkspaceGuest, false, SpaceEditor), ok},
{"grant to an outsider", SetPageGrant(SpaceEditor, "", false, SpaceViewer), invalid},
{"grant to a workspace admin", SetPageGrant(SpaceEditor, WorkspaceAdmin, false, SpaceViewer), invalid},
{"grant to a group", SetPageGrant(SpaceEditor, "", true, SpaceCommenter), ok},
{"viewer cannot grant", SetPageGrant(SpaceViewer, WorkspaceMember, false, SpaceViewer), forbidden},
{"member invites a guest", InvitePageGuest(WorkspaceMember, SpaceEditor), ok},
{"guest cannot invite", InvitePageGuest(WorkspaceGuest, SpaceEditor), forbidden},
{"top-level page needs space editor", CreatePageUnder(SpaceViewer, SpaceEditor, true), forbidden},
{"guest cannot add a top-level page", CreatePageUnder("", SpaceEditor, true), forbidden},
{"subpage needs parent editor", CreatePageUnder("", SpaceEditor, false), ok},
{"subpage of a viewed page", CreatePageUnder(SpaceEditor, SpaceViewer, false), forbidden},
}
for _, c := range cases {
if got := kind(c.err); got != c.want {
t.Errorf("%s: got kind %v, want %v (%v)", c.name, got, c.want, c.err)
}
}
}
+176 -9
View File
@@ -48,6 +48,45 @@ func (e InviteStatus) Valid() bool {
}
}
// Defines values for PageGrantType.
const (
PageGrantTypeGroup PageGrantType = "group"
PageGrantTypeUser PageGrantType = "user"
)
// Valid indicates whether the value is a known member of the PageGrantType enum.
func (e PageGrantType) Valid() bool {
switch e {
case PageGrantTypeGroup:
return true
case PageGrantTypeUser:
return true
default:
return false
}
}
// Defines values for PageGrantRole.
const (
PageGrantRoleCommenter PageGrantRole = "commenter"
PageGrantRoleEditor PageGrantRole = "editor"
PageGrantRoleViewer PageGrantRole = "viewer"
)
// Valid indicates whether the value is a known member of the PageGrantRole enum.
func (e PageGrantRole) Valid() bool {
switch e {
case PageGrantRoleCommenter:
return true
case PageGrantRoleEditor:
return true
case PageGrantRoleViewer:
return true
default:
return false
}
}
// Defines values for Role.
const (
RoleAdmin Role = "admin"
@@ -69,6 +108,33 @@ func (e Role) Valid() bool {
}
}
// Defines values for SpaceCallerRole.
const (
SpaceCallerRoleAdmin SpaceCallerRole = "admin"
SpaceCallerRoleCommenter SpaceCallerRole = "commenter"
SpaceCallerRoleEditor SpaceCallerRole = "editor"
SpaceCallerRoleEmpty SpaceCallerRole = ""
SpaceCallerRoleViewer SpaceCallerRole = "viewer"
)
// Valid indicates whether the value is a known member of the SpaceCallerRole enum.
func (e SpaceCallerRole) Valid() bool {
switch e {
case SpaceCallerRoleAdmin:
return true
case SpaceCallerRoleCommenter:
return true
case SpaceCallerRoleEditor:
return true
case SpaceCallerRoleEmpty:
return true
case SpaceCallerRoleViewer:
return true
default:
return false
}
}
// Defines values for SpaceDefaultRole.
const (
SpaceDefaultRoleCommenter SpaceDefaultRole = "commenter"
@@ -513,7 +579,7 @@ type Organization struct {
// Page defines model for Page.
type Page struct {
// Ancestors Root first
// Ancestors Root first; pages the caller cannot open are left out
Ancestors []PageRef `json:"ancestors"`
Created string `json:"created"`
@@ -526,8 +592,13 @@ type Page struct {
Id string `json:"id"`
// InTrash The page or one of its ancestors is in the trash
InTrash bool `json:"inTrash"`
Parent string `json:"parent"`
InTrash bool `json:"inTrash"`
Parent string `json:"parent"`
// Restricted The page or one of its ancestors is restricted
Restricted bool `json:"restricted"`
// Role The caller's role on this page
Role SpaceRole `json:"role"`
Space string `json:"space"`
Title string `json:"title"`
@@ -535,6 +606,28 @@ type Page struct {
Workspace string `json:"workspace"`
}
// PageAccess defines model for PageAccess.
type PageAccess struct {
// CanInvite May share with people outside the workspace
CanInvite bool `json:"canInvite"`
CanManage bool `json:"canManage"`
// Grants This page's grants first
Grants []PageGrant `json:"grants"`
// InheritedFrom The restricted ancestor, when the restriction comes from one
InheritedFrom *PageRef `json:"inheritedFrom"`
// Invites Pending guest invites for this page (editors only)
Invites []PageInvite `json:"invites"`
// Restricted The page or an ancestor is restricted; space members then see it only through grants
Restricted bool `json:"restricted"`
// Role The caller's role on this page
Role SpaceRole `json:"role"`
}
// PageContent defines model for PageContent.
type PageContent struct {
// Content Tiptap JSON with type "doc"; null for a page that was never edited
@@ -542,6 +635,36 @@ type PageContent struct {
Updated string `json:"updated"`
}
// PageGrant defines model for PageGrant.
type PageGrant struct {
// Email Empty for groups
Email string `json:"email"`
Id string `json:"id"`
// Inherited Granted on an ancestor
Inherited bool `json:"inherited"`
Name string `json:"name"`
// Page Where the grant was made
Page PageRef `json:"page"`
Role PageGrantRole `json:"role"`
Type PageGrantType `json:"type"`
}
// PageGrantType defines model for PageGrant.Type.
type PageGrantType string
// PageGrantRole defines model for PageGrantRole.
type PageGrantRole string
// PageInvite defines model for PageInvite.
type PageInvite struct {
Email string `json:"email"`
Expires string `json:"expires"`
Id string `json:"id"`
Role PageGrantRole `json:"role"`
}
// PageItem defines model for PageItem.
type PageItem struct {
// At When it was favorited
@@ -558,13 +681,16 @@ type PageNode struct {
Icon string `json:"icon"`
Id string `json:"id"`
// Parent Parent page id; empty at the top level
// Parent Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor.
Parent string `json:"parent"`
// Position Fractional sort key among siblings
Position string `json:"position"`
Title string `json:"title"`
Updated string `json:"updated"`
// Restricted This page itself is restricted
Restricted bool `json:"restricted"`
Title string `json:"title"`
Updated string `json:"updated"`
}
// PageRef defines model for PageRef.
@@ -639,6 +765,14 @@ type ShareLink struct {
Url string `json:"url"`
}
// SharePageResult defines model for SharePageResult.
type SharePageResult struct {
Access PageAccess `json:"access"`
// Invite Set when the person was invited as a guest; the grant is made when they accept
Invite *Invite `json:"invite"`
}
// SharedPage defines model for SharedPage.
type SharedPage struct {
// Content Tiptap JSON; files load from /api/v1/share/{token}/files/{fileId}
@@ -691,15 +825,23 @@ type Space struct {
Description string `json:"description"`
Icon string `json:"icon"`
Id string `json:"id"`
Name string `json:"name"`
Role SpaceRole `json:"role"`
Slug string `json:"slug"`
// Limited The caller cannot open the space itself and sees only pages shared with them
Limited bool `json:"limited"`
Name string `json:"name"`
// Role The caller's space role; empty when they see only pages shared with them
Role SpaceCallerRole `json:"role"`
Slug string `json:"slug"`
// Visibility open - every workspace member gets the default role; private - explicit members only.
Visibility SpaceVisibility `json:"visibility"`
Workspace string `json:"workspace"`
}
// SpaceCallerRole The caller's space role; empty when they see only pages shared with them
type SpaceCallerRole string
// SpaceDefaultRole Role that workspace members (not guests) get in an open space without an explicit role.
type SpaceDefaultRole string
@@ -894,6 +1036,22 @@ type UpdatePageJSONBody struct {
Title *string `json:"title,omitempty"`
}
// SetPageRestrictedJSONBody defines parameters for SetPageRestricted.
type SetPageRestrictedJSONBody struct {
Restricted bool `json:"restricted"`
}
// SharePageWithGroupJSONBody defines parameters for SharePageWithGroup.
type SharePageWithGroupJSONBody struct {
Role PageGrantRole `json:"role"`
}
// SharePageWithUserJSONBody defines parameters for SharePageWithUser.
type SharePageWithUserJSONBody struct {
Email openapi_types.Email `json:"email"`
Role PageGrantRole `json:"role"`
}
// UploadAttachmentMultipartBody defines parameters for UploadAttachment.
type UploadAttachmentMultipartBody struct {
File openapi_types.File `json:"file"`
@@ -1081,6 +1239,15 @@ type RenameOrgJSONRequestBody = NameRequest
// UpdatePageJSONRequestBody defines body for UpdatePage for application/json ContentType.
type UpdatePageJSONRequestBody UpdatePageJSONBody
// SetPageRestrictedJSONRequestBody defines body for SetPageRestricted for application/json ContentType.
type SetPageRestrictedJSONRequestBody SetPageRestrictedJSONBody
// SharePageWithGroupJSONRequestBody defines body for SharePageWithGroup for application/json ContentType.
type SharePageWithGroupJSONRequestBody SharePageWithGroupJSONBody
// SharePageWithUserJSONRequestBody defines body for SharePageWithUser for application/json ContentType.
type SharePageWithUserJSONRequestBody SharePageWithUserJSONBody
// UploadAttachmentMultipartRequestBody defines body for UploadAttachment for multipart/form-data ContentType.
type UploadAttachmentMultipartRequestBody UploadAttachmentMultipartBody
+2
View File
@@ -846,6 +846,7 @@ func (s *Service) RemoveMember(ctx context.Context, c access.Caller, wsID, userI
}
}
s.dropGroupMemberships(ctx, userID, ws.ID)
s.dropPageGrants(ctx, "user", userID, ws.ID)
return nil
}
@@ -861,6 +862,7 @@ func (s *Service) dropMemberships(ctx context.Context, userID string) {
_ = s.pb.Delete(ctx, "workspace_members", m.ID)
}
s.dropGroupMemberships(ctx, userID, "")
s.dropPageGrants(ctx, "user", userID, "")
spaceMembers, err := s.userSpaceMemberships(ctx, userID, "")
if err != nil {
return
+11 -6
View File
@@ -47,21 +47,26 @@ const userPageFields = "id,page,created,visited," +
// visibleItems keeps the rows whose page c can still open, with space names.
func (s *Service) visibleItems(ctx context.Context, c access.Caller, rows []userPageRecord, at func(userPageRecord) string) []PageItem {
spaceNames := map[string]string{} // space id → name, "" = no access
type reach struct {
name string // "" = no access to the space
rules pageRules
}
spaces := map[string]reach{}
out := []PageItem{}
for _, r := range rows {
p := r.Expand.Page
if p == nil || p.DeletedAt != "" {
continue
}
name, seen := spaceNames[p.Space]
sp, seen := spaces[p.Space]
if !seen {
if a, err := s.spaceFor(ctx, c, p.Space); err == nil {
name = a.space.Name
if a, rules, err := s.spaceRules(ctx, c, p.Space); err == nil {
sp = reach{name: a.space.Name, rules: rules}
}
spaceNames[p.Space] = name
spaces[p.Space] = sp
}
if name == "" {
name := sp.name
if name == "" || sp.rules.role(p.ID) == "" {
continue
}
out = append(out, PageItem{ID: p.ID, Title: p.Title, Icon: p.Icon, Space: p.Space, SpaceName: name, At: at(r)})
+1
View File
@@ -264,6 +264,7 @@ func (s *Service) DeleteGroup(ctx context.Context, c access.Caller, id string) e
return err
}
}
s.dropPageGrants(ctx, "group", g.ID, "")
return mapPB(s.pb.Delete(ctx, "groups", g.ID), "group not found")
}
+23 -4
View File
@@ -72,6 +72,8 @@ type inviteRecord struct {
Role string `json:"role"`
Workspace string `json:"workspace"`
WorkspaceRole string `json:"workspace_role"`
Page string `json:"page"`
PageRole string `json:"page_role"`
InvitedBy string `json:"invited_by"`
Expires string `json:"expires"`
Accepted string `json:"accepted"`
@@ -135,6 +137,9 @@ type CreateInviteInput struct {
// workspace admin, and the organization is the workspace's.
Workspace string `json:"workspace"`
WorkspaceRole string `json:"workspaceRole"`
// page and pageRole make a guest invite that shares one page
// (SharePageWithUser, which has checked the inviter's rights).
page, pageRole string
}
// CreateInvite invites someone by email. Inviting a person who already has
@@ -160,11 +165,16 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn
if role == "" {
role = access.WorkspaceMember
}
if err := access.InviteToWorkspace(actorRole, role); err != nil {
return Invite{}, err
if in.page == "" {
if err := access.InviteToWorkspace(actorRole, role); err != nil {
return Invite{}, err
}
}
org = ws.Organization
body["role"], body["workspace"], body["workspace_role"] = access.RoleUser, ws.ID, role
if in.page != "" {
body["page"], body["page_role"] = in.page, in.pageRole
}
} else {
role, ok := access.NormalizeRole(in.Role)
if !ok {
@@ -187,7 +197,7 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn
switch {
case err == nil && existing.Role == access.RoleSuperadmin:
return Invite{}, apperr.Conflict("that person is a superadmin and already has access everywhere")
case err == nil && existing.Organization == org && org != "" && ws.ID != "":
case err == nil && existing.Organization == org && org != "" && ws.ID != "" && in.page == "":
// Already in the organization: no invite needed.
m, err := s.SetMember(ctx, c, ws.ID, email, body["workspace_role"].(string))
if err != nil {
@@ -214,7 +224,8 @@ func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateIn
body["expires"] = pbTime(time.Now().Add(inviteTTL))
// Inviting the same person to the same place again refreshes the invite.
filter := fmt.Sprintf("email = '%s' && organization = '%s' && workspace = '%s' && accepted = ''", filterValue(email), org, ws.ID)
filter := fmt.Sprintf("email = '%s' && organization = '%s' && workspace = '%s' && page = '%s' && accepted = ''",
filterValue(email), org, ws.ID, in.page)
prev, err := pocketbase.List[inviteRecord](ctx, s.pb, "invites", pocketbase.ListOptions{PerPage: 1, Filter: filter})
if err != nil {
return Invite{}, err
@@ -509,6 +520,14 @@ func (s *Service) AcceptInvite(ctx context.Context, me *auth.User, in AcceptInvi
}
}
}
if rec.Page != "" && access.ValidPageGrant(rec.PageRole) {
// The page may have gone since; the workspace membership still stands.
if p, err := s.getPage(ctx, rec.Page); err == nil {
if err := s.upsertGrant(ctx, p, "user", userID, rec.PageRole); err != nil {
return "", err
}
}
}
if _, err := pocketbase.Update[inviteRecord](ctx, s.pb, "invites", rec.ID, map[string]any{
"accepted": pbTime(time.Now()),
}); err != nil {
+60 -32
View File
@@ -22,7 +22,7 @@ import (
// Purging deletes the record, and PocketBase cascades to the subtree.
// pageFields skips the large content columns.
const pageFields = "id,workspace,space,parent,title,icon,position,creator,last_editor,deleted_at,created,updated"
const pageFields = "id,workspace,space,parent,title,icon,position,restricted,creator,last_editor,deleted_at,created,updated"
type pageRecord struct {
ID string `json:"id"`
@@ -32,6 +32,7 @@ type pageRecord struct {
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
Restricted bool `json:"restricted"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
@@ -46,11 +47,13 @@ type PageNode struct {
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
Updated string `json:"updated"`
// Restricted is set on the page that is restricted itself (not its subtree).
Restricted bool `json:"restricted"`
Updated string `json:"updated"`
}
func (r pageRecord) node() PageNode {
return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Updated: r.Updated}
return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Restricted: r.Restricted, Updated: r.Updated}
}
type PageRef struct {
@@ -74,6 +77,8 @@ type Page struct {
InTrash bool `json:"inTrash"`
Ancestors []PageRef `json:"ancestors"`
Role string `json:"role"`
// Restricted is true when the page or an ancestor is restricted.
Restricted bool `json:"restricted"`
// Favorite is whether the caller has the page in their favorites.
Favorite bool `json:"favorite"`
}
@@ -101,17 +106,11 @@ func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) {
return res.Items[0], nil
}
// pageFor loads a page and c's access to its space.
// pageFor loads a page and c's access to it; a.role is c's role on the page
// (see pageAccess).
func (s *Service) pageFor(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, error) {
p, err := s.getPage(ctx, id)
if err != nil {
return p, spaceAccess{}, err
}
a, err := s.spaceFor(ctx, c, p.Space)
if err != nil {
return p, a, apperr.NotFound("page not found")
}
return p, a, nil
p, a, _, err := s.pageAccess(ctx, c, id)
return p, a, err
}
// tree is every page of one space, live or trashed.
@@ -170,9 +169,23 @@ func (t tree) within(id, ancestor string) bool {
return false
}
// ListPages returns a space's live pages, siblings in order; clients build the tree.
// restrictedBelow reports whether page id, or an ancestor of it below
// ancestor, is restricted.
func (t tree) restrictedBelow(id, ancestor string) bool {
for depth := 0; id != "" && id != ancestor && depth < 1000; depth++ {
if t.byID[id].Restricted {
return true
}
id = t.byID[id].Parent
}
return false
}
// ListPages returns the space's live pages c can open, siblings in order;
// clients build the tree. A visible page under hidden ones hangs from its
// nearest visible ancestor (the top level when there is none).
func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string) ([]PageNode, error) {
a, err := s.spaceFor(ctx, c, spaceID)
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
@@ -181,27 +194,33 @@ func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string
return nil, err
}
out := []PageNode{}
var walk func(parent string)
walk = func(parent string) {
var walk func(parent, shownParent string)
walk = func(parent, shownParent string) {
for _, p := range t.children[parent] {
out = append(out, p.node())
walk(p.ID)
under := shownParent
if rules.role(p.ID) != "" {
n := p.node()
n.Parent = shownParent
out = append(out, n)
under = p.ID
}
walk(p.ID, under)
}
}
walk("")
walk("", "")
return out, nil
}
// GetPage returns a page with its breadcrumbs.
func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page, error) {
p, a, err := s.pageFor(ctx, c, id)
p, a, rules, err := s.pageAccess(ctx, c, id)
if err != nil {
return Page{}, err
}
page := Page{
ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon,
Created: p.Created, Updated: p.Updated, DeletedAt: p.DeletedAt, InTrash: p.DeletedAt != "",
Ancestors: []PageRef{}, Role: a.role, Favorite: s.isFavorite(ctx, c.ID, p.ID),
Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, Favorite: s.isFavorite(ctx, c.ID, p.ID),
}
parent := p.Parent
for depth := 0; parent != "" && depth < 100; depth++ {
@@ -210,7 +229,11 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
break
}
page.InTrash = page.InTrash || anc.DeletedAt != ""
page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...)
page.Restricted = page.Restricted || anc.Restricted
// Breadcrumbs leave out pages the caller cannot open.
if rules.role(anc.ID) != "" {
page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...)
}
parent = anc.Parent
}
return page, nil
@@ -286,13 +309,14 @@ type CreatePageInput struct {
Index *int `json:"index"`
}
// CreatePage adds a page to a space (editor).
// CreatePage adds a page to a space (editor of the parent page, or of the
// space for a top-level page).
func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID string, in CreatePageInput) (Page, error) {
a, err := s.spaceFor(ctx, c, spaceID)
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
if err := access.CreatePageUnder(a.role, rules.role(in.Parent), in.Parent == ""); err != nil {
return Page{}, err
}
title, err := cleanTitle(in.Title)
@@ -374,15 +398,19 @@ type MovePageInput struct {
Index int `json:"index"`
}
// MovePage moves a page (with its subtree) within its space (editor).
// MovePage moves a page (with its subtree) within its space (editor of the
// page and of where it goes).
func (s *Service) MovePage(ctx context.Context, c access.Caller, id string, in MovePageInput) (Page, error) {
p, a, err := s.pageFor(ctx, c, id)
p, a, rules, err := s.pageAccess(ctx, c, id)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
return Page{}, err
}
if err := access.CreatePageUnder(a.spaceRole, rules.role(in.Parent), in.Parent == ""); err != nil {
return Page{}, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
@@ -467,10 +495,10 @@ func (s *Service) RestorePage(ctx context.Context, c access.Caller, id string) (
return s.GetPage(ctx, c, p.ID)
}
// ListTrash lists a space's trashed pages, newest first. Pages inside a
// trashed page are not listed separately: they come back with it.
// ListTrash lists a space's trashed pages c can open, newest first. Pages
// inside a trashed page are not listed separately: they come back with it.
func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]TrashedPage, error) {
a, err := s.spaceFor(ctx, c, spaceID)
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
@@ -480,7 +508,7 @@ func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string
}
out := []TrashedPage{}
for _, p := range t.byID {
if p.DeletedAt != "" && t.live(p.Parent) {
if p.DeletedAt != "" && t.live(p.Parent) && rules.role(p.ID) != "" {
out = append(out, TrashedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, DeletedAt: p.DeletedAt})
}
}
+526
View File
@@ -0,0 +1,526 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"fmt"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Page permissions ------------------------------------------------------
//
// A page's role refines the space role through grants and restricted
// subtrees (access.PageRole). Most spaces have neither, so pageRules only
// loads the space's page tree when the caller has a grant there or some page
// is restricted.
type pageGrantRecord struct {
ID string `json:"id"`
Page string `json:"page"`
Space string `json:"space"`
PrincipalType string `json:"principal_type"`
PrincipalID string `json:"principal_id"`
Role string `json:"role"`
}
// principalFilter matches rows granted to userID or one of their groups.
func principalFilter(userID string, groups []string) string {
f := fmt.Sprintf("(principal_type = 'user' && principal_id = '%s')", userID)
if len(groups) == 0 {
return f
}
ors := make([]string, len(groups))
for i, g := range groups {
ors[i] = fmt.Sprintf("principal_id = '%s'", g)
}
return "(" + f + " || (principal_type = 'group' && (" + strings.Join(ors, " || ") + ")))"
}
// callerGrants lists the page grants of c and their groups, in one space or
// (spaceID "") the whole workspace wsID.
func (s *Service) callerGrants(ctx context.Context, c access.Caller, wsID, spaceID string) ([]pageGrantRecord, error) {
groups, err := s.userGroups(ctx, c.ID, wsID)
if err != nil {
return nil, err
}
filter := principalFilter(c.ID, groups)
if spaceID != "" {
filter = fmt.Sprintf("space = '%s' && ", spaceID) + filter
} else {
filter = fmt.Sprintf("space.workspace = '%s' && ", wsID) + filter
}
return listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{Filter: filter})
}
// hasPageGrants reports whether c holds any page grant in space sp.
func (s *Service) hasPageGrants(ctx context.Context, c access.Caller, sp spaceRecord) (bool, error) {
grants, err := s.callerGrants(ctx, c, sp.Workspace, sp.ID)
return len(grants) > 0, err
}
// grantedSpaces is the set of spaces of workspace wsID where c holds page grants.
func (s *Service) grantedSpaces(ctx context.Context, c access.Caller, wsID string) (map[string]bool, error) {
grants, err := s.callerGrants(ctx, c, wsID, "")
if err != nil {
return nil, err
}
out := make(map[string]bool, len(grants))
for _, g := range grants {
out[g.Space] = true
}
return out, nil
}
// pageRules resolves one caller's role on the pages of one space.
type pageRules struct {
spaceRole string
restricted map[string]bool
grants map[string]string // page → the caller's best grant
parent map[string]string // nil when no page needs more than the space role
}
func (s *Service) rulesFor(ctx context.Context, c access.Caller, a spaceAccess) (pageRules, error) {
r := pageRules{spaceRole: a.spaceRole, restricted: map[string]bool{}, grants: map[string]string{}}
locked, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s' && restricted = true", a.space.ID), Fields: "id",
})
if err != nil {
return r, err
}
for _, p := range locked {
r.restricted[p.ID] = true
}
if !access.SpaceAtLeast(a.spaceRole, access.SpaceAdmin) {
grants, err := s.callerGrants(ctx, c, a.space.Workspace, a.space.ID)
if err != nil {
return r, err
}
for _, g := range grants {
r.grants[g.Page] = access.HigherSpaceRole(r.grants[g.Page], g.Role)
}
}
if len(r.restricted) == 0 && len(r.grants) == 0 {
return r, nil
}
all, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s'", a.space.ID), Fields: "id,parent",
})
if err != nil {
return r, err
}
r.parent = make(map[string]string, len(all))
for _, p := range all {
r.parent[p.ID] = p.Parent
}
return r, nil
}
// plain reports whether every page simply has the space role.
func (r pageRules) plain() bool { return r.parent == nil }
func (r pageRules) role(id string) string {
if r.plain() {
return access.PageRole(r.spaceRole, nil)
}
var chain []access.PageNode
for depth := 0; id != "" && depth < 1000; depth++ {
chain = append(chain, access.PageNode{Restricted: r.restricted[id], Grant: r.grants[id]})
id = r.parent[id]
}
return access.PageRole(r.spaceRole, chain)
}
// restrictedAt is the page itself or its nearest restricted ancestor ("" when none).
func (r pageRules) restrictedAt(id string) string {
if len(r.restricted) == 0 {
return ""
}
for depth := 0; id != "" && depth < 1000; depth++ {
if r.restricted[id] {
return id
}
id = r.parent[id]
}
return ""
}
// pageAccess loads a page with c's rights on it: a.role is the page role.
// A page c cannot open is reported as not found.
func (s *Service) pageAccess(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, pageRules, error) {
p, err := s.getPage(ctx, id)
if err != nil {
return p, spaceAccess{}, pageRules{}, err
}
a, err := s.spaceReach(ctx, c, p.Space)
if err != nil {
return p, a, pageRules{}, apperr.NotFound("page not found")
}
rules, err := s.rulesFor(ctx, c, a)
if err != nil {
return p, a, rules, err
}
a.role = rules.role(p.ID)
if a.role == "" {
return p, a, rules, apperr.NotFound("page not found")
}
return p, a, rules, nil
}
// spaceRules loads a space c can reach (see spaceReach) with its page rules.
func (s *Service) spaceRules(ctx context.Context, c access.Caller, spaceID string) (spaceAccess, pageRules, error) {
a, err := s.spaceReach(ctx, c, spaceID)
if err != nil {
return a, pageRules{}, err
}
rules, err := s.rulesFor(ctx, c, a)
return a, rules, err
}
// ---- Sharing a page with people and groups ---------------------------------
// PageGrant is one person or group with a role on a page.
type PageGrant struct {
// Type is "user" or "group".
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
// Page is where the grant was made: this page, or an ancestor it inherits from.
Page PageRef `json:"page"`
Inherited bool `json:"inherited"`
}
// PageInvite is a pending invite that shares this page with a new guest.
type PageInvite struct {
ID string `json:"id"`
Email string `json:"email"`
Role string `json:"role"`
Expires string `json:"expires"`
}
// PageAccess is who can reach a page beyond its space's members.
type PageAccess struct {
// Restricted is true when the page or an ancestor is restricted: the
// space's members then see it only through grants.
Restricted bool `json:"restricted"`
// InheritedFrom is the restricted ancestor when the page is restricted
// through it (nil when the page itself is restricted, or nothing is).
InheritedFrom *PageRef `json:"inheritedFrom"`
Grants []PageGrant `json:"grants"`
Invites []PageInvite `json:"invites"`
// Role is the caller's role on the page.
Role string `json:"role"`
CanManage bool `json:"canManage"`
// CanInvite is whether the caller may share the page with people
// outside the workspace (who join it as guests).
CanInvite bool `json:"canInvite"`
}
// GetPageAccess lists a page's grants, its own and inherited (viewer).
func (s *Service) GetPageAccess(ctx context.Context, c access.Caller, id string) (PageAccess, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
if err != nil {
return PageAccess{}, err
}
out := PageAccess{
Grants: []PageGrant{}, Invites: []PageInvite{}, Role: a.role,
CanManage: access.ManagePageAccess(a.role) == nil,
CanInvite: access.InvitePageGuest(a.wsRole, a.role) == nil,
}
// The pages whose grants apply: this one and its ancestors up to the
// nearest restriction.
chain := []pageRecord{p}
for cur, depth := p, 0; !cur.Restricted && cur.Parent != "" && depth < 100; depth++ {
if cur, err = s.getPage(ctx, cur.Parent); err != nil {
break
}
chain = append(chain, cur)
}
if last := chain[len(chain)-1]; last.Restricted {
out.Restricted = true
if last.ID != p.ID {
out.InheritedFrom = &PageRef{ID: last.ID, Title: last.Title, Icon: last.Icon}
}
}
ors := make([]string, len(chain))
refs := make(map[string]PageRef, len(chain))
for i, cp := range chain {
ors[i] = fmt.Sprintf("page = '%s'", cp.ID)
refs[cp.ID] = PageRef{ID: cp.ID, Title: cp.Title, Icon: cp.Icon}
}
grants, err := listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{
Filter: strings.Join(ors, " || "),
})
if err != nil {
return PageAccess{}, err
}
for _, g := range grants {
pg := PageGrant{Type: g.PrincipalType, ID: g.PrincipalID, Role: g.Role, Page: refs[g.Page], Inherited: g.Page != p.ID}
if g.PrincipalType == "group" {
grp, err := pocketbase.Get[groupRecord](ctx, s.pb, "groups", g.PrincipalID)
if err != nil {
continue // a deleted group's leftover row
}
pg.Name = grp.Name
} else {
u, err := s.getUser(ctx, g.PrincipalID)
if err != nil {
continue
}
pg.Name, pg.Email = u.Name, u.Email
}
out.Grants = append(out.Grants, pg)
}
sort.SliceStable(out.Grants, func(i, j int) bool {
gi, gj := out.Grants[i], out.Grants[j]
if gi.Inherited != gj.Inherited {
return !gi.Inherited
}
if gi.Type != gj.Type {
return gi.Type == "group"
}
return strings.ToLower(gi.Name+gi.Email) < strings.ToLower(gj.Name+gj.Email)
})
if out.CanManage {
invites, err := listAll[inviteRecord](ctx, s, "invites", pocketbase.ListOptions{
Filter: fmt.Sprintf("page = '%s' && accepted = ''", p.ID), Sort: "email",
})
if err != nil {
return PageAccess{}, err
}
now := time.Now()
for _, inv := range invites {
if inv.view(now).Status == "pending" {
out.Invites = append(out.Invites, PageInvite{ID: inv.ID, Email: inv.Email, Role: inv.PageRole, Expires: inv.Expires})
}
}
}
return out, nil
}
// SetPageRestricted turns a page's restriction on or off (editor). Someone
// who restricts a page without being a space admin keeps editor on it
// through a grant, so they cannot lock themselves out.
func (s *Service) SetPageRestricted(ctx context.Context, c access.Caller, id string, on bool) (PageAccess, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
if err != nil {
return PageAccess{}, err
}
if err := access.ManagePageAccess(a.role); err != nil {
return PageAccess{}, err
}
if p.Restricted == on {
return s.GetPageAccess(ctx, c, p.ID)
}
if on && !access.SpaceAtLeast(a.spaceRole, access.SpaceAdmin) {
if err := s.upsertGrant(ctx, p, "user", c.ID, access.SpaceEditor); err != nil {
return PageAccess{}, err
}
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"restricted": on}); err != nil {
return PageAccess{}, mapPB(err, "page not found")
}
s.kickSubtree(ctx, p)
return s.GetPageAccess(ctx, c, p.ID)
}
// SharePageResult is a page's access after sharing it, with the invite sent
// when the person had no way into the workspace yet.
type SharePageResult struct {
Access PageAccess `json:"access"`
Invite *Invite `json:"invite"`
}
// SharePageWithUser gives someone (by email) role on a page (editor). A
// workspace member gets a grant; someone from the workspace's organization
// who is not in the workspace joins it as a guest; anyone else is invited as
// a guest, and the grant is made when they accept.
func (s *Service) SharePageWithUser(ctx context.Context, c access.Caller, id, email, role string) (SharePageResult, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
if err != nil {
return SharePageResult{}, err
}
if err := access.ManagePageAccess(a.role); err != nil {
return SharePageResult{}, err
}
if !access.ValidPageGrant(role) {
return SharePageResult{}, apperr.Invalid("role must be editor, commenter or viewer")
}
email = strings.ToLower(strings.TrimSpace(email))
if !strings.Contains(email, "@") || len(email) > 255 {
return SharePageResult{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."})
}
u, err := s.findUserByEmail(ctx, email)
if err != nil && !isNotFound(err) {
return SharePageResult{}, err
}
if err == nil {
targetWs, err := s.effective(ctx, u.Caller(), a.ws)
if err != nil {
return SharePageResult{}, err
}
if targetWs == "" && u.Organization == a.ws.Organization && u.Role != access.RoleSuperadmin {
if err := access.InvitePageGuest(a.wsRole, a.role); err != nil {
return SharePageResult{}, err
}
if _, err := pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{
"workspace": a.ws.ID, "user": u.ID, "role": access.WorkspaceGuest,
}); err != nil {
return SharePageResult{}, mapPB(err, "workspace not found")
}
s.forget(u.ID)
targetWs = access.WorkspaceGuest
}
if targetWs != "" {
if err := access.SetPageGrant(a.role, targetWs, false, role); err != nil {
return SharePageResult{}, err
}
if err := s.upsertGrant(ctx, p, "user", u.ID, role); err != nil {
return SharePageResult{}, err
}
s.kickSubtree(ctx, p)
pa, err := s.GetPageAccess(ctx, c, p.ID)
return SharePageResult{Access: pa}, err
}
// No way into this organization yet: fall through to an invite,
// which refuses accounts that belong to another organization.
}
if err := access.InvitePageGuest(a.wsRole, a.role); err != nil {
return SharePageResult{}, err
}
inv, err := s.CreateInvite(ctx, c, CreateInviteInput{
Email: email, Workspace: a.ws.ID, WorkspaceRole: access.WorkspaceGuest, page: p.ID, pageRole: role,
})
if err != nil {
return SharePageResult{}, err
}
pa, err := s.GetPageAccess(ctx, c, p.ID)
return SharePageResult{Access: pa, Invite: &inv}, err
}
// SharePageWithGroup gives a group of the page's workspace role on it (editor).
func (s *Service) SharePageWithGroup(ctx context.Context, c access.Caller, id, groupID, role string) (PageAccess, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
if err != nil {
return PageAccess{}, err
}
if err := access.ViewGroups(a.wsRole); err != nil {
return PageAccess{}, err
}
if err := access.SetPageGrant(a.role, "", true, role); err != nil {
return PageAccess{}, err
}
if !validID(groupID) {
return PageAccess{}, apperr.NotFound("group not found")
}
g, err := pocketbase.Get[groupRecord](ctx, s.pb, "groups", groupID)
if err != nil || g.Workspace != p.Workspace {
return PageAccess{}, apperr.NotFound("group not found")
}
if err := s.upsertGrant(ctx, p, "group", g.ID, role); err != nil {
return PageAccess{}, err
}
s.kickSubtree(ctx, p)
return s.GetPageAccess(ctx, c, p.ID)
}
// UnsharePage removes a user's or group's grant on a page (idempotent).
// Anyone may drop their own grant; removing others needs editor.
func (s *Service) UnsharePage(ctx context.Context, c access.Caller, id, principalType, principalID string) (PageAccess, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
if err != nil {
return PageAccess{}, err
}
if principalType != "user" || principalID != c.ID {
if err := access.ManagePageAccess(a.role); err != nil {
return PageAccess{}, err
}
}
if !validID(principalID) {
return PageAccess{}, apperr.NotFound("grant not found")
}
cur, err := s.grantOf(ctx, p.ID, principalType, principalID)
if err != nil {
return PageAccess{}, err
}
if cur.ID != "" {
if err := s.pb.Delete(ctx, "page_permissions", cur.ID); err != nil && !pocketbase.IsNotFound(err) {
return PageAccess{}, err
}
s.kickSubtree(ctx, p)
}
pa, err := s.GetPageAccess(ctx, c, p.ID)
if e, ok := apperr.As(err); ok && e.Kind == apperr.KindNotFound {
// They removed their own last way in.
return PageAccess{Grants: []PageGrant{}, Invites: []PageInvite{}}, nil
}
return pa, err
}
func (s *Service) grantOf(ctx context.Context, pageID, principalType, principalID string) (pageGrantRecord, error) {
res, err := pocketbase.List[pageGrantRecord](ctx, s.pb, "page_permissions", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && principal_type = '%s' && principal_id = '%s'",
pageID, filterValue(principalType), principalID),
})
if err != nil || len(res.Items) == 0 {
return pageGrantRecord{}, err
}
return res.Items[0], nil
}
func (s *Service) upsertGrant(ctx context.Context, p pageRecord, principalType, principalID, role string) error {
cur, err := s.grantOf(ctx, p.ID, principalType, principalID)
if err != nil {
return err
}
if cur.ID != "" {
if cur.Role == role {
return nil
}
_, err = pocketbase.Update[pageGrantRecord](ctx, s.pb, "page_permissions", cur.ID, map[string]any{"role": role})
} else {
_, err = pocketbase.Create[pageGrantRecord](ctx, s.pb, "page_permissions", map[string]any{
"page": p.ID, "space": p.Space, "principal_type": principalType, "principal_id": principalID, "role": role,
})
}
return mapPB(err, "page not found")
}
// kickSubtree reconnects the editors of a page and every page under it, so
// they pick up changed rights.
func (s *Service) kickSubtree(ctx context.Context, p pageRecord) {
t, err := s.loadTree(ctx, p.Space)
if err != nil {
s.docs.Kick(p.ID)
return
}
for id := range t.byID {
if t.within(id, p.ID) {
s.docs.Kick(id)
}
}
}
// dropPageGrants deletes grants (best effort): a user's in one workspace
// ("" = all), or a group's.
func (s *Service) dropPageGrants(ctx context.Context, principalType, principalID, wsID string) {
filter := fmt.Sprintf("principal_type = '%s' && principal_id = '%s'", principalType, principalID)
if wsID != "" {
filter += fmt.Sprintf(" && space.workspace = '%s'", wsID)
}
grants, err := listAll[pageGrantRecord](ctx, s, "page_permissions", pocketbase.ListOptions{Filter: filter})
if err != nil {
return
}
for _, g := range grants {
_ = s.pb.Delete(ctx, "page_permissions", g.ID)
}
}
+25 -4
View File
@@ -27,7 +27,7 @@ type SearchResult struct {
Total int `json:"total"`
}
// Search finds pages in a workspace, only in the spaces c can open.
// Search finds pages in a workspace, only the ones c can open.
func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (SearchResult, error) {
spaces, err := s.ListSpaces(ctx, c, wsID)
if err != nil {
@@ -39,19 +39,40 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string
}
ids := make([]string, len(spaces))
names := make(map[string]string, len(spaces))
rules := make(map[string]pageRules, len(spaces))
filtered := false // some pages of these spaces are hidden from c
for i, sp := range spaces {
ids[i], names[sp.ID] = sp.ID, sp.Name
_, r, err := s.spaceRules(ctx, c, sp.ID)
if err != nil {
return SearchResult{}, err
}
rules[sp.ID] = r
filtered = filtered || (!r.plain() && r.spaceRole != access.SpaceAdmin)
}
if limit <= 0 {
limit = 20
}
hits, total, err := s.search.Query(ctx, wsID, ids, text, limit)
// Hidden pages are dropped after the query, so ask for more to keep
// the page of results full.
want := limit
if filtered {
want = limit*3 + 20
}
hits, total, err := s.search.Query(ctx, wsID, ids, text, want)
if err != nil {
return SearchResult{}, err
}
dropped := 0
for _, h := range hits {
out.Items = append(out.Items, SearchHit{Hit: h, SpaceName: names[h.Space]})
if rules[h.Space].role(h.ID) == "" {
dropped++
continue
}
if len(out.Items) < limit {
out.Items = append(out.Items, SearchHit{Hit: h, SpaceName: names[h.Space]})
}
}
out.Total = total
out.Total = max(total-dropped, len(out.Items))
return out, nil
}
+4 -1
View File
@@ -162,7 +162,7 @@ func (s *Service) sharedScope(ctx context.Context, token, pageID string) (shareR
return link, root, t, nil
}
p, ok := t.byID[pageID]
if !ok || !link.IncludeSubpages || !t.live(p.ID) || !t.within(p.ID, root.ID) {
if !ok || !link.IncludeSubpages || !t.live(p.ID) || !t.within(p.ID, root.ID) || t.restrictedBelow(p.ID, root.ID) {
return link, pageRecord{}, tree{}, apperr.NotFound("page not found")
}
return link, p, t, nil
@@ -188,6 +188,9 @@ func (s *Service) GetSharedPage(ctx context.Context, token, pageID string) (Shar
var walk func(parent string)
walk = func(parent string) {
for _, c := range t.children[parent] {
if c.Restricted {
continue
}
out.Pages = append(out.Pages, c.node())
walk(c.ID)
}
+56 -14
View File
@@ -26,7 +26,10 @@ type Space struct {
Visibility string `json:"visibility"`
DefaultRole string `json:"defaultRole"`
// Role is the caller's effective space role after the cascade.
Role string `json:"role"`
Role string `json:"role"`
// Limited is true when the caller cannot open the space itself and sees
// only the pages shared with them (Role is then "").
Limited bool `json:"limited"`
Created string `json:"created"`
}
@@ -49,7 +52,7 @@ func (r spaceRecord) view(role string) Space {
}
return Space{
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description,
Visibility: r.Visibility, DefaultRole: def, Role: role, Created: r.Created,
Visibility: r.Visibility, DefaultRole: def, Role: role, Limited: role == "", Created: r.Created,
}
}
@@ -96,17 +99,19 @@ func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) (
return res.Items[0], nil
}
// spaceAccess is a space with the caller's workspace and space roles.
// spaceAccess is a space with the caller's workspace and space roles. From
// pageFor, role is the caller's role on that page (see pageRules) and
// spaceRole stays the role in the space itself.
type spaceAccess struct {
space spaceRecord
ws workspaceRecord
wsRole string
role string
space spaceRecord
ws workspaceRecord
wsRole string
spaceRole string
role string
}
// spaceFor loads a space with c's roles. A space c cannot open is reported as
// not found, like a workspace.
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
// loadSpace loads a space with c's roles, without checking that c may open it.
func (s *Service) loadSpace(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
if !validID(id) {
return spaceAccess{}, apperr.NotFound("space not found")
}
@@ -128,13 +133,43 @@ func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spa
return spaceAccess{}, err
}
}
a := spaceAccess{space: sp, ws: ws, wsRole: wsRole, role: access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)}
role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)
return spaceAccess{space: sp, ws: ws, wsRole: wsRole, spaceRole: role, role: role}, nil
}
// spaceFor loads a space with c's roles. A space c cannot open is reported as
// not found, like a workspace.
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
a, err := s.loadSpace(ctx, c, id)
if err != nil {
return spaceAccess{}, err
}
if err := access.ViewSpace(a.role); err != nil {
return spaceAccess{}, err
}
return a, nil
}
// spaceReach is spaceFor that also lets in a workspace member who cannot
// open the space but holds page grants in it (a guest a page was shared
// with). Their role stays "": only pageRules gives them anything.
func (s *Service) spaceReach(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
a, err := s.loadSpace(ctx, c, id)
if err != nil || a.role != "" {
return a, err
}
if a.wsRole != "" {
has, err := s.hasPageGrants(ctx, c, a.space)
if err != nil {
return spaceAccess{}, err
}
if has {
return a, nil
}
}
return spaceAccess{}, apperr.NotFound("space not found")
}
// ListSpaces lists the spaces of a workspace that c can open.
func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) {
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
@@ -168,9 +203,15 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string)
explicit[g.Space] = access.HigherSpaceRole(explicit[g.Space], g.Role)
}
}
var shared map[string]bool
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
if shared, err = s.grantedSpaces(ctx, c, ws.ID); err != nil {
return nil, err
}
}
out := []Space{}
for _, sp := range spaces {
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" {
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" || shared[sp.ID] {
out = append(out, sp.view(role))
}
}
@@ -178,9 +219,10 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string)
return out, nil
}
// GetSpace returns one space with c's role.
// GetSpace returns one space with c's role (Limited for someone who sees
// only pages shared with them).
func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) {
a, err := s.spaceFor(ctx, c, id)
a, err := s.spaceReach(ctx, c, id)
if err != nil {
return Space{}, err
}
+2 -2
View File
@@ -84,11 +84,11 @@ type ImportFile struct {
// Markdown (.md, .markdown, .txt) and HTML (.html, .htm) are understood; a
// leading level-1 heading becomes the title, otherwise the file name does.
func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []ImportFile) ([]Page, error) {
a, err := s.spaceFor(ctx, c, spaceID)
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
if err := access.EditPages(a.role); err != nil {
if err := access.CreatePageUnder(a.role, rules.role(parent), parent == ""); err != nil {
return nil, err
}
if len(files) == 0 {
+1
View File
@@ -151,6 +151,7 @@ func (a *api) routes(mux *routeMux) {
a.searchRoutes(mux)
a.transferRoutes(mux)
a.shareRoutes(mux)
a.permissionRoutes(mux)
a.commentRoutes(mux)
a.adminRoutes(mux)
}
+1
View File
@@ -41,6 +41,7 @@ type DirectoryService interface {
SearchService
TransferService
ShareService
PermissionService
CommentService
}
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// PermissionService is the part of directory.Service for page-level access.
type PermissionService interface {
GetPageAccess(ctx context.Context, c access.Caller, id string) (directory.PageAccess, error)
SetPageRestricted(ctx context.Context, c access.Caller, id string, on bool) (directory.PageAccess, error)
SharePageWithUser(ctx context.Context, c access.Caller, id, email, role string) (directory.SharePageResult, error)
SharePageWithGroup(ctx context.Context, c access.Caller, id, groupID, role string) (directory.PageAccess, error)
UnsharePage(ctx context.Context, c access.Caller, id, principalType, principalID string) (directory.PageAccess, error)
}
func (a *api) permissionRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/pages/{id}/access", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pa, err := a.dir.GetPageAccess(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, pa, err)
}))
mux.HandleFunc("PATCH /api/v1/pages/{id}/access", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Restricted bool }
if !a.decode(w, r, &in) {
return
}
pa, err := a.dir.SetPageRestricted(r.Context(), caller(r), r.PathValue("id"), in.Restricted)
a.respond(w, pa, err)
}))
mux.HandleFunc("PUT /api/v1/pages/{id}/access/users", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Email, Role string }
if !a.decode(w, r, &in) {
return
}
res, err := a.dir.SharePageWithUser(r.Context(), caller(r), r.PathValue("id"), in.Email, in.Role)
a.respond(w, res, err)
}))
mux.HandleFunc("DELETE /api/v1/pages/{id}/access/users/{userId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pa, err := a.dir.UnsharePage(r.Context(), caller(r), r.PathValue("id"), "user", r.PathValue("userId"))
a.respond(w, pa, err)
}))
mux.HandleFunc("PUT /api/v1/pages/{id}/access/groups/{groupId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Role string }
if !a.decode(w, r, &in) {
return
}
pa, err := a.dir.SharePageWithGroup(r.Context(), caller(r), r.PathValue("id"), r.PathValue("groupId"), in.Role)
a.respond(w, pa, err)
}))
mux.HandleFunc("DELETE /api/v1/pages/{id}/access/groups/{groupId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pa, err := a.dir.UnsharePage(r.Context(), caller(r), r.PathValue("id"), "group", r.PathValue("groupId"))
a.respond(w, pa, err)
}))
}
@@ -1,7 +1,7 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { PageNode } from "@docwell/api-client";
import { DwButton, DwTreeItem } from "@docwell/ui";
import { DwButton, DwIcon, DwTreeItem } from "@docwell/ui";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { dropPlacement, zoneAt, type DropZone } from "../lib/tree";
@@ -110,6 +110,13 @@ const dropClass = computed(() => {
>
<span v-if="node.icon" class="mr-1">{{ node.icon }}</span
>{{ node.title || $t("home.untitled") }}
<DwIcon
v-if="node.restricted"
name="lock"
:size="12"
class="ml-1 !inline-block align-[-1px] text-ink-muted"
:label="$t('share.restrictedBadge')"
/>
</RouterLink>
<template v-if="editable" #actions>
<DwButton
+262 -24
View File
@@ -2,7 +2,11 @@
<script setup lang="ts">
import {
ApiError,
type Group,
type Page,
type PageAccess,
type PageGrant,
type PageGrantRole,
type ShareLink,
type Space,
type SpaceGroup,
@@ -14,43 +18,73 @@ import { useApi } from "../api";
import { useFormErrors } from "../composables/useFormErrors";
import { spaceAtLeast } from "../stores/spaces";
// Who can open a page, and its public link. Access comes from the space;
// changing it is done in the space settings.
// Who can open a page, and its public link. The space gives the baseline
// (changed in the space settings); the page adds people and groups, and can
// be restricted to them.
const open = defineModel<boolean>({ default: false });
const props = defineProps<{ page: Page }>();
const emit = defineEmits<{ changed: [] }>();
const api = useApi();
const errors = useFormErrors();
const grantRoles: PageGrantRole[] = ["editor", "commenter", "viewer"];
const space = ref<Space | null>(null);
const members = ref<SpaceMember[]>([]);
const groups = ref<SpaceGroup[]>([]);
const workspaceGroups = ref<Group[]>([]);
const pageAccess = ref<PageAccess | null>(null);
const link = ref<ShareLink | null>(null);
const busy = ref(false);
const copied = ref("");
const notice = ref("");
const inviteLink = ref("");
const dialog = ref<HTMLElement | null>(null);
// The add-people form: an email, or a group picked from the list.
const who = ref("");
const whoRole = ref<PageGrantRole>("viewer");
const canEdit = computed(() => spaceAtLeast(props.page.role, "editor") && !props.page.inTrash);
const canManage = computed(() => !!pageAccess.value?.canManage && !props.page.inTrash);
const pageUrl = computed(() => `${location.origin}/p/${props.page.id}`);
const ownGrants = computed(() => pageAccess.value?.grants.filter((g) => !g.inherited) ?? []);
const inheritedGrants = computed(() => pageAccess.value?.grants.filter((g) => g.inherited) ?? []);
const groupMatches = computed(() => {
const q = who.value.trim().toLowerCase();
if (!q || q.includes("@")) return [];
const granted = new Set(ownGrants.value.filter((g) => g.type === "group").map((g) => g.id));
return workspaceGroups.value.filter((g) => !granted.has(g.id) && g.name.toLowerCase().includes(q)).slice(0, 5);
});
const orNull = <T,>(p: Promise<T>) =>
p.catch((e) => {
if (e instanceof ApiError && (e.status === 404 || e.status === 403)) return null;
throw e;
});
watch(open, async (v) => {
if (!v) return;
errors.reset();
copied.value = "";
copied.value = notice.value = inviteLink.value = who.value = "";
await nextTick();
dialog.value?.focus();
try {
const [s, m, g] = await Promise.all([
api.spaces.get(props.page.space),
api.spaces.members(props.page.space),
api.spaces.groups(props.page.space),
]);
const [s, acc] = await Promise.all([api.spaces.get(props.page.space), api.pages.access(props.page.id)]);
space.value = s;
members.value = m;
groups.value = g;
link.value = await api.pages.shareLink(props.page.id).catch((e) => {
if (e instanceof ApiError && e.status === 404) return null;
throw e;
});
pageAccess.value = acc;
// Someone who sees only shared pages cannot list the space's members or
// the workspace's groups.
const [m, g, wg, l] = await Promise.all([
s.limited ? null : orNull(api.spaces.members(props.page.space)),
s.limited ? null : orNull(api.spaces.groups(props.page.space)),
acc.canManage && !s.limited ? orNull(api.workspaces.groups(s.workspace)) : null,
orNull(api.pages.shareLink(props.page.id)),
]);
members.value = m ?? [];
groups.value = g ?? [];
workspaceGroups.value = wg ?? [];
link.value = l;
} catch (e) {
errors.show(e);
}
@@ -59,6 +93,7 @@ watch(open, async (v) => {
async function run(action: () => Promise<void>) {
busy.value = true;
errors.reset();
notice.value = "";
try {
await action();
} catch (e) {
@@ -81,7 +116,57 @@ const setSubpages = (on: boolean) =>
link.value = await api.pages.setShareLink(props.page.id, on);
});
async function copy(which: "page" | "public", text: string) {
const setRestricted = (on: boolean) =>
run(async () => {
pageAccess.value = await api.pages.setRestricted(props.page.id, on);
emit("changed");
});
const addEmail = (email: string) =>
run(async () => {
const res = await api.pages.shareWithUser(props.page.id, email, whoRole.value);
pageAccess.value = res.access;
who.value = "";
if (res.invite) {
notice.value = res.invite.mailed ? "share.invited" : "share.invitedNoMail";
inviteLink.value = res.invite.mailed ? "" : (res.invite.link ?? "");
}
emit("changed");
});
const addGroup = (g: Group) =>
run(async () => {
pageAccess.value = await api.pages.shareWithGroup(props.page.id, g.id, whoRole.value);
who.value = "";
emit("changed");
});
function submitWho() {
const v = who.value.trim();
if (v.includes("@")) addEmail(v);
else if (groupMatches.value[0]) addGroup(groupMatches.value[0]);
}
const changeRole = (g: PageGrant, role: PageGrantRole) =>
run(async () => {
pageAccess.value =
g.type === "group"
? await api.pages.shareWithGroup(props.page.id, g.id, role)
: (await api.pages.shareWithUser(props.page.id, g.email, role)).access;
});
const removeGrant = (g: PageGrant) =>
run(async () => {
pageAccess.value =
g.type === "group"
? await api.pages.unshareGroup(props.page.id, g.id)
: await api.pages.unshareUser(props.page.id, g.id);
emit("changed");
});
const revokeInvite = (id: string) =>
run(async () => {
await api.invites.revoke(id);
pageAccess.value = await api.pages.access(props.page.id);
});
async function copy(which: string, text: string) {
await navigator.clipboard.writeText(text);
copied.value = which;
setTimeout(() => (copied.value = ""), 2000);
@@ -92,7 +177,7 @@ async function copy(which: "page" | "public", text: string) {
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 px-4 pt-[10vh]"
class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/40 px-4 py-[10vh]"
@mousedown.self="open = false"
@keydown.esc="open = false"
>
@@ -118,24 +203,177 @@ async function copy(which: "page" | "public", text: string) {
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-3">{{
errors.message.value
}}</DwCallout>
<DwCallout v-if="notice" tone="success" size="ui" class="mt-3">
{{ $t(notice) }}
<span v-if="inviteLink" class="mt-2 flex gap-2">
<input
:value="inviteLink"
readonly
class="dw-input min-w-0 flex-1 font-mono text-ui-sm"
:aria-label="$t('share.inviteLink')"
@focus="($event.target as HTMLInputElement).select()"
/>
<DwButton size="sm" icon="link" @click="copy('invite', inviteLink)">
{{ copied === "invite" ? $t("workspace.copied") : $t("workspace.copyLink") }}
</DwButton>
</span>
</DwCallout>
<section class="mt-4">
<!-- People and groups this page is shared with. -->
<section v-if="pageAccess" class="mt-4">
<h3 class="dw-label">{{ $t("share.people") }}</h3>
<form v-if="canManage" class="relative mt-2 flex gap-2" @submit.prevent="submitWho">
<input
v-model="who"
class="dw-input min-w-0 flex-1"
:placeholder="$t(workspaceGroups.length ? 'share.addPlaceholderGroups' : 'share.addPlaceholder')"
:aria-label="$t('share.addPeople')"
autocomplete="off"
data-testid="share-who"
/>
<select v-model="whoRole" class="dw-input w-auto" :aria-label="$t('share.role')">
<option v-for="r in grantRoles" :key="r" :value="r">{{ $t(`space.roles.${r}`) }}</option>
</select>
<DwButton type="submit" variant="primary" :disabled="busy || !who.trim()" data-testid="share-add">
{{ $t("share.add") }}
</DwButton>
<ul
v-if="groupMatches.length"
class="absolute left-0 top-full z-10 mt-1 w-64 rounded-sm border border-line bg-surface-raised py-1 shadow-dialog"
role="listbox"
>
<li v-for="g in groupMatches" :key="g.id">
<button
type="button"
class="flex w-full items-center gap-2 px-3 py-1.5 text-left text-ui-md hover:bg-surface-hover"
@click="addGroup(g)"
>
<DwIcon name="users" :size="16" class="text-ink-muted" />{{ g.name }}
</button>
</li>
</ul>
</form>
<p v-if="canManage && !pageAccess.canInvite" class="mt-1 text-ui-sm text-ink-muted">
{{ $t("share.membersOnly") }}
</p>
<ul class="mt-3 space-y-1" data-testid="share-grants">
<li v-for="g in ownGrants" :key="g.type + g.id" class="flex items-center gap-2 text-ui-md">
<DwIcon :name="g.type === 'group' ? 'users' : 'at'" :size="16" class="text-ink-muted" />
<span class="min-w-0 flex-1 truncate">
{{ g.name || g.email }}
<span v-if="g.email && g.name" class="text-ui-sm text-ink-muted">{{ g.email }}</span>
</span>
<select
v-if="canManage"
:value="g.role"
class="dw-input w-auto py-0.5 text-ui-sm"
:aria-label="$t('share.roleFor', { name: g.name || g.email })"
:disabled="busy"
@change="changeRole(g, ($event.target as HTMLSelectElement).value as PageGrantRole)"
>
<option v-for="r in grantRoles" :key="r" :value="r">{{ $t(`space.roles.${r}`) }}</option>
</select>
<span v-else class="text-ui-sm text-ink-muted">{{ $t(`space.roles.${g.role}`) }}</span>
<DwButton
v-if="canManage"
variant="ghost"
size="sm"
icon="close"
class="!size-6"
:aria-label="$t('share.remove', { name: g.name || g.email })"
:disabled="busy"
@click="removeGrant(g)"
/>
</li>
<li
v-for="inv in pageAccess.invites"
:key="inv.id"
class="flex items-center gap-2 text-ui-md text-ink-muted"
>
<DwIcon name="clock" :size="16" />
<span class="min-w-0 flex-1 truncate">{{ inv.email }} · {{ $t("share.pending") }}</span>
<span class="text-ui-sm">{{ $t(`space.roles.${inv.role}`) }}</span>
<DwButton
variant="ghost"
size="sm"
icon="close"
class="!size-6"
:aria-label="$t('share.revokeInvite', { email: inv.email })"
:disabled="busy"
@click="revokeInvite(inv.id)"
/>
</li>
<li
v-for="g in inheritedGrants"
:key="'i' + g.type + g.id + g.page.id"
class="flex items-center gap-2 text-ui-md"
>
<DwIcon :name="g.type === 'group' ? 'users' : 'at'" :size="16" class="text-ink-muted" />
<span class="min-w-0 flex-1 truncate">
{{ g.name || g.email }}
<span class="text-ui-sm text-ink-muted">{{
$t("share.inheritedFrom", { page: g.page.title || $t("home.untitled") })
}}</span>
</span>
<span class="text-ui-sm text-ink-muted">{{ $t(`space.roles.${g.role}`) }}</span>
</li>
</ul>
<p
v-if="!ownGrants.length && !inheritedGrants.length && !pageAccess.invites.length"
class="mt-2 text-ui-sm text-ink-muted"
>
{{ $t("share.noPeople") }}
</p>
</section>
<!-- The space's own audience, unless the page is restricted. -->
<section class="mt-6 border-t border-line pt-4">
<h3 class="dw-label">{{ $t("share.access") }}</h3>
<p class="mt-2 flex items-start gap-2 text-ui-md">
<label v-if="pageAccess" class="mt-2 flex items-start gap-3 text-ui-md">
<input
type="checkbox"
class="mt-1 accent-primary"
:checked="pageAccess.restricted"
:disabled="busy || !canManage || !!pageAccess.inheritedFrom"
data-testid="share-restricted"
@change="setRestricted(($event.target as HTMLInputElement).checked)"
/>
<span>
<span class="font-medium">{{ $t("share.restrict") }}</span>
<span class="block text-ui-sm text-ink-muted">
{{
pageAccess.inheritedFrom
? $t("share.restrictedBy", { page: pageAccess.inheritedFrom.title || $t("home.untitled") })
: $t("share.restrictHint")
}}
</span>
</span>
</label>
<p v-if="space && !pageAccess?.restricted" class="mt-3 flex items-start gap-2 text-ui-md">
<DwIcon
:name="space?.visibility === 'private' ? 'lock' : 'users'"
:name="space.visibility === 'private' ? 'lock' : 'users'"
:size="18"
class="mt-0.5 text-ink-muted"
/>
<span v-if="space">
<span>
{{
space.visibility === "private"
? $t("share.privateSpace", { space: space.name })
: $t("share.openSpace", { space: space.name, role: $t(`space.roles.${space.defaultRole}`) })
space.limited
? $t("share.limitedSpace", { space: space.name })
: space.visibility === "private"
? $t("share.privateSpace", { space: space.name })
: $t("share.openSpace", { space: space.name, role: $t(`space.roles.${space.defaultRole}`) })
}}
</span>
</p>
<ul v-if="members.length || groups.length" class="mt-2 space-y-1 text-ui-sm text-ink-muted">
<p v-else-if="space" class="mt-3 flex items-start gap-2 text-ui-md">
<DwIcon name="lock" :size="18" class="mt-0.5 text-ink-muted" />
<span>{{ $t("share.restrictedSpace", { space: space.name }) }}</span>
</p>
<ul
v-if="!pageAccess?.restricted && (members.length || groups.length)"
class="mt-2 space-y-1 text-ui-sm text-ink-muted"
>
<li v-for="g in groups" :key="g.group.id">{{ g.group.name }} · {{ $t(`space.roles.${g.role}`) }}</li>
<li v-for="m in members" :key="m.user.id">
{{ m.user.name }} ({{ m.user.email }}) · {{ $t(`space.roles.${m.role}`) }}
+9 -1
View File
@@ -4,7 +4,15 @@ import type { PageNode } from "@docwell/api-client";
import { describe, expect, it } from "vitest";
import { applyMove, childrenByParent, dropPlacement, isWithin, zoneAt } from "./tree";
const node = (id: string, parent = ""): PageNode => ({ id, parent, title: id, icon: "", position: "", updated: "" });
const node = (id: string, parent = ""): PageNode => ({
id,
parent,
title: id,
icon: "",
position: "",
restricted: false,
updated: "",
});
// a
// a1
+25 -2
View File
@@ -205,7 +205,8 @@
"commenter": "Commenter",
"viewer": "Viewer"
},
"import": "Import"
"import": "Import",
"sharedWithYou": "Shared with you"
},
"page": {
"title": "Page title",
@@ -293,7 +294,29 @@
"subpages": "Include the pages inside it",
"editorsOnly": "Editors of this space can turn the public link on or off.",
"readOnly": "Shared page · read only",
"gone": "This link does not work any more. Ask the person who shared it for a new one."
"gone": "This link does not work any more. Ask the person who shared it for a new one.",
"people": "People with access",
"addPeople": "Add people",
"addPlaceholder": "Email address",
"addPlaceholderGroups": "Email address or group name",
"role": "Role",
"roleFor": "Role for {name}",
"add": "Share",
"remove": "Remove {name}",
"pending": "invited",
"revokeInvite": "Cancel the invite for {email}",
"inheritedFrom": "· from {page}",
"noPeople": "Not shared with anyone beyond the space yet. Pages inside this one get the same people.",
"membersOnly": "Only workspace members can invite people from outside the workspace.",
"invited": "Invite sent. They join the workspace as a guest and see only what is shared with them.",
"invitedNoMail": "Invite created, but email is not set up. Send them this link:",
"inviteLink": "Invite link",
"restrict": "Only the people above can open it",
"restrictHint": "Space members lose access to this page and the pages inside it. Space admins keep it.",
"restrictedBy": "Restricted because {page} is restricted.",
"restrictedBadge": "Restricted",
"restrictedSpace": "Members of {space} cannot open it unless it is shared with them. Space admins can.",
"limitedSpace": "You see only the pages of {space} that are shared with you."
},
"editor": {
"slashMenu": "Insert block",
+25 -2
View File
@@ -205,7 +205,8 @@
"commenter": "Komentujący",
"viewer": "Czytelnik"
},
"import": "Importuj"
"import": "Importuj",
"sharedWithYou": "Udostępnione Tobie"
},
"page": {
"title": "Tytuł strony",
@@ -293,7 +294,29 @@
"subpages": "Uwzględnij strony wewnątrz",
"editorsOnly": "Edytorzy tej przestrzeni mogą włączać i wyłączać link publiczny.",
"readOnly": "Udostępniona strona · tylko do odczytu",
"gone": "Ten link już nie działa. Poproś osobę, która go udostępniła, o nowy."
"gone": "Ten link już nie działa. Poproś osobę, która go udostępniła, o nowy.",
"people": "Osoby z dostępem",
"addPeople": "Dodaj osoby",
"addPlaceholder": "Adres e-mail",
"addPlaceholderGroups": "Adres e-mail lub nazwa grupy",
"role": "Rola",
"roleFor": "Rola dla {name}",
"add": "Udostępnij",
"remove": "Usuń {name}",
"pending": "zaproszono",
"revokeInvite": "Anuluj zaproszenie dla {email}",
"inheritedFrom": "· ze strony {page}",
"noPeople": "Nie udostępniono jeszcze nikomu spoza przestrzeni. Strony wewnątrz otrzymują te same osoby.",
"membersOnly": "Tylko członkowie obszaru roboczego mogą zapraszać osoby spoza niego.",
"invited": "Zaproszenie wysłane. Dołączy do obszaru roboczego jako gość i zobaczy tylko to, co mu udostępniono.",
"invitedNoMail": "Zaproszenie utworzone, ale e-mail nie jest skonfigurowany. Wyślij ten link:",
"inviteLink": "Link z zaproszeniem",
"restrict": "Otworzyć ją mogą tylko osoby powyżej",
"restrictHint": "Członkowie przestrzeni tracą dostęp do tej strony i stron wewnątrz. Administratorzy przestrzeni go zachowują.",
"restrictedBy": "Ograniczona, ponieważ strona {page} jest ograniczona.",
"restrictedBadge": "Ograniczona",
"restrictedSpace": "Członkowie {space} nie mogą jej otworzyć, chyba że zostanie im udostępniona. Administratorzy przestrzeni mogą.",
"limitedSpace": "Widzisz tylko te strony z {space}, które Ci udostępniono."
},
"editor": {
"slashMenu": "Wstaw blok",
+2 -1
View File
@@ -82,7 +82,8 @@ watch(
<span class="mt-auto flex flex-wrap items-center gap-2 pt-3 text-ui-sm text-ink-muted">
{{ $t("space.pageCount", { n: spaces.trees[s.id]?.length ?? 0 }, spaces.trees[s.id]?.length ?? 0) }}
<DwBadge v-if="s.visibility === 'private'">{{ $t("space.private") }}</DwBadge>
<DwBadge tone="accent">{{ $t(`space.roles.${s.role}`) }}</DwBadge>
<DwBadge v-if="s.limited" tone="accent">{{ $t("space.sharedWithYou") }}</DwBadge>
<DwBadge v-else tone="accent">{{ $t(`space.roles.${s.role}`) }}</DwBadge>
</span>
</RouterLink>
</li>
+9 -1
View File
@@ -167,6 +167,14 @@ const crumbs = computed(() => {
];
});
// Sharing changed who sees what: refresh the caller's role and the tree.
async function accessChanged() {
const p = page.value;
if (!p) return;
page.value = await api.pages.get(p.id).catch(() => p);
void spaces.loadTree(p.space);
}
async function load(id: string) {
notFound.value = false;
try {
@@ -360,7 +368,7 @@ const purge = () =>
</DwButton>
<DwMenu :items="menu" :label="$t('page.more')" data-testid="page-menu" />
</Teleport>
<ShareDialog v-if="page" v-model="shareOpen" :page="page" />
<ShareDialog v-if="page" v-model="shareOpen" :page="page" @changed="accessChanged" />
<div class="flex min-h-full items-start">
<article class="mx-auto min-w-0 max-w-doc flex-1 px-4 pt-6 pb-16 sm:px-16 sm:pt-10">
+184 -7
View File
@@ -1434,6 +1434,133 @@ paths:
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
# Page-level permissions: grants to people and groups, and restricted pages.
/api/v1/pages/{id}/access:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getPageAccess
tags: [sharing]
summary: Who has access to the page beyond the space's members (viewer)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PageAccess" }
"404": { $ref: "#/components/responses/Error" }
patch:
operationId: setPageRestricted
tags: [sharing]
summary: Restrict the page and its subpages to the people it is shared with, or lift that (editor)
description: Space admins always keep access. An editor who restricts a page keeps editor on it through a grant.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [restricted]
properties:
restricted: { type: boolean }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PageAccess" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/access/users:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
put:
operationId: sharePageWithUser
tags: [sharing]
summary: Share the page and its subpages with someone by email (editor)
description: >-
A workspace member gets the role on the page. Someone from the workspace's organization who is not
in the workspace joins it as a guest. Anyone else is invited as a guest (workspace members only).
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [email, role]
properties:
email: { type: string, format: email }
role: { $ref: "#/components/schemas/PageGrantRole" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/SharePageResult" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
"409": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/access/users/{userId}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: userId, in: path, required: true, schema: { type: string } }
delete:
operationId: unsharePageWithUser
tags: [sharing]
summary: Remove someone's grant on the page (editor, or the person themselves)
security: [{ bearer: [] }]
responses:
"200":
description: The page's access afterwards
content:
application/json:
schema: { $ref: "#/components/schemas/PageAccess" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/access/groups/{groupId}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: groupId, in: path, required: true, schema: { type: string } }
put:
operationId: sharePageWithGroup
tags: [sharing]
summary: Share the page and its subpages with a group of the workspace (editor)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [role]
properties:
role: { $ref: "#/components/schemas/PageGrantRole" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PageAccess" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: unsharePageWithGroup
tags: [sharing]
summary: Remove a group's grant on the page (editor)
security: [{ bearer: [] }]
responses:
"200":
description: The page's access afterwards
content:
application/json:
schema: { $ref: "#/components/schemas/PageAccess" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
# Public share links: read access for anyone with the link.
/api/v1/pages/{id}/share:
parameters:
@@ -1824,7 +1951,7 @@ components:
description: open - every workspace member gets the default role; private - explicit members only.
Space:
type: object
required: [id, workspace, name, slug, icon, description, visibility, defaultRole, role, created]
required: [id, workspace, name, slug, icon, description, visibility, defaultRole, role, limited, created]
properties:
id: { type: string }
workspace: { type: string }
@@ -1834,7 +1961,8 @@ components:
description: { type: string }
visibility: { $ref: "#/components/schemas/SpaceVisibility" }
defaultRole: { $ref: "#/components/schemas/SpaceDefaultRole" }
role: { $ref: "#/components/schemas/SpaceRole" }
role: { $ref: "#/components/schemas/SpaceCallerRole" }
limited: { type: boolean, description: The caller cannot open the space itself and sees only pages shared with them }
created: { type: string }
SpaceMember:
type: object
@@ -1850,13 +1978,16 @@ components:
role: { $ref: "#/components/schemas/SpaceRole" }
PageNode:
type: object
required: [id, parent, title, icon, position, updated]
required: [id, parent, title, icon, position, restricted, updated]
properties:
id: { type: string }
parent: { type: string, description: Parent page id; empty at the top level }
parent:
type: string
description: Parent page id; empty at the top level. In a page tree, a page whose parent the caller cannot open hangs from its nearest visible ancestor.
title: { type: string }
icon: { type: string }
position: { type: string, description: Fractional sort key among siblings }
restricted: { type: boolean, description: This page itself is restricted }
updated: { type: string }
PageRef:
type: object
@@ -1867,7 +1998,7 @@ components:
icon: { type: string }
Page:
type: object
required: [id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, ancestors, role, favorite]
required: [id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, ancestors, role, restricted, favorite]
properties:
id: { type: string }
workspace: { type: string }
@@ -1879,9 +2010,55 @@ components:
updated: { type: string }
deletedAt: { type: string, description: When the page itself was trashed; empty otherwise }
inTrash: { type: boolean, description: The page or one of its ancestors is in the trash }
ancestors: { type: array, items: { $ref: "#/components/schemas/PageRef" }, description: Root first }
role: { $ref: "#/components/schemas/SpaceRole" }
ancestors: { type: array, items: { $ref: "#/components/schemas/PageRef" }, description: Root first; pages the caller cannot open are left out }
role: { $ref: "#/components/schemas/SpaceRole", description: The caller's role on this page }
restricted: { type: boolean, description: The page or one of its ancestors is restricted }
favorite: { type: boolean, description: In the caller's favorites }
PageGrantRole: { type: string, enum: [editor, commenter, viewer] }
SpaceCallerRole:
type: string
enum: [admin, editor, commenter, viewer, ""]
description: The caller's space role; empty when they see only pages shared with them
PageGrant:
type: object
required: [type, id, name, email, role, page, inherited]
properties:
type: { type: string, enum: [user, group] }
id: { type: string }
name: { type: string }
email: { type: string, description: Empty for groups }
role: { $ref: "#/components/schemas/PageGrantRole" }
page: { $ref: "#/components/schemas/PageRef", description: Where the grant was made }
inherited: { type: boolean, description: Granted on an ancestor }
PageInvite:
type: object
required: [id, email, role, expires]
properties:
id: { type: string }
email: { type: string }
role: { $ref: "#/components/schemas/PageGrantRole" }
expires: { type: string }
PageAccess:
type: object
required: [restricted, inheritedFrom, grants, invites, role, canManage, canInvite]
properties:
restricted: { type: boolean, description: The page or an ancestor is restricted; space members then see it only through grants }
inheritedFrom:
oneOf: [{ $ref: "#/components/schemas/PageRef" }, { type: "null" }]
description: The restricted ancestor, when the restriction comes from one
grants: { type: array, items: { $ref: "#/components/schemas/PageGrant" }, description: This page's grants first, then inherited ones }
invites: { type: array, items: { $ref: "#/components/schemas/PageInvite" }, description: Pending guest invites for this page (editors only) }
role: { $ref: "#/components/schemas/SpaceRole", description: The caller's role on this page }
canManage: { type: boolean }
canInvite: { type: boolean, description: May share with people outside the workspace, who join as guests }
SharePageResult:
type: object
required: [access, invite]
properties:
access: { $ref: "#/components/schemas/PageAccess" }
invite:
oneOf: [{ $ref: "#/components/schemas/Invite" }, { type: "null" }]
description: Set when the person was invited as a guest; the grant is made when they accept
PageContent:
type: object
required: [content, updated]