zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
//! What an OAuth request grants, for people: consent rows (a bold line saying
//! what the app can do, a muted line saying where or whose, and optionally a
//! list behind a chevron) and the fuller breakdown the details sheet shows.
//! Everything is derived from the scope string, the small naming tables below,
//! and a permission set's own lexicon text. Nothing is written per app.
const std = @import("std");
const scope_rules = @import("../../internal/scopes.zig");
pub const Icon = enum { records, files, space, service, read, report, permission_set, account, identity };
pub const Row = struct {
icon: Icon,
title: []const u8,
detail: []const u8,
/// Shown when the row is expanded; rows without it are static.
more: []const []const u8 = &.{},
warning: bool = false,
};
/// Title and detail a permission set's lexicon gives for one `include:` scope.
pub const PermissionSetText = struct {
scope: []const u8,
title: []const u8,
detail: []const u8,
expanded: []const u8 = "",
};
pub const RecordLine = struct {
/// "Create, change, delete".
verbs: []const u8,
collections: []const []const u8,
};
pub const Owner = enum { you, anyone, account };
pub const SpaceAccess = struct {
owner: Owner,
/// The authority DID when `owner` is `.account`.
authority: []const u8 = "",
/// "any key", or the one space key the scope names.
key: ?[]const u8,
view: ?[]const u8 = null,
write_collections: []const []const u8 = &.{},
write_verbs: ?[]const u8 = null,
manage: ?[]const u8 = null,
};
pub const SpaceType = struct {
nsid: []const u8,
access: []const SpaceAccess,
};
pub const ServiceCalls = struct {
/// The audience DID, or "*" for any service.
aud: []const u8,
methods: []const []const u8,
};
pub const SetEntry = struct {
nsid: []const u8,
title: []const u8,
detail: []const u8,
expanded: []const []const u8,
};
pub const Summary = struct {
rows: []const Row,
records: []const RecordLine = &.{},
any_records: ?[]const u8 = null,
/// Accepted upload types; empty when uploads are not requested.
files: []const []const u8 = &.{},
spaces: []const SpaceType = &.{},
services: []const ServiceCalls = &.{},
sets: []const SetEntry = &.{},
/// Scopes the sections above do not cover, shown as they are.
other: []const []const u8 = &.{},
full_identity: bool = false,
};
const Actions = packed struct(u3) {
create: bool = false,
update: bool = false,
delete: bool = false,
const all: Actions = .{ .create = true, .update = true, .delete = true };
fn bits(self: Actions) u3 {
return @bitCast(self);
}
fn any(self: Actions) bool {
return self.bits() != 0;
}
fn merge(self: *Actions, other: Actions) void {
self.* = @bitCast(self.bits() | other.bits());
}
};
/// Bluesky record types, in the order rows list them. Collections that read
/// as the same thing to a person share a name.
const bluesky_collections = [_]struct { []const u8, []const u8 }{
.{ "app.bsky.actor.profile", "profile" },
.{ "app.bsky.feed.post", "posts" },
.{ "app.bsky.feed.like", "likes" },
.{ "app.bsky.feed.repost", "reposts" },
.{ "app.bsky.graph.follow", "follows" },
.{ "app.bsky.graph.block", "blocks" },
.{ "app.bsky.graph.list", "lists" },
.{ "app.bsky.graph.listitem", "lists" },
.{ "app.bsky.graph.listblock", "list blocks" },
.{ "app.bsky.graph.starterpack", "starter packs" },
.{ "app.bsky.graph.verification", "verifications" },
.{ "app.bsky.feed.threadgate", "reply settings" },
.{ "app.bsky.feed.postgate", "quote settings" },
.{ "app.bsky.feed.generator", "feeds" },
.{ "app.bsky.actor.status", "status" },
.{ "app.bsky.notification.declaration", "activity subscription settings" },
.{ "chat.bsky.actor.declaration", "chat settings" },
};
/// Services whose display name is not their reversed domain.
const service_names = [_]struct { []const u8, []const u8 }{
.{ "app.bsky", "Bluesky" },
.{ "chat.bsky", "Bluesky chat" },
};
/// The NSID segment before an XRPC method, named for people, for calls that
/// change something on any service.
const method_groups = [_]struct { []const u8, []const u8 }{
.{ "notification", "notifications" },
.{ "graph", "connections" },
.{ "actor", "profile and preferences" },
.{ "feed", "posts and feeds" },
.{ "bookmark", "bookmarks" },
.{ "convo", "messages" },
.{ "video", "videos" },
};
/// Method-name prefixes that only read. Every other method is taken to change
/// something, which never understates what a request can do.
const read_prefixes = [_][]const u8{ "get", "list", "search", "query", "describe", "resolve", "check", "count" };
/// Nouns that stay singular in a list ("your tracks and profile").
const singular_nouns = [_][]const u8{ "profile", "status", "settings", "preferences", "configuration", "declaration", "audio", "chat", "data", "media" };
const report_method = "com.atproto.moderation.createReport";
const max_named = 4;
/// Service rows a consent card lists before it folds them into one per service.
const max_service_rows = 4;
/// The calls an app makes to one service, for its folded row.
const ServiceArea = struct {
name: []const u8,
/// What the calls touch, in order: "notifications", "webhook", "CI".
areas: []const []const u8,
actions: usize,
reads_only: bool,
/// "54 actions: notifications, webhooks, secrets…".
fn summary(self: ServiceArea, a: std.mem.Allocator) ![]const u8 {
const shown = @min(self.areas.len, 3);
return std.fmt.allocPrint(a, "{d} action{s}: {s}{s}", .{
self.actions,
if (self.actions == 1) "" else "s",
try std.mem.join(a, ", ", self.areas[0..shown]),
if (self.areas.len > shown) "…" else "",
});
}
};
/// What one call touches, named by the NSID segment before the method:
/// Bluesky's segments use the shared names, other services' read as written,
/// and short ones are taken for acronyms ("ci" → "CI").
fn areaName(a: std.mem.Allocator, key: []const u8, lxm: []const u8) ![]const u8 {
const group = groupSegment(lxm) orelse return humanize(a, lastSegment(lxm));
if (std.mem.eql(u8, key, "app.bsky") or std.mem.eql(u8, key, "chat.bsky")) {
for (method_groups) |entry| if (std.mem.eql(u8, entry[0], group)) return entry[1];
}
if (std.mem.eql(u8, group, "notification")) return "notifications";
if (group.len <= 2) return std.ascii.allocUpperString(a, group);
return humanize(a, group);
}
pub fn describe(allocator: std.mem.Allocator, scope_text: []const u8, sets: []const PermissionSetText, app_host: ?[]const u8) !Summary {
var b: Builder = .{ .allocator = allocator, .app_host = app_host };
var scopes = std.mem.tokenizeScalar(u8, scope_text, ' ');
while (scopes.next()) |scope| try b.add(scope, sets);
return b.finish();
}
/// Whether the request asks for every identity attribute, which can take over
/// or permanently break the account.
pub fn requestsFullIdentity(scope_text: []const u8) bool {
var scopes = std.mem.tokenizeScalar(u8, scope_text, ' ');
while (scopes.next()) |scope| {
const parsed = resource(scope, "identity") orelse continue;
if (std.mem.eql(u8, parsed.positional, "*")) return true;
}
return false;
}
/// The domain a service's NSID authority names: `social.grain` is grain.social.
pub fn serviceName(allocator: std.mem.Allocator, key: []const u8) ![]const u8 {
for (service_names) |entry| if (std.mem.eql(u8, entry[0], key)) return entry[1];
const dot = std.mem.indexOfScalar(u8, key, '.') orelse return key;
return std.fmt.allocPrint(allocator, "{s}.{s}", .{ key[dot + 1 ..], key[0..dot] });
}
/// The host a `did:web` audience names, or the audience itself.
pub fn audienceHost(allocator: std.mem.Allocator, aud: []const u8) ![]const u8 {
if (!std.mem.startsWith(u8, aud, "did:web:")) return aud;
const rest = aud["did:web:".len..];
const end = std.mem.indexOfScalar(u8, rest, '#') orelse rest.len;
return std.mem.replaceOwned(u8, allocator, rest[0..end], "%3A", ":");
}
const Collection = struct { nsid: []const u8, actions: Actions };
const SpaceGrant = struct {
space_type: []const u8,
authority: []const u8,
skey: ?[]const u8,
read: bool = false,
read_self: bool = false,
write: Actions = .{},
collections: std.ArrayList([]const u8) = .empty,
manage: Actions = .{},
};
const Method = struct { lxm: []const u8, aud: []const u8 };
const Builder = struct {
allocator: std.mem.Allocator,
app_host: ?[]const u8,
seen: std.ArrayList([]const u8) = .empty,
head_rows: std.ArrayList(Row) = .empty,
tail_rows: std.ArrayList(Row) = .empty,
account_rows: std.ArrayList(Row) = .empty,
set_rows: std.ArrayList(Row) = .empty,
collections: std.ArrayList(Collection) = .empty,
any_records: Actions = .{},
blob_types: std.ArrayList([]const u8) = .empty,
grants: std.ArrayList(SpaceGrant) = .empty,
methods: std.ArrayList(Method) = .empty,
sets: std.ArrayList(SetEntry) = .empty,
other: std.ArrayList([]const u8) = .empty,
only_atproto: bool = true,
full_identity: bool = false,
fn add(self: *Builder, scope: []const u8, sets: []const PermissionSetText) !void {
const a = self.allocator;
if (contains(self.seen.items, scope)) return;
try self.seen.append(a, scope);
if (std.mem.eql(u8, scope, "atproto")) return;
self.only_atproto = false;
if (std.mem.eql(u8, scope, "transition:generic")) {
try self.head_rows.append(a, .{ .icon = .records, .title = "Create, change and delete any of your data", .detail = "and act as you on any service" });
try self.other.append(a, scope);
} else if (std.mem.eql(u8, scope, "transition:email")) {
try self.tail_rows.append(a, .{ .icon = .account, .title = "Read your email address", .detail = "Your account" });
try self.other.append(a, scope);
} else if (std.mem.eql(u8, scope, "transition:chat.bsky")) {
try self.tail_rows.append(a, .{ .icon = .service, .title = "Read and send Bluesky chat messages", .detail = "via Bluesky chat" });
try self.other.append(a, scope);
} else if (std.mem.startsWith(u8, scope, "include:")) {
try self.addSet(scope, sets);
} else if (resource(scope, "repo")) |parsed| {
try self.addRepo(parsed);
} else if (resource(scope, "rpc")) |parsed| {
const aud = try percentDecode(a, firstParam(parsed.query, "aud") orelse "*");
if (parsed.positional.len > 0) try self.methods.append(a, .{ .lxm = parsed.positional, .aud = aud });
var it = params(parsed.query, "lxm");
while (it.next()) |lxm| try self.methods.append(a, .{ .lxm = lxm, .aud = aud });
} else if (resource(scope, "blob")) |parsed| {
if (parsed.positional.len > 0) try self.addBlobType(parsed.positional);
var it = params(parsed.query, "accept");
var any_param = false;
while (it.next()) |value| {
any_param = true;
try self.addBlobType(value);
}
if (parsed.positional.len == 0 and !any_param) try self.addBlobType("*/*");
} else if (resource(scope, "account")) |parsed| {
try self.account_rows.append(a, accountRow(parsed));
try self.other.append(a, scope);
} else if (resource(scope, "identity")) |parsed| {
const full = std.mem.eql(u8, parsed.positional, "*");
if (full) self.full_identity = true;
try self.head_rows.append(a, if (full)
.{ .icon = .identity, .title = "Manage your whole identity", .detail = "Including your @handle and the keys that control your account", .warning = true }
else
.{ .icon = .identity, .title = "Change your @handle", .detail = "Your identity" });
try self.other.append(a, scope);
} else if (scope_rules.isSpaceScope(scope)) {
try self.addSpace(scope);
} else {
try self.tail_rows.append(a, .{ .icon = .service, .title = "Other access", .detail = scope });
try self.other.append(a, scope);
}
}
fn addSet(self: *Builder, scope: []const u8, sets: []const PermissionSetText) !void {
const a = self.allocator;
const nsid = includeNsid(scope);
const text = for (sets) |set| {
if (std.mem.eql(u8, set.scope, scope)) break set;
} else PermissionSetText{ .scope = scope, .title = nsid, .detail = "" };
const publisher = try serviceName(a, serviceKey(nsid));
try self.set_rows.append(a, .{
.icon = .permission_set,
.title = try sentenceCase(a, text.title, publisher),
.detail = try std.fmt.allocPrint(a, "As described by {s}", .{publisher}),
});
var expanded: std.ArrayList([]const u8) = .empty;
var parts = std.mem.tokenizeScalar(u8, text.expanded, ' ');
while (parts.next()) |part| try expanded.append(a, part);
try self.sets.append(a, .{ .nsid = nsid, .title = text.title, .detail = text.detail, .expanded = expanded.items });
}
fn addRepo(self: *Builder, parsed: Resource) !void {
const actions = repoActions(parsed.query);
var named = false;
if (parsed.positional.len > 0) {
try self.addCollection(parsed.positional, actions);
named = true;
}
var it = params(parsed.query, "collection");
while (it.next()) |collection| {
try self.addCollection(collection, actions);
named = true;
}
if (!named) self.any_records.merge(actions);
}
fn addCollection(self: *Builder, nsid: []const u8, actions: Actions) !void {
if (std.mem.eql(u8, nsid, "*")) return self.any_records.merge(actions);
for (self.collections.items) |*existing| {
if (std.mem.eql(u8, existing.nsid, nsid)) return existing.actions.merge(actions);
}
try self.collections.append(self.allocator, .{ .nsid = nsid, .actions = actions });
}
fn addBlobType(self: *Builder, value: []const u8) !void {
if (!contains(self.blob_types.items, value)) try self.blob_types.append(self.allocator, value);
}
fn addSpace(self: *Builder, scope: []const u8) !void {
const a = self.allocator;
const space_type = scope_rules.spaceScopeType(scope) orelse "*";
const query = if (std.mem.indexOfScalar(u8, scope, '?')) |idx| scope[idx + 1 ..] else "";
const authority = firstParam(query, "authority") orelse "self";
const skey_param = firstParam(query, "skey");
const skey: ?[]const u8 = if (skey_param) |value| (if (std.mem.eql(u8, value, "*")) null else value) else null;
const grant = for (self.grants.items) |*existing| {
if (std.mem.eql(u8, existing.space_type, space_type) and std.mem.eql(u8, existing.authority, authority) and optionalEql(existing.skey, skey)) break existing;
} else blk: {
try self.grants.append(a, .{ .space_type = space_type, .authority = authority, .skey = skey });
break :blk &self.grants.items[self.grants.items.len - 1];
};
var saw_action = false;
var write: Actions = .{};
var actions = params(query, "action");
while (actions.next()) |action| {
saw_action = true;
if (std.mem.eql(u8, action, "read")) grant.read = true;
if (std.mem.eql(u8, action, "read_self")) grant.read_self = true;
if (std.mem.eql(u8, action, "create")) write.create = true;
if (std.mem.eql(u8, action, "update")) write.update = true;
if (std.mem.eql(u8, action, "delete")) write.delete = true;
}
var saw_collection = false;
var collections = params(query, "collection");
while (collections.next()) |collection| {
saw_collection = true;
if (!contains(grant.collections.items, collection)) try grant.collections.append(a, collection);
}
// Without an action list a space scope allows reading, and writing
// whatever collections it names.
if (!saw_action) {
grant.read = true;
if (saw_collection) write = Actions.all;
}
if (saw_collection) grant.write.merge(write);
var manages = params(query, "manage");
while (manages.next()) |manage| {
if (std.mem.eql(u8, manage, "create")) grant.manage.create = true;
if (std.mem.eql(u8, manage, "update")) grant.manage.update = true;
if (std.mem.eql(u8, manage, "delete")) grant.manage.delete = true;
}
}
fn finish(self: *Builder) !Summary {
const a = self.allocator;
var rows: std.ArrayList(Row) = .empty;
try rows.appendSlice(a, self.head_rows.items);
try rows.appendSlice(a, self.set_rows.items);
if (self.only_atproto) {
try rows.append(a, .{ .icon = .account, .title = "Know which account is yours", .detail = "and nothing else" });
}
const records = try self.recordRows(&rows);
try rows.appendSlice(a, self.account_rows.items);
const files = try self.fileRow(&rows);
const spaces = try self.spaceRows(&rows);
const services = try self.serviceRows(&rows);
try rows.appendSlice(a, self.tail_rows.items);
return .{
.rows = rows.items,
.records = records,
.any_records = if (self.any_records.any()) sheetVerbs(self.any_records) else null,
.files = files,
.spaces = spaces,
.services = services,
.sets = self.sets.items,
.other = self.other.items,
.full_identity = self.full_identity,
};
}
/// Services in the order rows list them: the app's own first, then by
/// first appearance.
fn orderedServices(self: *Builder, keys: []const []const u8) ![]const []const u8 {
const a = self.allocator;
var own: std.ArrayList([]const u8) = .empty;
var rest: std.ArrayList([]const u8) = .empty;
for (keys) |key| {
if (self.isAppService(key)) try own.append(a, key) else try rest.append(a, key);
}
try own.appendSlice(a, rest.items);
return own.items;
}
fn isAppService(self: *Builder, key: []const u8) bool {
const host = self.app_host orelse return false;
const domain = serviceName(self.allocator, key) catch return false;
return std.mem.eql(u8, host, domain) or (std.mem.endsWith(u8, host, domain) and host.len > domain.len and host[host.len - domain.len - 1] == '.');
}
fn recordRows(self: *Builder, rows: *std.ArrayList(Row)) ![]const RecordLine {
const a = self.allocator;
if (self.any_records.any()) {
try rows.append(a, .{ .icon = .records, .title = try std.fmt.allocPrint(a, "{s} any record in your repo", .{try capitalize(a, verbPhrase(self.any_records))}), .detail = "Every app's records" });
}
var keys: std.ArrayList([]const u8) = .empty;
for (self.collections.items) |collection| {
const key = serviceKey(collection.nsid);
if (!contains(keys.items, key)) try keys.append(a, key);
}
for (try self.orderedServices(keys.items)) |key| {
var mine: std.ArrayList(Collection) = .empty;
var all: Actions = .{};
for (self.collections.items) |collection| {
if (!std.mem.eql(u8, serviceKey(collection.nsid), key)) continue;
try mine.append(a, collection);
all.merge(collection.actions);
}
try rows.append(a, try self.recordRow(key, mine.items, all));
}
// The sheet lists record types by the actions granted on them.
var lines: std.ArrayList(RecordLine) = .empty;
var sets: std.ArrayList(Actions) = .empty;
for (self.collections.items) |collection| {
if (!containsActions(sets.items, collection.actions)) try sets.append(a, collection.actions);
}
for (sets.items) |set| {
var nsids: std.ArrayList([]const u8) = .empty;
for (self.collections.items) |collection| {
if (collection.actions.bits() == set.bits()) try nsids.append(a, collection.nsid);
}
try lines.append(a, .{ .verbs = sheetVerbs(set), .collections = nsids.items });
}
return lines.items;
}
fn recordRow(self: *Builder, key: []const u8, collections: []const Collection, all: Actions) !Row {
const a = self.allocator;
const service = try serviceName(a, key);
const detail = try std.fmt.allocPrint(a, "{s} records", .{service});
var names: std.ArrayList([]const u8) = .empty;
var ranks: std.ArrayList(usize) = .empty;
for (collections) |collection| {
const entry = try collectionName(a, collection.nsid);
if (!contains(names.items, entry.name)) try insertRanked(a, &names, &ranks, entry.name, entry.rank);
}
if (names.items.len > max_named) {
var more: std.ArrayList([]const u8) = .empty;
for (collections) |collection| {
const label = try humanize(a, afterAuthority(collection.nsid));
try more.append(a, if (collection.actions.bits() == all.bits()) label else try std.fmt.allocPrint(a, "{s} · {s}", .{ label, verbPhrase(collection.actions) }));
}
return .{
.icon = .records,
.title = try std.fmt.allocPrint(a, "{s} {d} kinds of {s} records", .{ try capitalize(a, verbPhrase(all)), collections.len, service }),
.detail = detail,
.more = more.items,
};
}
// One clause per distinct set of actions, in first-appearance order.
var sets: std.ArrayList(Actions) = .empty;
for (collections) |collection| {
if (!containsActions(sets.items, collection.actions)) try sets.append(a, collection.actions);
}
var clauses: std.ArrayList([]const u8) = .empty;
for (sets.items) |set| {
var set_names: std.ArrayList([]const u8) = .empty;
var set_ranks: std.ArrayList(usize) = .empty;
for (collections) |collection| {
if (collection.actions.bits() != set.bits()) continue;
const entry = try collectionName(a, collection.nsid);
if (!contains(set_names.items, entry.name)) try insertRanked(a, &set_names, &set_ranks, entry.name, entry.rank);
}
try clauses.append(a, try std.fmt.allocPrint(a, "{s} your {s}", .{ verbPhrase(set), try joinList(a, set_names.items, "and") }));
}
const sentence = if (clauses.items.len == 2)
try std.fmt.allocPrint(a, "{s}, and {s}", .{ clauses.items[0], clauses.items[1] })
else
try std.mem.join(a, "; ", clauses.items);
return .{ .icon = .records, .title = try capitalize(a, sentence), .detail = detail };
}
fn fileRow(self: *Builder, rows: *std.ArrayList(Row)) ![]const []const u8 {
const a = self.allocator;
if (self.blob_types.items.len == 0) return &.{};
var images = false;
var videos = false;
var other = false;
for (self.blob_types.items) |value| {
if (std.mem.startsWith(u8, value, "image/")) images = true else if (std.mem.startsWith(u8, value, "video/")) videos = true else other = true;
}
const detail = if (other) "Any type, stored on your PDS" else if (images and videos) "Images and videos, stored on your PDS" else if (videos) "Videos, stored on your PDS" else "Images, stored on your PDS";
try rows.append(a, .{ .icon = .files, .title = "Upload files", .detail = detail });
var labels: std.ArrayList([]const u8) = .empty;
for (self.blob_types.items) |value| try labels.append(a, if (std.mem.eql(u8, value, "*/*")) "any type" else value);
return labels.items;
}
fn spaceRows(self: *Builder, rows: *std.ArrayList(Row)) ![]const SpaceType {
const a = self.allocator;
var types: std.ArrayList([]const u8) = .empty;
for (self.grants.items) |grant| {
if (!contains(types.items, grant.space_type)) try types.append(a, grant.space_type);
}
var out: std.ArrayList(SpaceType) = .empty;
for (types.items) |space_type| {
var access: std.ArrayList(SpaceAccess) = .empty;
// You first, then named accounts, then anyone's.
for ([_]Owner{ .you, .account, .anyone }) |owner| {
for (self.grants.items) |grant| {
if (!std.mem.eql(u8, grant.space_type, space_type) or ownerOf(grant.authority) != owner) continue;
try access.append(a, try spaceAccess(a, grant, owner));
}
}
try out.append(a, .{ .nsid = space_type, .access = access.items });
}
var families: std.ArrayList([]const u8) = .empty;
for (types.items) |space_type| {
const key = serviceKey(space_type);
if (!contains(families.items, key)) try families.append(a, key);
}
for (try self.orderedServices(families.items)) |key| {
var more: std.ArrayList([]const u8) = .empty;
var yours = false;
for (types.items) |space_type| {
if (!std.mem.eql(u8, serviceKey(space_type), key)) continue;
try more.append(a, try self.spaceSummary(space_type, &yours));
}
const service = if (std.mem.eql(u8, key, "*")) "" else try serviceName(a, key);
try rows.append(a, .{
.icon = .space,
.title = if (std.mem.eql(u8, key, "*"))
"Use private spaces of any kind"
else if (yours)
try std.fmt.allocPrint(a, "Use your private {s} spaces", .{service})
else
try std.fmt.allocPrint(a, "Use private {s} spaces shared with you", .{service}),
.detail = try std.fmt.allocPrint(a, "{d} kind{s} of space", .{ more.items.len, if (more.items.len == 1) "" else "s" }),
.more = more.items,
});
}
return out.items;
}
/// "private media · view, add and delete tracks, create spaces".
fn spaceSummary(self: *Builder, space_type: []const u8, yours: *bool) ![]const u8 {
const a = self.allocator;
var read = false;
var read_self = false;
var write: Actions = .{};
var manage: Actions = .{};
var collections: std.ArrayList([]const u8) = .empty;
for (self.grants.items) |grant| {
if (!std.mem.eql(u8, grant.space_type, space_type)) continue;
if (ownerOf(grant.authority) == .you) yours.* = true;
read = read or grant.read;
read_self = read_self or grant.read_self;
write.merge(grant.write);
manage.merge(grant.manage);
if (grant.write.any()) for (grant.collections.items) |collection| {
const name = try pluralize(a, try humanize(a, lastSegment(collection)));
if (!contains(collections.items, name)) try collections.append(a, name);
};
}
var parts: std.ArrayList([]const u8) = .empty;
if (read) try parts.append(a, "view") else if (read_self) try parts.append(a, "view your own");
if (write.any()) try parts.append(a, try std.fmt.allocPrint(a, "{s} {s}", .{ writeVerbs(write), try joinList(a, collections.items, "and") }));
if (manage.any()) try parts.append(a, try std.fmt.allocPrint(a, "{s} spaces", .{manageVerbs(manage)}));
const name = if (std.mem.eql(u8, space_type, "*")) "any kind" else try humanize(a, lastSegment(space_type));
return std.fmt.allocPrint(a, "{s} · {s}", .{ name, try std.mem.join(a, ", ", parts.items) });
}
fn serviceRows(self: *Builder, rows: *std.ArrayList(Row)) ![]const ServiceCalls {
const a = self.allocator;
var calls: std.ArrayList(ServiceCalls) = .empty;
var auds: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (!contains(auds.items, method.aud)) try auds.append(a, method.aud);
}
for (auds.items) |aud| {
var lxms: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (std.mem.eql(u8, method.aud, aud) and !contains(lxms.items, method.lxm)) try lxms.append(a, method.lxm);
}
try calls.append(a, .{ .aud = aud, .methods = lxms.items });
}
// Calls that change something on any service read best by the kind of
// thing they touch; a group with any such call takes its reads too.
var change_groups: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, "*") or isSpecial(method.lxm) or isRead(method.lxm)) continue;
const group = groupSegment(method.lxm) orelse "";
if (!contains(change_groups.items, group)) try change_groups.append(a, group);
}
var any_rows: std.ArrayList(Row) = .empty;
var use_rows: std.ArrayList(Row) = .empty;
var change_rows: std.ArrayList(Row) = .empty;
var read_rows: std.ArrayList(Row) = .empty;
var report_rows: std.ArrayList(Row) = .empty;
for (auds.items) |aud| {
const any = std.mem.eql(u8, aud, "*");
const host = try audienceHost(a, aud);
// Any method at all.
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, aud) or !std.mem.eql(u8, method.lxm, "*")) continue;
try any_rows.append(a, if (any)
.{ .icon = .service, .title = "Act as you on any service", .detail = "Any method, via any service" }
else
.{ .icon = .service, .title = try std.fmt.allocPrint(a, "Use {s} as you", .{host}), .detail = try std.fmt.allocPrint(a, "Any method, via {s}", .{host}) });
break;
}
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, aud) or !std.mem.eql(u8, method.lxm, report_method)) continue;
try report_rows.append(a, .{ .icon = .report, .title = "Send moderation reports", .detail = if (any) "via any moderation service" else try std.fmt.allocPrint(a, "via {s}", .{host}) });
break;
}
// Reads, per service.
var read_keys: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, aud) or isSpecial(method.lxm) or !isRead(method.lxm)) continue;
if (any and contains(change_groups.items, groupSegment(method.lxm) orelse "")) continue;
const key = serviceKey(method.lxm);
if (!contains(read_keys.items, key)) try read_keys.append(a, key);
}
for (read_keys.items) |key| {
var objects: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, aud) or isSpecial(method.lxm) or !isRead(method.lxm) or !std.mem.eql(u8, serviceKey(method.lxm), key)) continue;
if (any and contains(change_groups.items, groupSegment(method.lxm) orelse "")) continue;
const object = try readObject(a, method.lxm);
if (!contains(objects.items, object)) try objects.append(a, object);
}
const service = try serviceName(a, key);
try read_rows.append(a, .{
.icon = .read,
.title = if (objects.items.len > max_named)
try std.fmt.allocPrint(a, "Look up {d} kinds of {s} data", .{ objects.items.len, service })
else
try std.fmt.allocPrint(a, "Look up {s} {s}", .{ service, try joinList(a, objects.items, "and") }),
.detail = if (any) try std.fmt.allocPrint(a, "via any {s} service", .{service}) else try std.fmt.allocPrint(a, "via {s}", .{host}),
});
}
// Changes on one named service: say what they do there.
if (!any) {
var phrases: Phrases = .{};
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, aud) or isSpecial(method.lxm) or isRead(method.lxm)) continue;
try phrases.add(a, method.lxm);
}
if (phrases.count() > 0) {
try use_rows.append(a, .{
.icon = .service,
.title = try std.fmt.allocPrint(a, "Use {s} to {s}", .{ host, try phrases.sentence(a) }),
.detail = try std.fmt.allocPrint(a, "via {s}", .{host}),
});
}
}
}
// Changes on any service, by group.
for (change_groups.items) |group| {
var keys: std.ArrayList([]const u8) = .empty;
var reads = false;
for (self.methods.items) |method| {
if (!std.mem.eql(u8, method.aud, "*") or isSpecial(method.lxm)) continue;
if (!std.mem.eql(u8, groupSegment(method.lxm) orelse "", group)) continue;
if (isRead(method.lxm)) reads = true;
const key = serviceKey(method.lxm);
if (!contains(keys.items, key)) {
if (std.mem.eql(u8, key, "app.bsky")) try keys.insert(a, 0, key) else try keys.append(a, key);
}
}
var names: std.ArrayList([]const u8) = .empty;
for (keys.items) |key| try names.append(a, try serviceName(a, key));
const noun = for (method_groups) |entry| {
if (std.mem.eql(u8, entry[0], group)) break entry[1];
} else if (group.len == 0) "data" else try humanize(a, group);
try change_rows.append(a, .{
.icon = .service,
.title = try std.fmt.allocPrint(a, "{s} your {s}", .{ if (reads) "Read and change" else "Change", noun }),
.detail = try std.fmt.allocPrint(a, "via any {s} service", .{try joinList(a, names.items, "or")}),
});
}
// Past a handful of rows, one row per service keeps the consent card
// short enough that its buttons stay in reach.
if (use_rows.items.len + change_rows.items.len + read_rows.items.len > max_service_rows) {
try rows.appendSlice(a, any_rows.items);
try self.groupedServiceRows(rows);
} else {
try rows.appendSlice(a, any_rows.items);
try rows.appendSlice(a, use_rows.items);
try rows.appendSlice(a, change_rows.items);
try rows.appendSlice(a, read_rows.items);
}
try rows.appendSlice(a, report_rows.items);
return calls.items;
}
/// One row per service the app calls: its own services by name, every
/// other one together. A row lists the areas its calls touch.
fn groupedServiceRows(self: *Builder, rows: *std.ArrayList(Row)) !void {
const a = self.allocator;
var keys: std.ArrayList([]const u8) = .empty;
for (self.methods.items) |method| {
if (isSpecial(method.lxm)) continue;
const key = serviceKey(method.lxm);
if (!contains(keys.items, key)) try keys.append(a, key);
}
var others: std.ArrayList(ServiceArea) = .empty;
for (try self.orderedServices(keys.items)) |key| {
const area = try self.serviceArea(key);
if (self.isAppService(key)) {
try rows.append(a, .{
.icon = if (area.reads_only) .read else .service,
.title = try std.fmt.allocPrint(a, "{s} {s}", .{ if (area.reads_only) "Look up data on" else "Act as you on", area.name }),
.detail = try area.summary(a),
.more = area.areas,
});
} else try others.append(a, area);
}
if (others.items.len == 0) return;
const own = for (keys.items) |key| {
if (self.isAppService(key)) break true;
} else false;
if (others.items.len == 1) {
const area = others.items[0];
try rows.append(a, .{
.icon = if (area.reads_only) .read else .service,
.title = try std.fmt.allocPrint(a, "{s} {s}", .{ if (area.reads_only) "Look up data on" else "Act as you on", area.name }),
.detail = try area.summary(a),
.more = area.areas,
});
return;
}
var names: std.ArrayList([]const u8) = .empty;
var lines: std.ArrayList([]const u8) = .empty;
var reads_only = true;
for (others.items) |area| {
try names.append(a, area.name);
try lines.append(a, try std.fmt.allocPrint(a, "{s} · {s}", .{ area.name, try std.mem.join(a, ", ", area.areas) }));
if (!area.reads_only) reads_only = false;
}
try rows.append(a, .{
.icon = if (reads_only) .read else .service,
.title = try std.fmt.allocPrint(a, "{s} {d} {s}services", .{ if (reads_only) "Look up data on" else "Act as you on", others.items.len, if (own) "other " else "" }),
.detail = try std.mem.join(a, ", ", names.items),
.more = lines.items,
});
}
fn serviceArea(self: *Builder, key: []const u8) !ServiceArea {
const a = self.allocator;
var areas: std.ArrayList([]const u8) = .empty;
var counts: std.ArrayList(usize) = .empty;
var lxms: std.ArrayList([]const u8) = .empty;
var reads_only = true;
for (self.methods.items) |method| {
if (isSpecial(method.lxm) or !std.mem.eql(u8, serviceKey(method.lxm), key)) continue;
if (contains(lxms.items, method.lxm)) continue;
try lxms.append(a, method.lxm);
if (!isRead(method.lxm)) reads_only = false;
const area = try areaName(a, key, method.lxm);
for (areas.items, counts.items) |known, *count| {
if (std.mem.eql(u8, known, area)) {
count.* += 1;
break;
}
} else {
try areas.append(a, area);
try counts.append(a, 1);
}
}
// Busiest areas first, so the summary names what most calls touch.
var i: usize = 1;
while (i < areas.items.len) : (i += 1) {
var j = i;
while (j > 0 and counts.items[j - 1] < counts.items[j]) : (j -= 1) {
std.mem.swap(usize, &counts.items[j - 1], &counts.items[j]);
std.mem.swap([]const u8, &areas.items[j - 1], &areas.items[j]);
}
}
return .{ .name = try serviceName(a, key), .areas = areas.items, .actions = lxms.items.len, .reads_only = reads_only };
}
};
/// Verb phrases for calls to one service: "join jams and authorize uploads
/// and downloads". A method named by one word reads as that verb applied to
/// the segment before it; a longer name reads as itself.
const Phrases = struct {
verbs: std.ArrayList([]const u8) = .empty,
objects: std.ArrayList(std.ArrayList([]const u8)) = .empty,
plain: std.ArrayList([]const u8) = .empty,
fn add(self: *Phrases, a: std.mem.Allocator, lxm: []const u8) !void {
const name = lastSegment(lxm);
const has_upper = for (name) |c| {
if (std.ascii.isUpper(c)) break true;
} else false;
if (has_upper or std.mem.count(u8, lxm, ".") < 3) {
const phrase = try humanize(a, name);
if (!contains(self.plain.items, phrase)) try self.plain.append(a, phrase);
return;
}
const object = try pluralize(a, try humanize(a, previousSegment(lxm)));
for (self.verbs.items, self.objects.items) |verb, *objects| {
if (std.mem.eql(u8, verb, name)) {
if (!contains(objects.items, object)) try objects.append(a, object);
return;
}
}
var objects: std.ArrayList([]const u8) = .empty;
try objects.append(a, object);
try self.verbs.append(a, name);
try self.objects.append(a, objects);
}
fn count(self: Phrases) usize {
return self.verbs.items.len + self.plain.items.len;
}
fn sentence(self: Phrases, a: std.mem.Allocator) ![]const u8 {
var parts: std.ArrayList([]const u8) = .empty;
var methods: usize = 0;
for (self.verbs.items, self.objects.items) |verb, objects| {
methods += objects.items.len;
try parts.append(a, try std.fmt.allocPrint(a, "{s} {s}", .{ verb, try joinList(a, objects.items, "and") }));
}
methods += self.plain.items.len;
try parts.appendSlice(a, self.plain.items);
if (parts.items.len > 3) return std.fmt.allocPrint(a, "call {d} of its methods", .{methods});
return joinList(a, parts.items, "and");
}
};
fn spaceAccess(a: std.mem.Allocator, grant: SpaceGrant, owner: Owner) !SpaceAccess {
return .{
.owner = owner,
.authority = if (owner == .account) grant.authority else "",
.key = if (owner == .you) (if (grant.skey) |skey| skey else "any key") else null,
.view = if (grant.read) "everything in it" else if (grant.read_self) "your own records in it" else null,
.write_collections = if (grant.write.any()) grant.collections.items else &.{},
.write_verbs = if (grant.write.any()) writeVerbs(grant.write) else null,
.manage = if (grant.manage.any())
try std.fmt.allocPrint(a, "{s} {s}", .{ manageVerbs(grant.manage), if (grant.skey != null) "the space" else "spaces" })
else
null,
};
}
fn ownerOf(authority: []const u8) Owner {
if (std.mem.eql(u8, authority, "self")) return .you;
if (std.mem.eql(u8, authority, "*")) return .anyone;
return .account;
}
fn accountRow(parsed: Resource) Row {
var manage = false;
var it = params(parsed.query, "action");
while (it.next()) |action| {
if (std.mem.eql(u8, action, "manage")) manage = true;
}
const attr = parsed.positional;
if (std.mem.eql(u8, attr, "email")) return .{ .icon = .account, .title = if (manage) "Read and change your email address" else "Read your email address", .detail = "Your account" };
if (std.mem.eql(u8, attr, "repo")) return .{ .icon = .account, .title = if (manage) "Replace your whole repository" else "Read your repository's status", .detail = "Your account" };
if (std.mem.eql(u8, attr, "status")) return .{ .icon = .account, .title = if (manage) "Activate or deactivate your account" else "See whether your account is active", .detail = "Your account" };
return .{ .icon = .account, .title = if (manage) "Manage your email, repository and account status" else "Read your email, repository and account status", .detail = "Your account" };
}
fn isRead(lxm: []const u8) bool {
const name = lastSegment(lxm);
for (read_prefixes) |prefix| {
if (std.mem.startsWith(u8, name, prefix) and name.len > prefix.len and std.ascii.isUpper(name[prefix.len])) return true;
}
return false;
}
fn isSpecial(lxm: []const u8) bool {
return std.mem.eql(u8, lxm, "*") or std.mem.eql(u8, lxm, report_method);
}
/// What a read method looks up: `getProfiles` and `getProfile` are profiles.
fn readObject(a: std.mem.Allocator, lxm: []const u8) ![]const u8 {
const name = lastSegment(lxm);
for (read_prefixes) |prefix| {
if (std.mem.startsWith(u8, name, prefix) and name.len > prefix.len) return pluralizeAny(a, try humanize(a, name[prefix.len..]));
}
return humanize(a, name);
}
/// The NSID segment before the method name, when there is one past the
/// service authority.
fn groupSegment(lxm: []const u8) ?[]const u8 {
if (std.mem.count(u8, lxm, ".") < 3) return null;
return previousSegment(lxm);
}
fn previousSegment(nsid: []const u8) []const u8 {
const last_dot = std.mem.lastIndexOfScalar(u8, nsid, '.') orelse return nsid;
const previous_dot = std.mem.lastIndexOfScalar(u8, nsid[0..last_dot], '.') orelse return nsid[0..last_dot];
return nsid[previous_dot + 1 .. last_dot];
}
const NamedCollection = struct { name: []const u8, rank: usize };
fn collectionName(a: std.mem.Allocator, nsid: []const u8) !NamedCollection {
for (bluesky_collections, 0..) |entry, rank| {
if (std.mem.eql(u8, entry[0], nsid)) return .{ .name = entry[1], .rank = rank };
}
return .{ .name = try pluralize(a, try humanize(a, lastSegment(nsid))), .rank = std.math.maxInt(usize) };
}
fn insertRanked(a: std.mem.Allocator, names: *std.ArrayList([]const u8), ranks: *std.ArrayList(usize), name: []const u8, rank: usize) !void {
var index: usize = 0;
while (index < ranks.items.len and ranks.items[index] <= rank) index += 1;
try names.insert(a, index, name);
try ranks.insert(a, index, rank);
}
/// "manage", "create", "create and change"…
fn verbPhrase(actions: Actions) []const u8 {
return switch (actions.bits()) {
0b111 => "manage",
0b011 => "create and change",
0b101 => "create and delete",
0b110 => "change and delete",
0b001 => "create",
0b010 => "change",
else => "delete",
};
}
/// "Create, change, delete" for the details sheet.
fn sheetVerbs(actions: Actions) []const u8 {
return switch (actions.bits()) {
0b111 => "Create, change, delete",
0b011 => "Create, change",
0b101 => "Create, delete",
0b110 => "Change, delete",
0b001 => "Create",
0b010 => "Change",
else => "Delete",
};
}
fn writeVerbs(actions: Actions) []const u8 {
return switch (actions.bits()) {
0b111 => "add, change and delete",
0b011 => "add and change",
0b101 => "add and delete",
0b110 => "change and delete",
0b001 => "add",
0b010 => "change",
else => "delete",
};
}
fn manageVerbs(actions: Actions) []const u8 {
return switch (actions.bits()) {
0b111 => "create, configure and delete",
0b011 => "create and configure",
0b101 => "create and delete",
0b110 => "configure and delete",
0b001 => "create",
0b010 => "configure",
else => "delete",
};
}
fn repoActions(query: []const u8) Actions {
var actions: Actions = .{};
var it = params(query, "action");
while (it.next()) |action| {
if (std.mem.eql(u8, action, "create")) actions.create = true;
if (std.mem.eql(u8, action, "update")) actions.update = true;
if (std.mem.eql(u8, action, "delete")) actions.delete = true;
}
return if (actions.any()) actions else Actions.all;
}
/// Sentence case for a title written in Title Case ("Full Streamplace
/// Access"), keeping the publisher's own name; other titles stay as given.
fn sentenceCase(a: std.mem.Allocator, title: []const u8, publisher: []const u8) ![]const u8 {
var words = std.mem.tokenizeScalar(u8, title, ' ');
var count: usize = 0;
while (words.next()) |word| {
if (!std.ascii.isUpper(word[0])) return title;
count += 1;
}
if (count < 2) return title;
const plain_publisher = try std.mem.replaceOwned(u8, a, publisher, ".", "");
var out: std.ArrayList(u8) = .empty;
words = std.mem.tokenizeScalar(u8, title, ' ');
var first = true;
while (words.next()) |word| {
if (!first) try out.append(a, ' ');
const keep = first or std.ascii.eqlIgnoreCase(word, plain_publisher) or hasInnerUpper(word);
for (word, 0..) |c, i| try out.append(a, if (keep or i > 0) c else std.ascii.toLower(c));
first = false;
}
return out.toOwnedSlice(a);
}
/// An acronym or a name like "DMs" or "iOS" keeps its capitals.
fn hasInnerUpper(word: []const u8) bool {
for (word[1..]) |c| if (std.ascii.isUpper(c)) return true;
return false;
}
const Resource = struct { positional: []const u8, query: []const u8 };
/// `prefix:value?query` or `prefix?query`.
fn resource(scope: []const u8, prefix: []const u8) ?Resource {
if (!std.mem.startsWith(u8, scope, prefix)) return null;
const rest = scope[prefix.len..];
if (rest.len == 0) return .{ .positional = "", .query = "" };
const query_start = std.mem.indexOfScalar(u8, rest, '?');
if (rest[0] == '?') return .{ .positional = "", .query = rest[1..] };
if (rest[0] != ':') return null;
return .{ .positional = rest[1..(query_start orelse rest.len)], .query = if (query_start) |idx| rest[idx + 1 ..] else "" };
}
const ParamIterator = struct {
parts: std.mem.SplitIterator(u8, .scalar),
name: []const u8,
fn next(self: *ParamIterator) ?[]const u8 {
while (self.parts.next()) |part| {
const eq = std.mem.indexOfScalar(u8, part, '=') orelse continue;
if (std.mem.eql(u8, part[0..eq], self.name)) return part[eq + 1 ..];
}
return null;
}
};
fn params(query: []const u8, name: []const u8) ParamIterator {
return .{ .parts = std.mem.splitScalar(u8, query, '&'), .name = name };
}
fn firstParam(query: []const u8, name: []const u8) ?[]const u8 {
var it = params(query, name);
return it.next();
}
fn percentDecode(a: std.mem.Allocator, value: []const u8) ![]const u8 {
if (std.mem.indexOfScalar(u8, value, '%') == null) return value;
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < value.len) : (i += 1) {
if (value[i] == '%' and i + 2 < value.len) {
if (std.fmt.parseInt(u8, value[i + 1 .. i + 3], 16)) |byte| {
try out.append(a, byte);
i += 2;
continue;
} else |_| {}
}
try out.append(a, value[i]);
}
return out.toOwnedSlice(a);
}
/// The authority half of an NSID that names its service: `app.bsky` for
/// `app.bsky.feed.post`.
fn serviceKey(nsid: []const u8) []const u8 {
const first = std.mem.indexOfScalar(u8, nsid, '.') orelse return nsid;
const second = std.mem.indexOfScalarPos(u8, nsid, first + 1, '.') orelse return nsid;
return nsid[0..second];
}
fn afterAuthority(nsid: []const u8) []const u8 {
const key = serviceKey(nsid);
return if (key.len < nsid.len) nsid[key.len + 1 ..] else nsid;
}
fn lastSegment(nsid: []const u8) []const u8 {
const dot = std.mem.lastIndexOfScalar(u8, nsid, '.') orelse return nsid;
return nsid[dot + 1 ..];
}
fn includeNsid(scope: []const u8) []const u8 {
const rest = scope["include:".len..];
return rest[0..(std.mem.indexOfScalar(u8, rest, '?') orelse rest.len)];
}
/// `galleryItem` reads as "gallery item", `badge.def` as "badge def".
fn humanize(a: std.mem.Allocator, name: []const u8) ![]const u8 {
var out: std.ArrayList(u8) = .empty;
for (name, 0..) |c, i| {
if (c == '.') {
try out.append(a, ' ');
} else if (std.ascii.isUpper(c)) {
if (i > 0 and name[i - 1] != '.') try out.append(a, ' ');
try out.append(a, std.ascii.toLower(c));
} else try out.append(a, c);
}
return out.toOwnedSlice(a);
}
/// A plural for a record name: track → tracks, story → stories. Things a
/// person has one of, like a profile, stay singular.
fn pluralize(a: std.mem.Allocator, noun: []const u8) ![]const u8 {
const last_space = if (std.mem.lastIndexOfScalar(u8, noun, ' ')) |idx| idx + 1 else 0;
for (singular_nouns) |singular| if (std.mem.eql(u8, noun[last_space..], singular)) return noun;
return pluralizeAny(a, noun);
}
/// A plural for anything looked up, where one may be many: profile → profiles.
fn pluralizeAny(a: std.mem.Allocator, noun: []const u8) ![]const u8 {
const last_space = if (std.mem.lastIndexOfScalar(u8, noun, ' ')) |idx| idx + 1 else 0;
const word = noun[last_space..];
if (word.len == 0 or std.mem.endsWith(u8, word, "s")) return noun;
if (std.mem.endsWith(u8, word, "y") and word.len > 1 and std.mem.indexOfScalar(u8, "aeiou", word[word.len - 2]) == null) {
return std.fmt.allocPrint(a, "{s}ies", .{noun[0 .. noun.len - 1]});
}
if (std.mem.endsWith(u8, word, "ch") or std.mem.endsWith(u8, word, "sh") or std.mem.endsWith(u8, word, "x")) {
return std.fmt.allocPrint(a, "{s}es", .{noun});
}
return std.fmt.allocPrint(a, "{s}s", .{noun});
}
fn capitalize(a: std.mem.Allocator, text: []const u8) ![]const u8 {
if (text.len == 0) return text;
const out = try a.dupe(u8, text);
out[0] = std.ascii.toUpper(out[0]);
return out;
}
/// "a", "a and b", "a, b and c".
fn joinList(a: std.mem.Allocator, items: []const []const u8, conjunction: []const u8) ![]const u8 {
if (items.len == 0) return "";
if (items.len == 1) return items[0];
const head = try std.mem.join(a, ", ", items[0 .. items.len - 1]);
return std.fmt.allocPrint(a, "{s} {s} {s}", .{ head, conjunction, items[items.len - 1] });
}
fn contains(items: []const []const u8, value: []const u8) bool {
for (items) |item| if (std.mem.eql(u8, item, value)) return true;
return false;
}
fn containsActions(items: []const Actions, value: Actions) bool {
for (items) |item| if (item.bits() == value.bits()) return true;
return false;
}
fn optionalEql(x: ?[]const u8, y: ?[]const u8) bool {
if (x == null or y == null) return x == null and y == null;
return std.mem.eql(u8, x.?, y.?);
}
// Real scope strings, as published by each client.
const noti_scope = "atproto rpc:social.grain.notification.listNotifications?aud=* rpc:social.grain.notification.updateSeen?aud=* rpc:org.tangled.temp.notification.listNotifications?aud=* rpc:org.tangled.temp.notification.markAllRead?aud=* repo:app.bsky.graph.block repo:app.bsky.graph.follow rpc:app.bsky.notification.listNotifications?aud=* rpc:app.bsky.notification.listActivitySubscriptions?aud=* rpc:app.bsky.notification.putActivitySubscription?aud=* rpc:app.bsky.notification.updateSeen?aud=* rpc:app.bsky.notification.getUnreadCount?aud=* rpc:app.bsky.notification.getPreferences?aud=* rpc:app.bsky.notification.putPreferencesV2?aud=* rpc:app.bsky.graph.getMutes?aud=* rpc:app.bsky.graph.getBlocks?aud=* rpc:app.bsky.graph.muteActor?aud=* rpc:app.bsky.graph.unmuteActor?aud=* rpc:app.bsky.actor.getProfile?aud=* rpc:app.bsky.actor.getProfiles?aud=* rpc:app.bsky.actor.getPreferences?aud=* rpc:app.bsky.feed.getPosts?aud=* repo:app.bsky.graph.list repo:app.bsky.graph.listitem rpc:app.bsky.graph.getLists?aud=* rpc:app.bsky.graph.getList?aud=* rpc:fm.plyr.notification.listNotifications?aud=* rpc:fm.plyr.notification.updateSeen?aud=*";
const plyr_scope = "atproto repo:fm.plyr.track repo:fm.plyr.list repo:fm.plyr.like repo:fm.plyr.actor.profile blob:*/* rpc:fm.plyr.stg.jam.join?aud=did:web:plyr-jams-next.fly.dev#jams rpc:fm.plyr.upload.authorize?aud=did:web:plyr-jams-next.fly.dev#jams rpc:fm.plyr.download.authorize?aud=did:web:plyr-jams-next.fly.dev#jams space:fm.plyr.privateMedia?authority=*&collection=fm.plyr.track&action=read space:fm.plyr.stg.audio?authority=*&collection=fm.plyr.track&action=read space:fm.plyr.stg.jam?authority=self&collection=fm.plyr.stg.jamState&action=create&action=update&manage=create&manage=update space:fm.plyr.stg.jam?authority=*&action=read space:fm.plyr.privateMedia?authority=self&skey=self&collection=fm.plyr.track&action=read&action=create&manage=create space:fm.plyr.privateMedia?authority=self&skey=self&collection=fm.plyr.track&action=read&action=delete";
const stream_scope = "atproto blob:*/* repo?collection=app.bsky.feed.post&action=create repo?collection=app.bsky.actor.status repo?collection=app.bsky.graph.block repo?collection=app.bsky.graph.follow repo?collection=app.bsky.actor.profile rpc:app.bsky.actor.getProfile?aud=did:web:api.bsky.app%23bsky_appview rpc:app.bsky.actor.getProfiles?aud=did:web:api.bsky.app%23bsky_appview include:place.stream.authFull rpc:com.atproto.moderation.createReport?aud=* repo?collection=place.stream.badge.def repo?collection=place.stream.badge.issuance repo?collection=place.stream.beta.invite repo?collection=place.stream.beta.request repo?collection=place.stream.broadcast.origin repo?collection=place.stream.broadcast.syndication repo?collection=place.stream.chat.access repo?collection=place.stream.chat.gate repo?collection=place.stream.chat.message repo?collection=place.stream.chat.pinnedRecord repo?collection=place.stream.chat.profile repo?collection=place.stream.ingest.audioRendition repo?collection=place.stream.ingest.videoRendition repo?collection=place.stream.key repo?collection=place.stream.like repo?collection=place.stream.live.recommendations repo?collection=place.stream.live.teleport repo?collection=place.stream.live.viewerCount repo?collection=place.stream.livestream repo?collection=place.stream.media.origin repo?collection=place.stream.media.track repo?collection=place.stream.media.viewCount repo?collection=place.stream.metadata.configuration repo?collection=place.stream.moderation.permission repo?collection=place.stream.multistream.target repo?collection=place.stream.segment repo?collection=place.stream.server.settings repo?collection=place.stream.video repo?collection=place.stream.vod.comment repo?collection=place.stream.vod.draftVideo repo?collection=place.stream.vod.gate";
const tangled_scope = "atproto blob:*/* identity:handle repo:org.tangled.feed.comment repo:org.tangled.feed.reaction repo:org.tangled.feed.subscription repo:org.tangled.snippet.string repo:org.tangled.actor.profile repo:org.tangled.feed.star repo:org.tangled.graph.follow repo:org.tangled.graph.vouch repo:org.tangled.graph.attestation repo:org.tangled.repo.artifact repo:org.tangled.repo.declaration repo:org.tangled.key.sshKey repo:org.tangled.key.unspecced.gpgKey repo:org.tangled.git.refs repo:org.tangled.graph.collaborator repo:org.tangled.knot.member repo:org.tangled.knot.block repo:org.tangled.label.definition repo:org.tangled.repo.manifest repo:org.tangled.repo.review.unspecced.round repo:org.tangled.review.patch repo:org.tangled.track.ticket repo:org.tangled.track.unspecced.milestone rpc:com.atproto.moderation.createReport?aud=* rpc:com.atproto.repo.createRecord?aud=* rpc:com.atproto.repo.deleteRecord?aud=* rpc:com.atproto.repo.putRecord?aud=* rpc:com.atproto.repo.uploadBlob?aud=* rpc:com.atproto.server.describeServer?aud=* rpc:org.tangled.temp.account.addEmail?aud=* rpc:org.tangled.temp.account.deleteEmail?aud=* rpc:org.tangled.temp.account.listEmails?aud=* rpc:org.tangled.temp.account.setPrimaryEmail?aud=* rpc:org.tangled.temp.account.verifyEmail?aud=* rpc:org.tangled.temp.server.redeemInviteCode?aud=* rpc:com.bad-example.pocket.getPreferences?aud=* rpc:com.bad-example.pocket.putPreferences?aud=* rpc:org.tangled.temp.migrator.createTask?aud=* rpc:org.tangled.temp.migrator.describeSource?aud=* rpc:org.tangled.temp.migrator.getTask?aud=* rpc:org.tangled.temp.migrator.listTasks?aud=* rpc:org.tangled.temp.migrator.retryJob?aud=* rpc:org.tangled.temp.notification.getPreferences?aud=* rpc:org.tangled.temp.notification.getUnreadCount?aud=* rpc:org.tangled.temp.notification.listNotifications?aud=* rpc:org.tangled.temp.notification.markAllRead?aud=* rpc:org.tangled.temp.notification.markEntityRead?aud=* rpc:org.tangled.temp.notification.updatePreferences?aud=* rpc:org.tangled.temp.notification.updateSeen?aud=* rpc:org.tangled.temp.search.searchCode?aud=* rpc:org.tangled.secret.addSecret?aud=* rpc:org.tangled.secret.listSecrets?aud=* rpc:org.tangled.secret.removeSecret?aud=* rpc:org.tangled.webhook.createWebhook?aud=* rpc:org.tangled.webhook.deleteWebhook?aud=* rpc:org.tangled.webhook.listWebhookDeliveries?aud=* rpc:org.tangled.webhook.listWebhooks?aud=* rpc:org.tangled.webhook.retryWebhookDelivery?aud=* rpc:org.tangled.webhook.updateWebhook?aud=* rpc:org.tangled.temp.site.claimDomain?aud=* rpc:org.tangled.temp.site.getDomainClaim?aud=* rpc:org.tangled.temp.site.releaseDomain?aud=* rpc:org.tangled.temp.repo.disableSite?aud=* rpc:org.tangled.temp.repo.deploySite?aud=* rpc:org.tangled.temp.repo.getDeployHistory?aud=* rpc:org.tangled.temp.repo.getSiteConfig?aud=* rpc:org.tangled.temp.repo.updateSiteConfig?aud=* rpc:org.tangled.actor.getTrending?aud=* rpc:org.tangled.ci.approvePipeline?aud=* rpc:org.tangled.ci.cancelPipeline?aud=* rpc:org.tangled.ci.retryPipeline?aud=* rpc:org.tangled.event.notifyEvent?aud=* rpc:farm.tranquil.delegation.authorize?aud=* rpc:farm.tranquil.delegation.createAccount?aud=* rpc:farm.tranquil.delegation.listControlledAccounts?aud=* rpc:org.tangled.feed.getTimeline?aud=* rpc:org.tangled.foster.unmarkLiarAccount?aud=* rpc:org.tangled.graph.listNetworkVouches?aud=* rpc:org.tangled.repo.createRepo?aud=* rpc:org.tangled.repo.deleteRepo?aud=* rpc:org.tangled.repo.mintToken?aud=* rpc:org.tangled.review.submitPatch?aud=* rpc:org.tangled.git.setDefaultBranch?aud=* rpc:org.tangled.git.receivePack?aud=* account:*?action=manage";
fn expectRows(expected: []const [2][]const u8, actual: []const Row) !void {
for (expected, 0..) |want, i| {
if (i >= actual.len) {
std.debug.print("missing row {d}: {s} / {s}\n", .{ i, want[0], want[1] });
return error.TestExpectedEqual;
}
try std.testing.expectEqualStrings(want[0], actual[i].title);
try std.testing.expectEqualStrings(want[1], actual[i].detail);
}
try std.testing.expectEqual(expected.len, actual.len);
}
test "noti's real scope reads as four rows" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), noti_scope, &.{}, "noti.waow.tech");
try expectRows(&.{
.{ "Manage your follows, blocks and lists", "Bluesky records" },
.{ "Read and change your notifications", "via any Bluesky, grain.social, tangled.org or plyr.fm service" },
.{ "Read and change your connections", "via any Bluesky service" },
.{ "Look up Bluesky profiles, preferences and posts", "via any Bluesky service" },
}, summary.rows);
try std.testing.expectEqual(Icon.read, summary.rows[3].icon);
try std.testing.expectEqual(@as(usize, 1), summary.services.len);
try std.testing.expectEqualStrings("*", summary.services[0].aud);
}
test "tangled.org's real scope folds its service calls into one row per service" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), tangled_scope, &.{}, "tangled.org");
try expectRows(&.{
.{ "Change your @handle", "Your identity" },
.{ "Manage 23 kinds of tangled.org records", "tangled.org records" },
.{ "Manage your email, repository and account status", "Your account" },
.{ "Upload files", "Any type, stored on your PDS" },
.{ "Act as you on tangled.org", "50 actions: repo, notifications, webhook…" },
.{ "Act as you on 3 other services", "atproto.com, bad-example.com, tranquil.farm" },
.{ "Send moderation reports", "via any moderation service" },
}, summary.rows);
try std.testing.expect(contains(summary.rows[4].more, "CI"));
try std.testing.expectEqualStrings("atproto.com · repo, server", summary.rows[5].more[0]);
try std.testing.expectEqualStrings("tranquil.farm · delegation", summary.rows[5].more[2]);
}
test "next.plyr.fm's real scope reads as the mockup's four rows" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), plyr_scope, &.{}, "next.plyr.fm");
try expectRows(&.{
.{ "Manage your tracks, lists, likes and profile", "plyr.fm records" },
.{ "Upload files", "Any type, stored on your PDS" },
.{ "Use your private plyr.fm spaces", "3 kinds of space" },
.{ "Use plyr-jams-next.fly.dev to join jams and authorize uploads and downloads", "via plyr-jams-next.fly.dev" },
}, summary.rows);
const spaces = summary.rows[2].more;
try std.testing.expectEqual(@as(usize, 3), spaces.len);
try std.testing.expectEqualStrings("private media · view, add and delete tracks, create spaces", spaces[0]);
try std.testing.expectEqualStrings("audio · view", spaces[1]);
try std.testing.expectEqualStrings("jam · view, add and change jam states, create and configure spaces", spaces[2]);
try std.testing.expectEqual(@as(usize, 0), summary.rows[0].more.len);
try std.testing.expectEqualStrings("Create, change, delete", summary.records[0].verbs);
try std.testing.expectEqual(@as(usize, 4), summary.records[0].collections.len);
try std.testing.expectEqualStrings("any type", summary.files[0]);
try std.testing.expectEqualStrings("did:web:plyr-jams-next.fly.dev#jams", summary.services[0].aud);
try std.testing.expectEqual(@as(usize, 3), summary.services[0].methods.len);
}
test "stream.place's real scope reads as six rows" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), stream_scope, &.{
.{ .scope = "include:place.stream.authFull", .title = "Full Streamplace Access", .detail = "Full access to all Streamplace features and data." },
}, "stream.place");
try expectRows(&.{
.{ "Full Streamplace access", "As described by stream.place" },
.{ "Manage 31 kinds of stream.place records", "stream.place records" },
.{ "Manage 5 kinds of Bluesky records", "Bluesky records" },
.{ "Upload files", "Any type, stored on your PDS" },
.{ "Look up Bluesky profiles", "via api.bsky.app" },
.{ "Send moderation reports", "via any moderation service" },
}, summary.rows);
try std.testing.expectEqual(@as(usize, 31), summary.rows[1].more.len);
try std.testing.expectEqualStrings("badge def", summary.rows[1].more[0]);
try std.testing.expectEqualStrings("chat pinned record", summary.rows[1].more[9]);
try std.testing.expectEqualStrings("feed post · create", summary.rows[2].more[0]);
try std.testing.expectEqualStrings("actor status", summary.rows[2].more[1]);
try std.testing.expectEqual(@as(usize, 2), summary.records.len);
try std.testing.expectEqualStrings("Create", summary.records[0].verbs);
try std.testing.expectEqualStrings("did:web:api.bsky.app#bsky_appview", summary.services[0].aud);
}
test "up to four Bluesky record types are named, in table order, with mixed actions" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), "atproto repo:app.bsky.feed.post?action=create repo:app.bsky.graph.follow repo:app.bsky.actor.profile repo:social.grain.gallery?action=create&action=delete", &.{}, null);
try expectRows(&.{
.{ "Create your posts, and manage your profile and follows", "Bluesky records" },
.{ "Create and delete your galleries", "grain.social records" },
}, summary.rows);
}
test "space access groups by type and owner, and reading is never narrowed by collection" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const summary = try describe(arena.allocator(), plyr_scope, &.{}, "next.plyr.fm");
try std.testing.expectEqual(@as(usize, 3), summary.spaces.len);
const media = summary.spaces[0];
try std.testing.expectEqualStrings("fm.plyr.privateMedia", media.nsid);
try std.testing.expectEqual(@as(usize, 2), media.access.len);
try std.testing.expectEqual(Owner.you, media.access[0].owner);
try std.testing.expectEqualStrings("self", media.access[0].key.?);
try std.testing.expectEqualStrings("everything in it", media.access[0].view.?);
try std.testing.expectEqualStrings("add and delete", media.access[0].write_verbs.?);
try std.testing.expectEqualStrings("fm.plyr.track", media.access[0].write_collections[0]);
try std.testing.expectEqualStrings("create the space", media.access[0].manage.?);
try std.testing.expectEqual(Owner.anyone, media.access[1].owner);
try std.testing.expectEqualStrings("everything in it", media.access[1].view.?);
try std.testing.expect(media.access[1].write_verbs == null);
const jam = summary.spaces[2];
try std.testing.expectEqualStrings("fm.plyr.stg.jam", jam.nsid);
try std.testing.expectEqualStrings("any key", jam.access[0].key.?);
try std.testing.expect(jam.access[0].view == null);
try std.testing.expectEqualStrings("add and change", jam.access[0].write_verbs.?);
try std.testing.expectEqualStrings("create and configure spaces", jam.access[0].manage.?);
try std.testing.expectEqual(Owner.anyone, jam.access[1].owner);
const other = try describe(arena.allocator(), "atproto space:app.example.board?authority=did:plc:friend&action=read_self space:app.example.board?authority=self&collection=app.example.post", &.{}, null);
try std.testing.expectEqual(Owner.you, other.spaces[0].access[0].owner);
try std.testing.expectEqualStrings("everything in it", other.spaces[0].access[0].view.?);
try std.testing.expectEqualStrings("add, change and delete", other.spaces[0].access[0].write_verbs.?);
try std.testing.expectEqual(Owner.account, other.spaces[0].access[1].owner);
try std.testing.expectEqualStrings("did:plc:friend", other.spaces[0].access[1].authority);
try std.testing.expectEqualStrings("your own records in it", other.spaces[0].access[1].view.?);
try expectRows(&.{.{ "Use your private example.app spaces", "1 kind of space" }}, other.rows);
try std.testing.expectEqualStrings("board · view, add, change and delete posts", other.rows[0].more[0]);
}
test "identity, account and include rows keep their meaning" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const summary = try describe(a, "atproto identity:* account:email?action=manage include:com.example.sharedAccess?aud=did:web:x.example%23svc", &.{
.{ .scope = "include:com.example.sharedAccess?aud=did:web:x.example%23svc", .title = "Shared access for Example Apps", .detail = "" },
}, null);
try expectRows(&.{
.{ "Manage your whole identity", "Including your @handle and the keys that control your account" },
.{ "Shared access for Example Apps", "As described by example.com" },
.{ "Read and change your email address", "Your account" },
}, summary.rows);
try std.testing.expect(summary.rows[0].warning);
try std.testing.expect(summary.full_identity);
try expectRows(&.{.{ "Know which account is yours", "and nothing else" }}, (try describe(a, "atproto", &.{}, null)).rows);
try std.testing.expectEqualStrings("Full Streamplace access", try sentenceCase(a, "Full Streamplace Access", "stream.place"));
try std.testing.expectEqualStrings("Read your DMs", try sentenceCase(a, "Read Your DMs", "x.example"));
}
test "nouns pluralize sensibly" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try std.testing.expectEqualStrings("tracks", try pluralize(a, "track"));
try std.testing.expectEqualStrings("profile", try pluralize(a, "profile"));
try std.testing.expectEqualStrings("stories", try pluralize(a, "story"));
try std.testing.expectEqualStrings("jam states", try pluralize(a, "jam state"));
try std.testing.expectEqualStrings("settings", try pluralize(a, "settings"));
try std.testing.expectEqualStrings("batches", try pluralize(a, "batch"));
}