Skip to content

Normalize Key IDs #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Sources/WebPush/Helpers/DataProtocol+Base64URLCoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@ extension DataProtocol {
func base64URLEncodedString() -> String {
Data(self)
.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.transformToBase64URLEncoding()
}
}

extension String {
/// Transform a regular Base64 encoded string to a Base64URL encoded one.
@usableFromInline
func transformToBase64URLEncoding() -> String {
self.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/WebPush/VAPID/VAPIDKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ extension VAPID.Key: Identifiable {

public init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
self.rawValue = try container.decode(String.self)
self.rawValue = try container.decode(String.self).transformToBase64URLEncoding()
}

public func encode(to encoder: any Encoder) throws {
Expand Down
1 change: 1 addition & 0 deletions Tests/WebPushTests/VAPIDKeyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ import WebPushTesting

@Test func decoding() throws {
#expect(try JSONDecoder().decode(VAPID.Key.ID.self, from: Data("\"BLf3RZAljlexEovBgfZgFTjcEVUKBDr3lIH8quJioMdX4FweRdId_P72h613ptxtU-qSAyW3Tbt_3WgwGhOUxrs\"".utf8)) == .mockedKeyID1)
#expect(try JSONDecoder().decode(VAPID.Key.ID.self, from: Data("\"BLf3RZAljlexEovBgfZgFTjcEVUKBDr3lIH8quJioMdX4FweRdId/P72h613ptxtU+qSAyW3Tbt/3WgwGhOUxrs=\"".utf8)) == .mockedKeyID1)
}
}
}