const std = @import("std"); const zat = @import("zat"); const schema_collection = "com.atproto.lexicon.schema"; const default_lexicons_dir = "lexicons"; const max_lexicon_size = 2 * 1024 * 1024; const max_dns_response_size = 1024 * 1024; const usage = \\publex — check and publish AT Protocol lexicons \\ \\usage: \\ publex check [--dir lexicons] [--namespace FROM=TO] \\ publex publish [--dir lexicons] [--namespace FROM=TO] [--dry-run] [--skip-dns-check] \\ \\publish environment: \\ ATPROTO_HANDLE handle or DID owning the namespace \\ ATPROTO_PASSWORD app password (required) \\ ATPROTO_PDS_URL optional PDS override \\ \\lexicons are discovered recursively beneath ./lexicons by default. \\--namespace rewrites the source namespace in every string value, which is \\useful for staging declarations such as fm.plyr=fm.plyr.stg. \\ ; const Command = enum { check, publish }; const Replacement = struct { from: []const u8, to: []const u8, }; const Args = struct { command: Command, dir: []const u8 = default_lexicons_dir, replacement: ?Replacement = null, dry_run: bool = false, skip_dns_check: bool = false, }; const Schema = struct { path: []const u8, nsid: zat.Nsid, value: std.json.Value, }; pub fn main(init: std.process.Init) !void { const args = parseArgs(init.minimal.args) catch { std.debug.print("{s}", .{usage}); std.process.exit(2); }; var arena_state = std.heap.ArenaAllocator.init(init.gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const schemas = loadSchemas(arena, init.io, args) catch |err| { std.debug.print("publex: check failed: {t}\n", .{err}); std.process.exit(1); }; for (schemas) |schema| std.debug.print("checked {s} ({s})\n", .{ schema.nsid.str(), schema.path }); std.debug.print("checked {d} lexicon(s)\n", .{schemas.len}); if (args.command == .publish) { publishAll(arena, init.io, init.environ_map.*, schemas, args) catch |err| { std.debug.print("publex: publish failed: {t}\n", .{err}); std.process.exit(1); }; } } fn parseArgs(process_args: std.process.Args) !Args { var it = process_args.iterate(); _ = it.skip(); const command_text = it.next() orelse return error.MissingCommand; if (std.mem.eql(u8, command_text, "--help") or std.mem.eql(u8, command_text, "-h")) { std.debug.print("{s}", .{usage}); std.process.exit(0); } var result = Args{ .command = if (std.mem.eql(u8, command_text, "check")) .check else if (std.mem.eql(u8, command_text, "publish")) .publish else return error.UnknownCommand, }; while (it.next()) |arg| { if (std.mem.eql(u8, arg, "--dir")) { result.dir = it.next() orelse return error.MissingValue; } else if (std.mem.eql(u8, arg, "--namespace")) { const value = it.next() orelse return error.MissingValue; const equals = std.mem.indexOfScalar(u8, value, '=') orelse return error.InvalidNamespaceRewrite; if (equals == 0 or equals + 1 == value.len) return error.InvalidNamespaceRewrite; result.replacement = .{ .from = value[0..equals], .to = value[equals + 1 ..] }; } else if (std.mem.eql(u8, arg, "--skip-dns-check")) { result.skip_dns_check = true; } else if (std.mem.eql(u8, arg, "--dry-run")) { result.dry_run = true; } else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { std.debug.print("{s}", .{usage}); std.process.exit(0); } else { return error.UnknownArgument; } } if (result.command == .check and (result.skip_dns_check or result.dry_run)) return error.InvalidArgument; return result; } fn loadSchemas(allocator: std.mem.Allocator, io: std.Io, args: Args) ![]Schema { var paths: std.ArrayList([]const u8) = .empty; try collectJsonFiles(allocator, io, args.dir, &paths); if (paths.items.len == 0) return error.NoLexiconsFound; std.mem.sort([]const u8, paths.items, {}, lessThanString); var schemas: std.ArrayList(Schema) = .empty; var ids = std.StringHashMap(void).init(allocator); for (paths.items) |path| { const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(max_lexicon_size)); var value = std.json.parseFromSliceLeaky(std.json.Value, allocator, bytes, .{}) catch { std.debug.print("{s}: invalid JSON\n", .{path}); return error.InvalidJson; }; if (args.replacement) |replacement| try rewriteStrings(allocator, &value, replacement); const nsid = validateLexicon(path, value) catch |err| { std.debug.print("{s}: {t}\n", .{ path, err }); return err; }; if (ids.contains(nsid.str())) { std.debug.print("{s}: duplicate lexicon id {s}\n", .{ path, nsid.str() }); return error.DuplicateLexiconId; } try ids.put(nsid.str(), {}); try schemas.append(allocator, .{ .path = path, .nsid = nsid, .value = value }); } return schemas.toOwnedSlice(allocator); } fn collectJsonFiles( allocator: std.mem.Allocator, io: std.Io, path: []const u8, paths: *std.ArrayList([]const u8), ) !void { var dir = try std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }); defer dir.close(io); var iterator = dir.iterate(); while (try iterator.next(io)) |entry| { const child = try std.fs.path.join(allocator, &.{ path, entry.name }); switch (entry.kind) { .directory => try collectJsonFiles(allocator, io, child, paths), .file => if (std.mem.endsWith(u8, entry.name, ".json")) try paths.append(allocator, child), else => {}, } } } fn validateLexicon(path: []const u8, value: std.json.Value) !zat.Nsid { if (value != .object) return error.RootMustBeObject; const lexicon = value.object.get("lexicon") orelse return error.MissingLexiconVersion; if (lexicon != .integer or lexicon.integer != 1) return error.UnsupportedLexiconVersion; const id_value = value.object.get("id") orelse return error.MissingLexiconId; if (id_value != .string) return error.InvalidLexiconId; const nsid = zat.Nsid.parse(id_value.string) orelse return error.InvalidLexiconId; const defs = value.object.get("defs") orelse return error.MissingDefinitions; if (defs != .object or defs.object.count() == 0) return error.MissingDefinitions; var definitions = defs.object.iterator(); while (definitions.next()) |entry| { if (entry.value_ptr.* != .object) return error.InvalidDefinition; const type_value = entry.value_ptr.object.get("type") orelse return error.MissingDefinitionType; if (type_value != .string or type_value.string.len == 0) return error.MissingDefinitionType; } _ = path; return nsid; } fn rewriteStrings(allocator: std.mem.Allocator, value: *std.json.Value, replacement: Replacement) !void { switch (value.*) { .string => |text| value.* = .{ .string = try replaceNamespace(allocator, text, replacement) }, .array => |*array| for (array.items) |*item| try rewriteStrings(allocator, item, replacement), .object => |*object| { var it = object.iterator(); while (it.next()) |entry| try rewriteStrings(allocator, entry.value_ptr, replacement); }, else => {}, } } fn replaceNamespace(allocator: std.mem.Allocator, text: []const u8, replacement: Replacement) ![]const u8 { const needle = try std.fmt.allocPrint(allocator, "{s}.", .{replacement.from}); const substitute = try std.fmt.allocPrint(allocator, "{s}.", .{replacement.to}); return std.mem.replaceOwned(u8, allocator, text, needle, substitute); } fn publishAll( allocator: std.mem.Allocator, io: std.Io, env: std.process.Environ.Map, schemas: []Schema, args: Args, ) !void { const identifier = env.get("ATPROTO_HANDLE") orelse return error.MissingAtprotoHandle; const password = env.get("ATPROTO_PASSWORD") orelse return error.MissingAtprotoPassword; const pds = env.get("ATPROTO_PDS_URL") orelse try resolvePds(allocator, io, identifier); var client = zat.XrpcClient.init(io, allocator, pds); defer client.deinit(); const did = try login(&client, allocator, identifier, password); std.debug.print("authenticated as {s}\n", .{did}); if (!args.skip_dns_check) try verifyAuthorities(allocator, io, schemas, did); var published: usize = 0; var unchanged: usize = 0; for (schemas) |*schema| { try schema.value.object.put(allocator, "$type", .{ .string = schema_collection }); if (try recordMatches(&client, allocator, did, schema.*)) { unchanged += 1; std.debug.print("unchanged {s}\n", .{schema.nsid.str()}); continue; } if (args.dry_run) { published += 1; std.debug.print("would publish {s}\n", .{schema.nsid.str()}); continue; } try putSchema(&client, allocator, did, schema.*); published += 1; std.debug.print("published {s}\n", .{schema.nsid.str()}); } std.debug.print("{s} {d}, unchanged {d}\n", .{ if (args.dry_run) "would publish" else "published", published, unchanged, }); } fn resolvePds(allocator: std.mem.Allocator, io: std.Io, identifier: []const u8) ![]const u8 { const did_text = if (zat.Did.parse(identifier)) |_| identifier else blk: { const handle = zat.Handle.parse(identifier) orelse return error.InvalidAtprotoIdentifier; var handle_resolver = zat.HandleResolver.init(io, allocator); defer handle_resolver.deinit(); break :blk try handle_resolver.resolve(handle); }; const did = zat.Did.parse(did_text) orelse return error.InvalidDid; var did_resolver = zat.DidResolver.init(io, allocator); defer did_resolver.deinit(); var document = try did_resolver.resolve(did); defer document.deinit(); const endpoint = document.pdsEndpoint() orelse return error.NoPdsEndpoint; return allocator.dupe(u8, endpoint); } fn login(client: *zat.XrpcClient, allocator: std.mem.Allocator, identifier: []const u8, password: []const u8) ![]const u8 { const body = try std.fmt.allocPrint(allocator, "{f}", .{std.json.fmt(.{ .identifier = identifier, .password = password, }, .{})}); var result = try client.procedureChecked(zat.Nsid.parse("com.atproto.server.createSession").?, body, .{}); defer result.deinit(); return switch (result) { .err => |err| reportXrpcError("createSession", err), .ok => |response| blk: { const parsed = try std.json.parseFromSliceLeaky(std.json.Value, allocator, response.body, .{}); const did = zat.json.getString(parsed, "did") orelse return error.MissingDid; const token = zat.json.getString(parsed, "accessJwt") orelse return error.MissingToken; client.setAuth(try allocator.dupe(u8, token)); break :blk try allocator.dupe(u8, did); }, }; } fn recordMatches(client: *zat.XrpcClient, allocator: std.mem.Allocator, did: []const u8, schema: Schema) !bool { var params = std.StringHashMap([]const u8).init(allocator); defer params.deinit(); try params.put("repo", did); try params.put("collection", schema_collection); try params.put("rkey", schema.nsid.str()); var result = try client.queryChecked(zat.Nsid.parse("com.atproto.repo.getRecord").?, params, .{}); defer result.deinit(); return switch (result) { .err => |err| if (isRecordNotFound(err.status, err.error_name)) false else reportXrpcError("getRecord", err), .ok => |response| blk: { const parsed = try std.json.parseFromSliceLeaky(std.json.Value, allocator, response.body, .{}); const remote = zat.json.getPath(parsed, "value") orelse return error.MissingRecordValue; break :blk jsonEqual(schema.value, remote); }, }; } fn isRecordNotFound(status: std.http.Status, error_name: ?[]const u8) bool { const recognized_status = status == .bad_request or status == .not_found; const name = error_name orelse return false; return recognized_status and std.mem.eql(u8, name, "RecordNotFound"); } fn putSchema(client: *zat.XrpcClient, allocator: std.mem.Allocator, did: []const u8, schema: Schema) !void { const body = try std.fmt.allocPrint(allocator, "{f}", .{std.json.fmt(.{ .repo = did, .collection = schema_collection, .rkey = schema.nsid.str(), .record = schema.value, }, .{})}); var result = try client.procedureChecked(zat.Nsid.parse("com.atproto.repo.putRecord").?, body, .{}); defer result.deinit(); switch (result) { .ok => {}, .err => |err| return reportXrpcError("putRecord", err), } } fn verifyAuthorities(allocator: std.mem.Allocator, io: std.Io, schemas: []const Schema, did: []const u8) !void { var checked = std.StringHashMap(void).init(allocator); for (schemas) |schema| { const authority = schema.nsid.authority(); if (checked.contains(authority)) continue; const resolved = try resolveLexiconAuthority(allocator, io, authority); if (!std.mem.eql(u8, resolved, did)) { std.debug.print("authority {s} resolves to {s}, authenticated as {s}\n", .{ authority, resolved, did }); return error.LexiconAuthorityMismatch; } try checked.put(authority, {}); std.debug.print("verified authority {s}\n", .{authority}); } } fn resolveLexiconAuthority(allocator: std.mem.Allocator, io: std.Io, authority: []const u8) ![]const u8 { const domain = try authorityDomain(allocator, authority); const url = try std.fmt.allocPrint( allocator, "https://cloudflare-dns.com/dns-query?name=_lexicon.{s}&type=TXT", .{domain}, ); var transport = zat.HttpTransport.init(io, allocator); defer transport.deinit(); const response = try transport.fetch(.{ .url = url, .accept = "application/dns-json", .max_response_size = max_dns_response_size, .redirect_behavior = .not_allowed, }); defer allocator.free(response.body); if (response.status != .ok) return error.DnsResolutionFailed; return didFromDnsResponse(allocator, response.body); } fn authorityDomain(allocator: std.mem.Allocator, authority: []const u8) ![]const u8 { var segments: std.ArrayList([]const u8) = .empty; defer segments.deinit(allocator); var split = std.mem.splitScalar(u8, authority, '.'); while (split.next()) |segment| try segments.append(allocator, segment); std.mem.reverse([]const u8, segments.items); return std.mem.join(allocator, ".", segments.items); } fn didFromDnsResponse(allocator: std.mem.Allocator, body: []const u8) ![]const u8 { const parsed = try std.json.parseFromSliceLeaky(std.json.Value, allocator, body, .{}); const answers = zat.json.getArray(parsed, "Answer") orelse return error.NoLexiconDnsRecord; var found: ?[]const u8 = null; for (answers) |answer| { var data = zat.json.getString(answer, "data") orelse continue; if (data.len >= 2 and data[0] == '"' and data[data.len - 1] == '"') data = data[1 .. data.len - 1]; if (!std.mem.startsWith(u8, data, "did=")) continue; const candidate = data[4..]; if (zat.Did.parse(candidate) == null or found != null) return error.InvalidLexiconDnsRecord; found = candidate; } return allocator.dupe(u8, found orelse return error.NoLexiconDnsRecord); } fn jsonEqual(a: std.json.Value, b: std.json.Value) bool { if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; return switch (a) { .null => true, .bool => |value| value == b.bool, .integer => |value| value == b.integer, .float => |value| value == b.float, .number_string => |value| std.mem.eql(u8, value, b.number_string), .string => |value| std.mem.eql(u8, value, b.string), .array => |array| blk: { if (array.items.len != b.array.items.len) break :blk false; for (array.items, b.array.items) |left, right| if (!jsonEqual(left, right)) break :blk false; break :blk true; }, .object => |object| blk: { if (object.count() != b.object.count()) break :blk false; var it = object.iterator(); while (it.next()) |entry| { const other = b.object.get(entry.key_ptr.*) orelse break :blk false; if (!jsonEqual(entry.value_ptr.*, other)) break :blk false; } break :blk true; }, }; } fn reportXrpcError(operation: []const u8, err: zat.XrpcClient.XrpcError) error{XrpcCallFailed} { std.debug.print("{s} failed: {d} {s}: {s}\n", .{ operation, @intFromEnum(err.status), err.error_name orelse "(no error code)", err.message orelse err.body, }); return error.XrpcCallFailed; } fn lessThanString(_: void, left: []const u8, right: []const u8) bool { return std.mem.lessThan(u8, left, right); } test "validates future primary schema types without a closed enum" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const value = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), \\{"lexicon":1,"id":"fm.plyr.privateMedia","defs":{"main":{"type":"space","collections":["fm.plyr.track"]}}} , .{}); const nsid = try validateLexicon("privateMedia.json", value); try std.testing.expectEqualStrings("fm.plyr.privateMedia", nsid.str()); } test "namespace rewriting updates ids and nested references" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const allocator = arena_state.allocator(); var value = try std.json.parseFromSliceLeaky(std.json.Value, allocator, \\{"lexicon":1,"id":"fm.plyr.privateMediaAccess","defs":{"main":{"type":"permission-set","permissions":[{"resource":"space","spaces":["fm.plyr.privateMedia"]}]}}} , .{}); try rewriteStrings(allocator, &value, .{ .from = "fm.plyr", .to = "fm.plyr.stg" }); try std.testing.expectEqualStrings("fm.plyr.stg.privateMediaAccess", value.object.get("id").?.string); const permission = value.object.get("defs").?.object.get("main").?.object.get("permissions").?.array.items[0]; try std.testing.expectEqualStrings("fm.plyr.stg.privateMedia", permission.object.get("spaces").?.array.items[0].string); } test "JSON equality ignores object key order" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const allocator = arena_state.allocator(); const left = try std.json.parseFromSliceLeaky(std.json.Value, allocator, "{\"a\":1,\"b\":[true,null]}", .{}); const right = try std.json.parseFromSliceLeaky(std.json.Value, allocator, "{\"b\":[true,null],\"a\":1}", .{}); try std.testing.expect(jsonEqual(left, right)); } test "NSID authority reverses to its DNS domain" { const domain = try authorityDomain(std.testing.allocator, "fm.plyr.actor"); defer std.testing.allocator.free(domain); try std.testing.expectEqualStrings("actor.plyr.fm", domain); } test "extracts one DID from a lexicon DNS response" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const did = try didFromDnsResponse(arena_state.allocator(), \\{"Status":0,"Answer":[{"name":"_lexicon.plyr.fm","type":16,"TTL":300,"data":"\"did=did:plc:vs3hnzq2daqbszxlysywzy54\""}]} ); try std.testing.expectEqualStrings("did:plc:vs3hnzq2daqbszxlysywzy54", did); } test "missing schema records are publishable across PDS status conventions" { try std.testing.expect(isRecordNotFound(.not_found, "RecordNotFound")); try std.testing.expect(isRecordNotFound(.bad_request, "RecordNotFound")); try std.testing.expect(!isRecordNotFound(.internal_server_error, "RecordNotFound")); try std.testing.expect(!isRecordNotFound(.not_found, "OtherError")); try std.testing.expect(!isRecordNotFound(.not_found, null)); }