@oxy.so/services 15.1.5 → 15.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bloom/Package.bloom +15 -0
- package/bloom/Resources/Localizable/ar-SA.json +108 -0
- package/bloom/Resources/Localizable/bn-BD.json +108 -0
- package/bloom/Resources/Localizable/ca-ES.json +111 -0
- package/bloom/Resources/Localizable/de-DE.json +108 -0
- package/bloom/Resources/Localizable/en-US.json +124 -0
- package/bloom/Resources/Localizable/es-ES.json +124 -0
- package/bloom/Resources/Localizable/fr-FR.json +108 -0
- package/bloom/Resources/Localizable/hi-IN.json +108 -0
- package/bloom/Resources/Localizable/id-ID.json +108 -0
- package/bloom/Resources/Localizable/it-IT.json +108 -0
- package/bloom/Resources/Localizable/ja-JP.json +108 -0
- package/bloom/Resources/Localizable/ko-KR.json +108 -0
- package/bloom/Resources/Localizable/pt-PT.json +108 -0
- package/bloom/Resources/Localizable/ru-RU.json +108 -0
- package/bloom/Resources/Localizable/tr-TR.json +108 -0
- package/bloom/Resources/Localizable/zh-CN.json +108 -0
- package/bloom/Sources/OxyAccountUI/SignInFlow.bloom +322 -0
- package/bloom/Sources/OxyAccountUI/SignInRules.bloom +135 -0
- package/bloom/Sources/OxyAccountUI/SignInService.bloom +141 -0
- package/bloom/Sources/OxyAccountUI/SignUpFlow.bloom +322 -0
- package/bloom/Sources/OxyAccountUI/SignUpRules.bloom +189 -0
- package/bloom/Sources/OxyAccountUIChecks/Checks.bloom +254 -0
- package/bloom/Sources/OxyAccountUIChecks/FakeAuth.bloom +123 -0
- package/bloom/Sources/OxyAccountUIChecks/SignUpChecks.bloom +193 -0
- package/lib/commonjs/ui/boot/runProviderColdBoot.js +0 -2
- package/lib/commonjs/ui/boot/runProviderColdBoot.js.map +1 -1
- package/lib/commonjs/ui/context/OxyContext.js +7 -1
- package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
- package/lib/commonjs/ui/oauth/applicationSessionLane.js +12 -25
- package/lib/commonjs/ui/oauth/applicationSessionLane.js.map +1 -1
- package/lib/module/ui/boot/runProviderColdBoot.js +0 -2
- package/lib/module/ui/boot/runProviderColdBoot.js.map +1 -1
- package/lib/module/ui/context/OxyContext.js +8 -2
- package/lib/module/ui/context/OxyContext.js.map +1 -1
- package/lib/module/ui/oauth/applicationSessionLane.js +4 -23
- package/lib/module/ui/oauth/applicationSessionLane.js.map +1 -1
- package/lib/typescript/commonjs/ui/boot/runProviderColdBoot.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
- package/lib/typescript/commonjs/ui/oauth/applicationSessionLane.d.ts +1 -5
- package/lib/typescript/commonjs/ui/oauth/applicationSessionLane.d.ts.map +1 -1
- package/lib/typescript/module/ui/boot/runProviderColdBoot.d.ts.map +1 -1
- package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
- package/lib/typescript/module/ui/oauth/applicationSessionLane.d.ts +1 -5
- package/lib/typescript/module/ui/oauth/applicationSessionLane.d.ts.map +1 -1
- package/package.json +10 -5
- package/src/ui/boot/runProviderColdBoot.ts +0 -3
- package/src/ui/context/OxyContext.tsx +8 -1
- package/src/ui/oauth/applicationSessionLane.ts +7 -35
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// The calls the sign-in and sign-up screens make, and the answers they branch on.
|
|
2
|
+
//
|
|
3
|
+
// OxyCore's `OxyAuth` (oxy-core-bloom-3) implements this protocol: it makes the anonymous auth
|
|
4
|
+
// calls, keeps each request's secret in memory only and signs the device proof itself (an extern
|
|
5
|
+
// for now: core's bridge on the web, the Keystore credential on Android). `OxySession.commit` is
|
|
6
|
+
// the one bridge from a sign-in to the session. The screens never see a token or a proof.
|
|
7
|
+
//
|
|
8
|
+
// Nothing here says whether an account exists (ADR 0030 D2): the server's answers do not, and
|
|
9
|
+
// these types carry nothing more than the server's answers.
|
|
10
|
+
|
|
11
|
+
/// A sign-in email the server agreed to send (`POST /auth/signin/email/start`). The same answer
|
|
12
|
+
/// for every identifier, whether or not it names an account.
|
|
13
|
+
public struct EmailSignInStart {
|
|
14
|
+
public let requestId: String
|
|
15
|
+
/// Proves this client asked; held in memory only, never stored or logged.
|
|
16
|
+
public let requestSecret: String
|
|
17
|
+
/// The send budget is spent: nothing was sent, ask again later.
|
|
18
|
+
public let retryLater: Bool
|
|
19
|
+
|
|
20
|
+
public init(requestId: String, requestSecret: String, retryLater: Bool) {
|
|
21
|
+
self.requestId = requestId
|
|
22
|
+
self.requestSecret = requestSecret
|
|
23
|
+
self.retryLater = retryLater
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// The request a "Check your email" step confirms or collects, and the identifier it was for.
|
|
28
|
+
public struct EmailRequest: Equatable {
|
|
29
|
+
public let identifier: String
|
|
30
|
+
public let requestId: String
|
|
31
|
+
public let requestSecret: String
|
|
32
|
+
|
|
33
|
+
public init(identifier: String, requestId: String, requestSecret: String) {
|
|
34
|
+
self.identifier = identifier
|
|
35
|
+
self.requestId = requestId
|
|
36
|
+
self.requestSecret = requestSecret
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// One account of an email that holds several (ADR 0040), as the choice lists it.
|
|
41
|
+
public struct AccountOption: Equatable {
|
|
42
|
+
public let id: String
|
|
43
|
+
public let username: String?
|
|
44
|
+
public let displayName: String?
|
|
45
|
+
public let avatarUrl: String?
|
|
46
|
+
|
|
47
|
+
public init(id: String, username: String?, displayName: String?, avatarUrl: String?) {
|
|
48
|
+
self.id = id
|
|
49
|
+
self.username = username
|
|
50
|
+
self.displayName = displayName
|
|
51
|
+
self.avatarUrl = avatarUrl
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// A session the server minted, as the session layer commits it. Opaque to the screens.
|
|
56
|
+
public struct SessionGrant {
|
|
57
|
+
public let raw: JSONValue
|
|
58
|
+
|
|
59
|
+
public init(raw: JSONValue) {
|
|
60
|
+
self.raw = raw
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Where a sign-in step leads.
|
|
65
|
+
public enum SignInStep {
|
|
66
|
+
/// Signed in: commit it.
|
|
67
|
+
case session(SessionGrant)
|
|
68
|
+
/// The email holds several accounts and was just proven: which one signs in.
|
|
69
|
+
case chooseAccount([AccountOption])
|
|
70
|
+
/// The account has an authenticator: one more step.
|
|
71
|
+
case secondFactor(challengeId: String)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// How the first factor of a sign-in went, for the session layer (a platform's setup store).
|
|
75
|
+
public enum FirstFactor {
|
|
76
|
+
case emailCode
|
|
77
|
+
case password
|
|
78
|
+
case signup
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// The sign-up the server creates (`POST /auth/signup`), spending the email's ticket.
|
|
82
|
+
public struct SignUpRequest {
|
|
83
|
+
public let username: String
|
|
84
|
+
public let email: String
|
|
85
|
+
public let emailTicket: String
|
|
86
|
+
/// `YYYY-MM-DD`: the account's age band (ADR 0067).
|
|
87
|
+
public let dateOfBirth: String
|
|
88
|
+
public let languages: [String]
|
|
89
|
+
|
|
90
|
+
public init(username: String, email: String, emailTicket: String, dateOfBirth: String, languages: [String]) {
|
|
91
|
+
self.username = username
|
|
92
|
+
self.email = email
|
|
93
|
+
self.emailTicket = emailTicket
|
|
94
|
+
self.dateOfBirth = dateOfBirth
|
|
95
|
+
self.languages = languages
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// A failed call, as the screens read it: the API's machine code, the HTTP status (0: no answer)
|
|
100
|
+
/// and, on a 429, how long to wait. Never shown as the server's message, which is English: for a
|
|
101
|
+
/// refused username the server's policy message (`detail`, with `field` "username") is matched
|
|
102
|
+
/// against the policy's own sentences to name the rule.
|
|
103
|
+
public struct SignInFailure: Error, Equatable {
|
|
104
|
+
public let code: String?
|
|
105
|
+
public let status: Int
|
|
106
|
+
public let retryAfterSeconds: Double?
|
|
107
|
+
public let field: String?
|
|
108
|
+
public let detail: String?
|
|
109
|
+
|
|
110
|
+
public init(code: String?, status: Int, retryAfterSeconds: Double?, field: String?, detail: String?) {
|
|
111
|
+
self.code = code
|
|
112
|
+
self.status = status
|
|
113
|
+
self.retryAfterSeconds = retryAfterSeconds
|
|
114
|
+
self.field = field
|
|
115
|
+
self.detail = detail
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// A failure with only a code and a status.
|
|
120
|
+
public func signInFailure(_ code: String?, _ status: Int) -> SignInFailure {
|
|
121
|
+
SignInFailure(code: code, status: status, retryAfterSeconds: none, field: none, detail: none)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// The auth calls behind the screens. Every method throws a `SignInFailure`.
|
|
125
|
+
public protocol SignInService {
|
|
126
|
+
func emailStart(_ identifier: String) async throws -> EmailSignInStart
|
|
127
|
+
func emailConfirm(_ request: EmailRequest, code: String) async throws -> SignInStep
|
|
128
|
+
/// `none` while the link has not been opened in this browser.
|
|
129
|
+
func emailCollect(_ request: EmailRequest) async throws -> SignInStep?
|
|
130
|
+
func emailChoose(_ request: EmailRequest, userId: String) async throws -> SignInStep
|
|
131
|
+
func passwordSignIn(identifier: String, password: String) async throws -> SignInStep
|
|
132
|
+
func completeSecondFactor(challengeId: String, code: String) async throws -> SignInStep
|
|
133
|
+
func usernameAvailable(_ username: String) async throws -> Bool
|
|
134
|
+
/// Sends a code to a new account's email; the verification's id.
|
|
135
|
+
func startSignupVerification(email: String) async throws -> String
|
|
136
|
+
/// The code it sent → the one-use ticket a sign-up spends.
|
|
137
|
+
func confirmVerification(_ verificationId: String, code: String) async throws -> String
|
|
138
|
+
func signUp(_ request: SignUpRequest) async throws -> SignInStep
|
|
139
|
+
/// Signs this client in as `grant` (`handleWebSession`).
|
|
140
|
+
func commit(_ grant: SessionGrant, firstFactor: FirstFactor) async throws
|
|
141
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// Creating an Oxy account, as `OxySignUpPanel` keeps it, for every backend:
|
|
2
|
+
//
|
|
3
|
+
// username → date of birth → email → the code sent to it → signed in
|
|
4
|
+
//
|
|
5
|
+
// The username is held to the policy here first, and checked live against the server's
|
|
6
|
+
// ten-lookups-a-minute budget (`UsernameLookupBudget`), which the submit shares. The date of birth
|
|
7
|
+
// sets the account's age band (ADR 0067): below 13 the account is created under supervision, and
|
|
8
|
+
// the step says so. The email is confirmed before the account exists; a taken address gets a
|
|
9
|
+
// notice by mail, never an answer here (ADR 0030 D2). A password and an authenticator are added
|
|
10
|
+
// later, in the account's security settings.
|
|
11
|
+
|
|
12
|
+
/// From this age an account needs no guardian (`MINIMUM_UNSUPERVISED_AGE_YEARS`).
|
|
13
|
+
public let MINIMUM_UNSUPERVISED_AGE_YEARS = 13
|
|
14
|
+
/// The earliest year a date of birth may be in (`MIN_BIRTH_YEAR`).
|
|
15
|
+
public let MIN_BIRTH_YEAR = 1900
|
|
16
|
+
|
|
17
|
+
/// Whole years from a `YYYY-MM-DD` date of birth to `today` (`YYYY-MM-DD`), both in UTC
|
|
18
|
+
/// (`ageInYears`). A 29 February birthday counts on 1 March in a year without one.
|
|
19
|
+
public func ageInYears(_ dateOfBirth: String, today: String) -> Int {
|
|
20
|
+
let birth = dateOfBirth.components(separatedBy: "-").map { Int($0) ?? 0 }
|
|
21
|
+
let now = today.components(separatedBy: "-").map { Int($0) ?? 0 }
|
|
22
|
+
if birth.count != 3 || now.count != 3 { return 0 }
|
|
23
|
+
var age = now[0] - birth[0]
|
|
24
|
+
if birth[1] > now[1] || (birth[1] == now[1] && birth[2] > now[2]) { age -= 1 }
|
|
25
|
+
return age
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// A step of the sign-up.
|
|
29
|
+
public enum SignUpStage: Equatable {
|
|
30
|
+
case username
|
|
31
|
+
case birthdate
|
|
32
|
+
case email
|
|
33
|
+
case code(verificationId: String)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// What the live check knows about the username as typed.
|
|
37
|
+
public enum UsernameAvailability: Equatable {
|
|
38
|
+
case unknown
|
|
39
|
+
case available(String)
|
|
40
|
+
case taken(String)
|
|
41
|
+
/// The budget had no room for a background lookup; the submit will ask.
|
|
42
|
+
case deferred(String)
|
|
43
|
+
case refused(String, FlowMessage)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
@Observable
|
|
47
|
+
public final class SignUpFlow {
|
|
48
|
+
public private(set) var stage: SignUpStage = .username
|
|
49
|
+
public private(set) var username = ""
|
|
50
|
+
/// `YYYY-MM-DD`, or empty until picked.
|
|
51
|
+
public private(set) var dateOfBirth = ""
|
|
52
|
+
public private(set) var email = ""
|
|
53
|
+
public private(set) var code = ""
|
|
54
|
+
public private(set) var pending = false
|
|
55
|
+
public private(set) var error: FlowMessage? = none
|
|
56
|
+
/// "We sent you a new code".
|
|
57
|
+
public private(set) var noticeKey: String? = none
|
|
58
|
+
public private(set) var availability: UsernameAvailability = .unknown
|
|
59
|
+
public private(set) var signedIn = false
|
|
60
|
+
|
|
61
|
+
let service: SignInService
|
|
62
|
+
let budget: UsernameLookupBudget
|
|
63
|
+
/// Today, `YYYY-MM-DD` in UTC.
|
|
64
|
+
let today: () -> String
|
|
65
|
+
let languages: [String]
|
|
66
|
+
|
|
67
|
+
public init(service: SignInService, budget: UsernameLookupBudget, today: () -> String, languages: [String]) {
|
|
68
|
+
self.service = service
|
|
69
|
+
self.budget = budget
|
|
70
|
+
self.today = today
|
|
71
|
+
self.languages = languages
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// The username as typed, trimmed: what the live check and the submit are about.
|
|
75
|
+
var candidate: String { username.trimmed() }
|
|
76
|
+
|
|
77
|
+
/// "That username is taken", from the live check, while nothing else is wrong.
|
|
78
|
+
public var liveTaken: Bool {
|
|
79
|
+
if error != none { return false }
|
|
80
|
+
if case .taken(let name) = availability { return name == candidate }
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// "Available", from the live check, while nothing else is wrong.
|
|
85
|
+
public var showsAvailable: Bool {
|
|
86
|
+
if error != none || candidate.isEmpty { return false }
|
|
87
|
+
if case .available(let name) = availability { return name == candidate }
|
|
88
|
+
return false
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// The date puts the account below the minimum unsupervised age: the guardian note shows.
|
|
92
|
+
public var needsGuardian: Bool {
|
|
93
|
+
!dateOfBirth.isEmpty && ageInYears(dateOfBirth, today: today()) < MINIMUM_UNSUPERVISED_AGE_YEARS
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// MARK: typing
|
|
97
|
+
|
|
98
|
+
/// Only the characters the policy allows reach the field (`stripDisallowedUsernameCharacters`).
|
|
99
|
+
public func setUsername(_ value: String) {
|
|
100
|
+
var kept = ""
|
|
101
|
+
for ch in value {
|
|
102
|
+
let c = String(ch)
|
|
103
|
+
if ALNUM.contains(c) || c == "-" || c == "_" { kept += c }
|
|
104
|
+
}
|
|
105
|
+
username = kept
|
|
106
|
+
error = none
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
public func setDateOfBirth(_ value: String) {
|
|
110
|
+
dateOfBirth = value
|
|
111
|
+
error = none
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
public func setEmail(_ value: String) {
|
|
115
|
+
email = withoutWhitespace(value)
|
|
116
|
+
error = none
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
public func setCode(_ value: String) {
|
|
120
|
+
code = value
|
|
121
|
+
error = none
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// MARK: the live check
|
|
125
|
+
|
|
126
|
+
/// Ask whether the username as typed is free, once the typing has settled (the screen calls it
|
|
127
|
+
/// after its debounce). Never takes the budget's last lookup: that one is the submit's.
|
|
128
|
+
public func checkAvailability() async {
|
|
129
|
+
let name = candidate
|
|
130
|
+
guard case .ok(_) = checkUsernameDraft(name) else {
|
|
131
|
+
availability = .unknown
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
do {
|
|
135
|
+
let answer = try await budget.lookup(name, background: true) { n in
|
|
136
|
+
try await self.service.usernameAvailable(n)
|
|
137
|
+
}
|
|
138
|
+
if name != candidate { return }
|
|
139
|
+
if let free = answer {
|
|
140
|
+
availability = free ? .available(name) : .taken(name)
|
|
141
|
+
} else {
|
|
142
|
+
availability = .deferred(name)
|
|
143
|
+
}
|
|
144
|
+
} catch {
|
|
145
|
+
if name != candidate { return }
|
|
146
|
+
let failure = asFailure(error)
|
|
147
|
+
if let refused = describeUsernameRefusal(failure, name) {
|
|
148
|
+
availability = .refused(name, refused)
|
|
149
|
+
} else {
|
|
150
|
+
availability = .unknown
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// MARK: steps
|
|
156
|
+
|
|
157
|
+
public func submitUsername() async {
|
|
158
|
+
if pending { return }
|
|
159
|
+
switch checkUsernameDraft(username) {
|
|
160
|
+
case .invalid(let rule):
|
|
161
|
+
error = rule
|
|
162
|
+
return
|
|
163
|
+
case .ok(let handle):
|
|
164
|
+
username = handle
|
|
165
|
+
if case .taken(let name) = availability {
|
|
166
|
+
if name == handle {
|
|
167
|
+
error = message("signup.username.taken")
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
error = none
|
|
172
|
+
pending = true
|
|
173
|
+
do {
|
|
174
|
+
let answer = try await budget.lookup(handle, background: false) { n in
|
|
175
|
+
try await self.service.usernameAvailable(n)
|
|
176
|
+
}
|
|
177
|
+
if let free = answer {
|
|
178
|
+
if free {
|
|
179
|
+
stage = .birthdate
|
|
180
|
+
} else {
|
|
181
|
+
error = message("signup.username.taken")
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
error = FlowMessage(key: "signin.errors.rateLimited", args: ["seconds": "\(budget.cooldownSeconds())"])
|
|
185
|
+
}
|
|
186
|
+
} catch {
|
|
187
|
+
failUsername(error)
|
|
188
|
+
}
|
|
189
|
+
pending = false
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
public func submitBirthdate() {
|
|
194
|
+
if dateOfBirth.isEmpty {
|
|
195
|
+
error = message("signup.birthdate.required")
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
error = none
|
|
199
|
+
stage = .email
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public func submitEmail() async {
|
|
203
|
+
if pending { return }
|
|
204
|
+
guard let address = checkEmailAddress(email) else {
|
|
205
|
+
error = message("signup.email.invalid")
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
email = address
|
|
209
|
+
error = none
|
|
210
|
+
pending = true
|
|
211
|
+
do {
|
|
212
|
+
let verificationId = try await service.startSignupVerification(email: address)
|
|
213
|
+
code = ""
|
|
214
|
+
noticeKey = none
|
|
215
|
+
stage = .code(verificationId: verificationId)
|
|
216
|
+
} catch {
|
|
217
|
+
failUsername(error)
|
|
218
|
+
}
|
|
219
|
+
pending = false
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// "Send a new code".
|
|
223
|
+
public func resendCode() async {
|
|
224
|
+
guard case .code(_) = stage else { return }
|
|
225
|
+
error = none
|
|
226
|
+
noticeKey = none
|
|
227
|
+
code = ""
|
|
228
|
+
do {
|
|
229
|
+
let verificationId = try await service.startSignupVerification(email: email)
|
|
230
|
+
stage = .code(verificationId: verificationId)
|
|
231
|
+
noticeKey = "emailCode.resent"
|
|
232
|
+
} catch {
|
|
233
|
+
self.error = message(describeFailure(asFailure(error)))
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/// Continue on the code, or its field filled: confirm it, then create the account.
|
|
238
|
+
public func submitCode() async {
|
|
239
|
+
guard case .code(let verificationId) = stage else { return }
|
|
240
|
+
if pending { return }
|
|
241
|
+
var digits = ""
|
|
242
|
+
for ch in code {
|
|
243
|
+
if ch.isNumber { digits += String(ch) }
|
|
244
|
+
}
|
|
245
|
+
if digits.count != EMAIL_CODE_LENGTH {
|
|
246
|
+
error = message("emailCode.errors.codeInvalid")
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
error = none
|
|
250
|
+
pending = true
|
|
251
|
+
do {
|
|
252
|
+
let ticket = try await service.confirmVerification(verificationId, code: digits)
|
|
253
|
+
await createAccount(ticket)
|
|
254
|
+
} catch {
|
|
255
|
+
self.error = message(describeFailure(asFailure(error)))
|
|
256
|
+
}
|
|
257
|
+
pending = false
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
func createAccount(_ ticket: String) async {
|
|
261
|
+
// A flow restored from before a check existed may carry any name, or no date.
|
|
262
|
+
guard case .ok(let handle) = checkUsernameDraft(username) else {
|
|
263
|
+
if case .invalid(let rule) = checkUsernameDraft(username) { error = rule }
|
|
264
|
+
stage = .username
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
if dateOfBirth.isEmpty {
|
|
268
|
+
stage = .birthdate
|
|
269
|
+
error = message("signup.birthdate.required")
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
do {
|
|
273
|
+
let step = try await service.signUp(SignUpRequest(username: handle, email: email, emailTicket: ticket, dateOfBirth: dateOfBirth, languages: languages))
|
|
274
|
+
if case .session(let grant) = step {
|
|
275
|
+
try await service.commit(grant, firstFactor: .signup)
|
|
276
|
+
signedIn = true
|
|
277
|
+
} else {
|
|
278
|
+
error = message("signin.errors.generic")
|
|
279
|
+
}
|
|
280
|
+
} catch {
|
|
281
|
+
let failure = asFailure(error)
|
|
282
|
+
if failure.code == SignInCode.usernameTaken {
|
|
283
|
+
stage = .username
|
|
284
|
+
self.error = message("signup.username.taken")
|
|
285
|
+
} else if let refused = describeUsernameRefusal(failure, handle) {
|
|
286
|
+
// The server refused the name by a rule this client does not know yet.
|
|
287
|
+
stage = .username
|
|
288
|
+
self.error = refused
|
|
289
|
+
} else if isTicketExpired(failure) {
|
|
290
|
+
stage = .email
|
|
291
|
+
self.error = message(describeFailure(failure))
|
|
292
|
+
} else {
|
|
293
|
+
self.error = message(describeFailure(failure))
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/// Back one step ("Back", "Change email").
|
|
299
|
+
public func back() {
|
|
300
|
+
error = none
|
|
301
|
+
switch stage {
|
|
302
|
+
case .birthdate:
|
|
303
|
+
stage = .username
|
|
304
|
+
case .email:
|
|
305
|
+
stage = .birthdate
|
|
306
|
+
case .code(_):
|
|
307
|
+
stage = .email
|
|
308
|
+
case .username:
|
|
309
|
+
break
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
func failUsername(_ reason: Error) {
|
|
314
|
+
let failure = asFailure(reason)
|
|
315
|
+
if isTicketExpired(failure) { stage = .email }
|
|
316
|
+
if let refused = describeUsernameRefusal(failure, username) {
|
|
317
|
+
error = refused
|
|
318
|
+
} else {
|
|
319
|
+
error = message(describeFailure(failure))
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// The username and email rules a sign-up checks before asking the server, from
|
|
2
|
+
// `@oxy.so/contracts/client` (`username.ts`, `accountEmail.ts`, `check.ts`), in the person's
|
|
3
|
+
// words (`usernamePolicy.ts`). Reserved names are the server's call: it answers them with a 400
|
|
4
|
+
// whose message is the policy's, matched here to name the rule.
|
|
5
|
+
|
|
6
|
+
public let USERNAME_MIN_LENGTH = 3
|
|
7
|
+
public let USERNAME_MAX_LENGTH = 30
|
|
8
|
+
public let USERNAME_INVALID_MESSAGE = "Username must be 3-30 characters, use only letters, numbers, hyphens and underscores, start and end with a letter or number, and never repeat a separator"
|
|
9
|
+
public let RESERVED_USERNAME_MESSAGE = "This username is reserved and cannot be registered"
|
|
10
|
+
public let NUMERIC_USERNAME_MESSAGE = "Username cannot be only numbers"
|
|
11
|
+
public let BOT_USERNAME_INVALID_MESSAGE = "A bot account's username must end in \"bot\""
|
|
12
|
+
public let EMAIL_ADDRESS_MAX_LENGTH = 254
|
|
13
|
+
|
|
14
|
+
/// A message for the person: a catalog key and its `{name}`s.
|
|
15
|
+
public struct FlowMessage: Equatable {
|
|
16
|
+
public let key: String
|
|
17
|
+
public let args: [String: String]
|
|
18
|
+
|
|
19
|
+
public init(key: String, args: [String: String]) {
|
|
20
|
+
self.key = key
|
|
21
|
+
self.args = args
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// A message with no `{name}`s.
|
|
26
|
+
public func message(_ key: String) -> FlowMessage {
|
|
27
|
+
FlowMessage(key: key, args: [:])
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// A typed username held to the policy's shape.
|
|
31
|
+
public enum UsernameDraft: Equatable {
|
|
32
|
+
/// The trimmed handle to send.
|
|
33
|
+
case ok(String)
|
|
34
|
+
/// Which rule it broke.
|
|
35
|
+
case invalid(FlowMessage)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
39
|
+
|
|
40
|
+
/// `^[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*$`: alphanumeric runs joined by single separators.
|
|
41
|
+
func matchesUsernamePattern(_ name: String) -> Bool {
|
|
42
|
+
if name.isEmpty { return false }
|
|
43
|
+
var afterSeparator = true
|
|
44
|
+
for ch in name {
|
|
45
|
+
let c = String(ch)
|
|
46
|
+
if ALNUM.contains(c) {
|
|
47
|
+
afterSeparator = false
|
|
48
|
+
} else if c == "-" || c == "_" {
|
|
49
|
+
if afterSeparator { return false }
|
|
50
|
+
afterSeparator = true
|
|
51
|
+
} else {
|
|
52
|
+
return false
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return !afterSeparator
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// `checkUsernameDraft`: the policy's shape, with the rule named.
|
|
59
|
+
public func checkUsernameDraft(_ value: String) -> UsernameDraft {
|
|
60
|
+
let username = value.trimmed()
|
|
61
|
+
if username.isEmpty { return .invalid(message("usernamePolicy.required")) }
|
|
62
|
+
if username.count < USERNAME_MIN_LENGTH || username.count > USERNAME_MAX_LENGTH || !matchesUsernamePattern(username) {
|
|
63
|
+
return .invalid(describeUsernameIssue(username, USERNAME_INVALID_MESSAGE))
|
|
64
|
+
}
|
|
65
|
+
if allDigits(username) { return .invalid(describeUsernameIssue(username, NUMERIC_USERNAME_MESSAGE)) }
|
|
66
|
+
return .ok(username)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// The server's refusal of `username` (a 400 naming the `username` field), in the same words;
|
|
70
|
+
/// `none` when the failure is something else.
|
|
71
|
+
public func describeUsernameRefusal(_ failure: SignInFailure, _ username: String) -> FlowMessage? {
|
|
72
|
+
if failure.code != SignInCode.badRequest || failure.field != "username" { return none }
|
|
73
|
+
return describeUsernameIssue(username.trimmed(), failure.detail ?? "")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func describeUsernameIssue(_ username: String, _ detail: String) -> FlowMessage {
|
|
77
|
+
if detail == NUMERIC_USERNAME_MESSAGE { return message("usernamePolicy.onlyNumbers") }
|
|
78
|
+
if detail == RESERVED_USERNAME_MESSAGE { return message("usernamePolicy.reserved") }
|
|
79
|
+
if detail == BOT_USERNAME_INVALID_MESSAGE { return message("usernamePolicy.mustEndInBot") }
|
|
80
|
+
if detail == USERNAME_INVALID_MESSAGE {
|
|
81
|
+
// One message covers length and shape alike; the length names the rule that failed.
|
|
82
|
+
if username.count < USERNAME_MIN_LENGTH {
|
|
83
|
+
return FlowMessage(key: "usernamePolicy.tooShort", args: ["min": "\(USERNAME_MIN_LENGTH)"])
|
|
84
|
+
}
|
|
85
|
+
if username.count > USERNAME_MAX_LENGTH {
|
|
86
|
+
return FlowMessage(key: "usernamePolicy.tooLong", args: ["max": "\(USERNAME_MAX_LENGTH)"])
|
|
87
|
+
}
|
|
88
|
+
if withoutWhitespace(username) != username { return message("usernamePolicy.noSpaces") }
|
|
89
|
+
return message("usernamePolicy.characters")
|
|
90
|
+
}
|
|
91
|
+
return message("signin.errors.invalidInput")
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let EMAIL_LOCAL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'+-."
|
|
95
|
+
let EMAIL_LOCAL_LAST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-"
|
|
96
|
+
let LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
97
|
+
|
|
98
|
+
/// The contract's `EMAIL` pattern, without a regular expression:
|
|
99
|
+
/// `^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$`, any case.
|
|
100
|
+
func matchesEmailPattern(_ address: String) -> Bool {
|
|
101
|
+
if address.hasPrefix(".") || address.contains("..") { return false }
|
|
102
|
+
let parts = address.components(separatedBy: "@")
|
|
103
|
+
if parts.count != 2 { return false }
|
|
104
|
+
let local = parts[0]
|
|
105
|
+
let domain = parts[1]
|
|
106
|
+
if local.isEmpty { return false }
|
|
107
|
+
for ch in local {
|
|
108
|
+
if !EMAIL_LOCAL.contains(String(ch)) { return false }
|
|
109
|
+
}
|
|
110
|
+
guard let last = local.last else { return false }
|
|
111
|
+
if !EMAIL_LOCAL_LAST.contains(String(last)) { return false }
|
|
112
|
+
let labels = domain.components(separatedBy: ".")
|
|
113
|
+
if labels.count < 2 { return false }
|
|
114
|
+
let tld = labels[labels.count - 1]
|
|
115
|
+
if tld.count < 2 { return false }
|
|
116
|
+
for ch in tld {
|
|
117
|
+
if !LETTERS.contains(String(ch)) { return false }
|
|
118
|
+
}
|
|
119
|
+
for label in labels.dropLast() {
|
|
120
|
+
guard let first = label.first else { return false }
|
|
121
|
+
if !ALNUM.contains(String(first)) { return false }
|
|
122
|
+
for ch in label {
|
|
123
|
+
let c = String(ch)
|
|
124
|
+
if !ALNUM.contains(c) && c != "-" { return false }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return true
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// `emailAddressCheck`: trimmed, lower-cased, 3 to 254 characters, an address; `none` otherwise.
|
|
131
|
+
public func checkEmailAddress(_ value: String) -> String? {
|
|
132
|
+
let address = value.trimmed().lowercased()
|
|
133
|
+
if address.count < 3 || address.count > EMAIL_ADDRESS_MAX_LENGTH { return none }
|
|
134
|
+
return matchesEmailPattern(address) ? address : none
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// The ten username lookups a minute the server allows (`usernameLookupBudget.ts`): the live
|
|
138
|
+
/// preview and the submit share them, the preview never takes the last one, and one answer is
|
|
139
|
+
/// reused for the same handle within the minute.
|
|
140
|
+
public final class UsernameLookupBudget {
|
|
141
|
+
public static let limit = 10
|
|
142
|
+
public static let windowMs = 60000.0
|
|
143
|
+
var sentAt: [Double] = []
|
|
144
|
+
var settled: [String: Bool] = [:]
|
|
145
|
+
var settledAt: [String: Double] = [:]
|
|
146
|
+
let clock: () -> Double
|
|
147
|
+
|
|
148
|
+
public init(clock: () -> Double) {
|
|
149
|
+
self.clock = clock
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
func prune(_ now: Double) {
|
|
153
|
+
let cutoff = now - UsernameLookupBudget.windowMs
|
|
154
|
+
sentAt = sentAt.filter { $0 > cutoff }
|
|
155
|
+
var keep: [String: Double] = [:]
|
|
156
|
+
for (key, at) in settledAt {
|
|
157
|
+
if at > cutoff { keep[key] = at }
|
|
158
|
+
}
|
|
159
|
+
settledAt = keep
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/// Seconds until a lookup may be sent again; 0 when one may.
|
|
163
|
+
public func cooldownSeconds() -> Int {
|
|
164
|
+
let now = clock()
|
|
165
|
+
prune(now)
|
|
166
|
+
if sentAt.count < UsernameLookupBudget.limit { return 0 }
|
|
167
|
+
guard let oldest = sentAt.first else { return 0 }
|
|
168
|
+
let left = Int(((oldest + UsernameLookupBudget.windowMs - now) / 1000.0).ceil())
|
|
169
|
+
return left < 1 ? 1 : left
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/// Whether `username` is free, from a fresh answer or a lookup; `none` when the budget has no
|
|
173
|
+
/// room for it (`deferred`).
|
|
174
|
+
public func lookup(_ username: String, background: Bool, check: (String) async throws -> Bool) async throws -> Bool? {
|
|
175
|
+
let key = username.trimmed().lowercased()
|
|
176
|
+
let now = clock()
|
|
177
|
+
prune(now)
|
|
178
|
+
if settledAt[key] != none {
|
|
179
|
+
if let known = settled[key] { return known }
|
|
180
|
+
}
|
|
181
|
+
let room = background ? UsernameLookupBudget.limit - 1 : UsernameLookupBudget.limit
|
|
182
|
+
if sentAt.count >= room { return none }
|
|
183
|
+
sentAt.append(now)
|
|
184
|
+
let available = try await check(username)
|
|
185
|
+
settled[key] = available
|
|
186
|
+
settledAt[key] = clock()
|
|
187
|
+
return available
|
|
188
|
+
}
|
|
189
|
+
}
|