// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The three Bitwarden server calls bwgpg makes. //! //! - `POST /identity/connect/token` with the personal API key, an OAuth 2.0 //! `client_credentials` grant. It needs no second factor, which is why the //! API key is used rather than the password: the password never goes to //! the server at all, and is used only to decrypt. //! - `POST /identity/accounts/prelogin`, for the account's KDF settings when //! the token response does not carry them. //! - `GET /api/sync`, the whole vault, still encrypted. //! //! A self-hosted server (Vaultwarden, or Bitwarden's own) answers both under //! one base URL, at `/identity` and `/api`. Bitwarden's cloud splits them //! across `identity.bitwarden.com` and `api.bitwarden.com`, which is what //! `Endpoints` allows for. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Value = std.json.Value; const json = @import("json_util.zig"); const crypto = @import("crypto.zig"); pub const Error = error{ /// The server refused the API key: `invalid_client` and friends. BadCredentials, /// An answer that is not what the protocol says it should be. UnexpectedResponse, /// The server answered with a status other than success, and not one /// that means the credentials were wrong. ServerError, /// The access token has expired or was revoked. Unauthorized, }; pub const Endpoints = struct { identity: []const u8, api: []const u8, /// Both under one base URL, as a self-hosted server has them. pub fn fromBase(gpa: Allocator, base: []const u8) Allocator.Error!Endpoints { const trimmed = std.mem.trimEnd(u8, base, "/"); return .{ .identity = try std.fmt.allocPrint(gpa, "{s}/identity", .{trimmed}), .api = try std.fmt.allocPrint(gpa, "{s}/api", .{trimmed}), }; } pub fn deinit(e: Endpoints, gpa: Allocator) void { gpa.free(e.identity); gpa.free(e.api); } }; pub const Credentials = struct { client_id: []const u8, client_secret: []const u8, /// A UUID naming this installation, made once by `bwgpg login` and kept, /// so the server sees one device rather than a new one at every unlock. device_id: []const u8, }; /// Bitwarden's device type numbers: the CLI on each platform, since that is /// the closest thing bwgpg is to an existing client. const device_type: []const u8 = switch (builtin.os.tag) { .windows => "23", .macos => "24", else => "25", }; pub const Token = struct { access_token: []u8, /// Seconds from when it was issued. expires_in: i64, /// The protected user key, when the response carried it. protected_key: ?[]u8, /// The KDF settings, when the response carried them. kdf: ?crypto.Kdf, pub fn deinit(t: *Token, gpa: Allocator) void { std.crypto.secureZero(u8, t.access_token); gpa.free(t.access_token); if (t.protected_key) |k| gpa.free(k); t.* = undefined; } }; pub const Client = struct { gpa: Allocator, http: std.http.Client, endpoints: Endpoints, pub fn init(gpa: Allocator, io: std.Io, endpoints: Endpoints) Client { return .{ .gpa = gpa, .http = .{ .allocator = gpa, .io = io }, .endpoints = endpoints, }; } pub fn deinit(c: *Client) void { c.http.deinit(); } const Response = struct { status: std.http.Status, body: []u8, }; fn call( c: *Client, method: std.http.Method, url: []const u8, payload: ?[]const u8, content_type: ?[]const u8, bearer: ?[]const u8, ) !Response { var body: std.Io.Writer.Allocating = .init(c.gpa); errdefer body.deinit(); var auth_buf: [4096]u8 = undefined; const auth: std.http.Client.Request.Headers.Value = if (bearer) |b| .{ .override = std.fmt.bufPrint(&auth_buf, "Bearer {s}", .{b}) catch return error.UnexpectedResponse } else .default; defer std.crypto.secureZero(u8, &auth_buf); const result = try c.http.fetch(.{ .location = .{ .url = url }, .method = method, .payload = payload, .headers = .{ .content_type = if (content_type) |ct| .{ .override = ct } else .default, .authorization = auth, .user_agent = .{ .override = "bwgpg" }, }, .extra_headers = &.{ .{ .name = "Accept", .value = "application/json" }, .{ .name = "Device-Type", .value = device_type }, .{ .name = "Bitwarden-Client-Name", .value = "cli" }, .{ .name = "Bitwarden-Client-Version", .value = "2025.1.0" }, }, .response_writer = &body.writer, }); return .{ .status = result.status, .body = try body.toOwnedSlice() }; } /// Exchanges the API key for an access token. pub fn token(c: *Client, creds: Credentials) !Token { var form: std.Io.Writer.Allocating = .init(c.gpa); defer { std.crypto.secureZero(u8, form.writer.buffer); form.deinit(); } const w = &form.writer; const fields = [_][2][]const u8{ .{ "grant_type", "client_credentials" }, .{ "scope", "api" }, .{ "client_id", creds.client_id }, .{ "client_secret", creds.client_secret }, .{ "deviceType", device_type }, .{ "deviceIdentifier", creds.device_id }, .{ "deviceName", "bwgpg" }, }; for (fields, 0..) |f, i| { if (i > 0) try w.writeByte('&'); try w.writeAll(f[0]); try w.writeByte('='); try std.Uri.Component.percentEncode(w, f[1], isFormSafe); } const url = try std.fmt.allocPrint(c.gpa, "{s}/connect/token", .{c.endpoints.identity}); defer c.gpa.free(url); const res = try c.call(.POST, url, form.written(), "application/x-www-form-urlencoded", null); defer { std.crypto.secureZero(u8, res.body); c.gpa.free(res.body); } switch (res.status) { .ok => {}, .bad_request, .unauthorized => return error.BadCredentials, else => return error.ServerError, } const parsed = std.json.parseFromSlice(Value, c.gpa, res.body, .{}) catch return error.UnexpectedResponse; defer parsed.deinit(); const v = parsed.value; const access = json.getString(v, "access_token") orelse return error.UnexpectedResponse; var t: Token = .{ .access_token = try c.gpa.dupe(u8, access), .expires_in = json.getInt(v, "expires_in") orelse 3600, .protected_key = null, .kdf = kdfFrom(v), }; errdefer t.deinit(c.gpa); if (json.getString(v, "Key")) |k| t.protected_key = try c.gpa.dupe(u8, k); return t; } /// The account's KDF settings. pub fn prelogin(c: *Client, email: []const u8) !crypto.Kdf { const body = try std.json.Stringify.valueAlloc(c.gpa, .{ .email = email }, .{}); defer c.gpa.free(body); const url = try std.fmt.allocPrint(c.gpa, "{s}/accounts/prelogin", .{c.endpoints.identity}); defer c.gpa.free(url); const res = try c.call(.POST, url, body, "application/json", null); defer c.gpa.free(res.body); if (res.status != .ok) return error.ServerError; const parsed = std.json.parseFromSlice(Value, c.gpa, res.body, .{}) catch return error.UnexpectedResponse; defer parsed.deinit(); return kdfFrom(parsed.value) orelse error.UnexpectedResponse; } /// The whole vault, as parsed JSON. The caller deinits it. pub fn sync(c: *Client, access_token: []const u8) !std.json.Parsed(Value) { const url = try std.fmt.allocPrint(c.gpa, "{s}/sync?excludeDomains=true", .{c.endpoints.api}); defer c.gpa.free(url); const res = try c.call(.GET, url, null, null, access_token); defer c.gpa.free(res.body); switch (res.status) { .ok => {}, .unauthorized => return error.Unauthorized, else => return error.ServerError, } return std.json.parseFromSlice(Value, c.gpa, res.body, .{}) catch error.UnexpectedResponse; } }; /// `application/x-www-form-urlencoded` leaves only the unreserved characters /// alone. fn isFormSafe(c: u8) bool { return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; } /// The KDF settings in a token or prelogin response, under whichever names. pub fn kdfFrom(v: Value) ?crypto.Kdf { const kind = json.getInt(v, "Kdf") orelse return null; const iterations = json.getInt(v, "KdfIterations") orelse return null; if (iterations <= 0 or iterations > std.math.maxInt(u32)) return null; return switch (kind) { 0 => .{ .pbkdf2 = .{ .iterations = @intCast(iterations) } }, 1 => blk: { const memory = json.getInt(v, "KdfMemory") orelse return null; const parallelism = json.getInt(v, "KdfParallelism") orelse return null; if (memory <= 0 or memory > 1024 or parallelism <= 0 or parallelism > 16) return null; break :blk .{ .argon2id = .{ .iterations = @intCast(iterations), .memory_mib = @intCast(memory), .parallelism = @intCast(parallelism), } }; }, else => null, }; } test "KDF settings from either casing, and nonsense refused" { const gpa = std.testing.allocator; const a = try std.json.parseFromSlice(Value, gpa, \\{"Kdf":0,"KdfIterations":600000,"KdfMemory":null,"KdfParallelism":null} , .{}); defer a.deinit(); try std.testing.expectEqual(@as(u32, 600000), kdfFrom(a.value).?.pbkdf2.iterations); const b = try std.json.parseFromSlice(Value, gpa, \\{"kdf":1,"kdfIterations":3,"kdfMemory":64,"kdfParallelism":4} , .{}); defer b.deinit(); const k = kdfFrom(b.value).?.argon2id; try std.testing.expectEqual(@as(u32, 64), k.memory_mib); try std.testing.expectEqual(@as(u24, 4), k.parallelism); const c = try std.json.parseFromSlice(Value, gpa, \\{"kdf":1,"kdfIterations":3,"kdfMemory":100000,"kdfParallelism":4} , .{}); defer c.deinit(); try std.testing.expectEqual(@as(?crypto.Kdf, null), kdfFrom(c.value)); }