@circle-fin/daa-react-native-sdk 0.4.0 → 0.5.0
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/DaaReactNativeSdk.podspec +14 -8
- package/README.md +498 -24
- package/android/build.gradle +12 -7
- package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +1 -18
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +38 -4
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +139 -6
- package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +50 -1
- package/build/DaaClient.d.ts +183 -3
- package/build/DaaClient.js +296 -12
- package/build/api/AccountsClient.d.ts +3 -0
- package/build/api/AccountsClient.js +3 -0
- package/build/api/AuthClient.d.ts +17 -42
- package/build/api/AuthClient.js +26 -62
- package/build/api/ContractExecutionsClient.d.ts +114 -0
- package/build/api/ContractExecutionsClient.js +462 -0
- package/build/api/DaaUserClient.d.ts +74 -11
- package/build/api/DaaUserClient.js +84 -17
- package/build/api/TransactionsClient.d.ts +1 -1
- package/build/api/TransactionsClient.js +1 -0
- package/build/api/TransfersClient.d.ts +3 -0
- package/build/api/TransfersClient.js +3 -0
- package/build/api/WithdrawalsClient.d.ts +3 -0
- package/build/api/WithdrawalsClient.js +3 -0
- package/build/api/deviceApproval.d.ts +48 -0
- package/build/api/deviceApproval.js +247 -0
- package/build/api/deviceStatus.d.ts +61 -0
- package/build/api/deviceStatus.js +216 -0
- package/build/api/loginFailure.d.ts +10 -2
- package/build/api/loginFailure.js +33 -2
- package/build/api/signedResource.d.ts +49 -2
- package/build/api/signedResource.js +135 -36
- package/build/auth/RegistrationFlowKey.js +1 -1
- package/build/auth/daaRegistrationNative.d.ts +0 -22
- package/build/auth/daaRegistrationNative.js +3 -29
- package/build/auth/deviceAuthorization.d.ts +17 -3
- package/build/auth/deviceAuthorization.js +60 -8
- package/build/auth/registrationAuthorization.d.ts +2 -2
- package/build/auth/registrationAuthorization.js +13 -10
- package/build/config.d.ts +27 -0
- package/build/config.js +15 -0
- package/build/crypto/matchingCode.d.ts +47 -0
- package/build/crypto/matchingCode.js +93 -0
- package/build/errors.d.ts +150 -33
- package/build/errors.js +208 -47
- package/build/index.d.ts +11 -3
- package/build/models/ContractExecution.d.ts +197 -0
- package/build/models/ContractExecution.js +130 -0
- package/build/models/CreateContractExecutionRequest.d.ts +81 -0
- package/build/models/CreateContractExecutionRequest.js +19 -0
- package/build/models/DaaUserContext.d.ts +53 -3
- package/build/models/DaaUserContext.js +33 -2
- package/build/models/DeviceStatus.d.ts +69 -0
- package/build/models/DeviceStatus.js +19 -0
- package/build/models/PendingDeviceApproval.d.ts +121 -0
- package/build/models/PendingDeviceApproval.js +208 -0
- package/build/models/PendingDeviceRegistration.d.ts +162 -23
- package/build/models/PendingDeviceRegistration.js +525 -69
- package/build/models/PreparedContractExecution.d.ts +70 -0
- package/build/models/PreparedContractExecution.js +77 -0
- package/build/models/PreparedSocialLogin.d.ts +19 -26
- package/build/models/PreparedSocialLogin.js +32 -15
- package/build/models/Transaction.d.ts +48 -2
- package/build/models/Transaction.js +52 -4
- package/build/models/codeSecrets.d.ts +100 -0
- package/build/models/codeSecrets.js +321 -0
- package/build/securekey/InMemorySecureKey.d.ts +3 -1
- package/build/securekey/InMemorySecureKey.js +47 -6
- package/build/securekey/NativeSecureKey.d.ts +3 -1
- package/build/securekey/NativeSecureKey.js +204 -27
- package/build/securekey/NativeSecureKeyBridge.d.ts +72 -4
- package/build/securekey/SecureKey.d.ts +128 -8
- package/build/securekey/alias.d.ts +9 -0
- package/build/securekey/alias.js +11 -2
- package/build/securekey/ownerAuthKeyResolver.d.ts +26 -9
- package/build/securekey/ownerAuthKeyResolver.js +35 -20
- package/build/securekey/registration.d.ts +19 -0
- package/build/securekey/registration.js +38 -0
- package/build/securekey/resolveNativeBridge.d.ts +3 -0
- package/build/securekey/resolveNativeBridge.js +88 -7
- package/build/transport/headers.d.ts +11 -0
- package/build/transport/headers.js +36 -0
- package/build/wire/contractExecutionPayload.d.ts +24 -0
- package/build/wire/contractExecutionPayload.js +130 -0
- package/build/wire/daaStatusCodes.d.ts +20 -3
- package/build/wire/daaStatusCodes.js +20 -3
- package/build/wire/deviceContextPayload.d.ts +9 -7
- package/build/wire/deviceContextPayload.js +9 -7
- package/build/wire/deviceRegistrationResultPayload.d.ts +55 -10
- package/build/wire/deviceRegistrationResultPayload.js +116 -82
- package/build/wire/deviceStatusPayload.d.ts +20 -0
- package/build/wire/deviceStatusPayload.js +66 -0
- package/build/wire/instant.js +4 -1
- package/build/wire/pendingRegistrationPayload.d.ts +16 -0
- package/build/wire/pendingRegistrationPayload.js +18 -0
- package/build/wire/socialLoginRequestPayload.d.ts +0 -5
- package/build/wire/socialLoginRequestPayload.js +2 -19
- package/build/wire/transactionPayload.d.ts +2 -2
- package/build/wire/transactionPayload.js +27 -4
- package/ios/DaaRegistrationModule.swift +1 -19
- package/ios/DaaSecureKeyExceptions.swift +53 -5
- package/ios/DaaSecureKeyModule.swift +149 -5
- package/ios/InstallationIdentityStore.swift +43 -7
- package/package.json +1 -1
- package/src/DaaClient.ts +353 -15
- package/src/api/AccountsClient.ts +3 -0
- package/src/api/AuthClient.ts +33 -98
- package/src/api/ContractExecutionsClient.ts +527 -0
- package/src/api/DaaUserClient.ts +92 -17
- package/src/api/TransactionsClient.ts +1 -0
- package/src/api/TransfersClient.ts +3 -0
- package/src/api/WithdrawalsClient.ts +3 -0
- package/src/api/deviceApproval.ts +306 -0
- package/src/api/deviceStatus.ts +238 -0
- package/src/api/loginFailure.ts +39 -2
- package/src/api/signedResource.ts +206 -46
- package/src/auth/RegistrationFlowKey.ts +1 -1
- package/src/auth/daaRegistrationNative.ts +4 -49
- package/src/auth/deviceAuthorization.ts +74 -11
- package/src/auth/registrationAuthorization.ts +12 -9
- package/src/config.ts +36 -0
- package/src/crypto/matchingCode.ts +100 -0
- package/src/errors.ts +309 -52
- package/src/index.ts +36 -1
- package/src/models/ContractExecution.ts +250 -0
- package/src/models/CreateContractExecutionRequest.ts +100 -0
- package/src/models/DaaUserContext.ts +59 -3
- package/src/models/DeviceStatus.ts +50 -0
- package/src/models/PendingDeviceApproval.ts +229 -0
- package/src/models/PendingDeviceRegistration.ts +673 -79
- package/src/models/PreparedContractExecution.ts +128 -0
- package/src/models/PreparedSocialLogin.ts +41 -31
- package/src/models/Transaction.ts +77 -2
- package/src/models/codeSecrets.ts +360 -0
- package/src/securekey/InMemorySecureKey.ts +61 -7
- package/src/securekey/NativeSecureKey.ts +234 -25
- package/src/securekey/NativeSecureKeyBridge.ts +84 -4
- package/src/securekey/SecureKey.ts +138 -8
- package/src/securekey/alias.ts +11 -3
- package/src/securekey/ownerAuthKeyResolver.ts +63 -24
- package/src/securekey/registration.ts +40 -0
- package/src/securekey/resolveNativeBridge.ts +167 -9
- package/src/transport/headers.ts +47 -0
- package/src/wire/contractExecutionPayload.ts +152 -0
- package/src/wire/daaStatusCodes.ts +20 -3
- package/src/wire/deviceContextPayload.ts +9 -7
- package/src/wire/deviceRegistrationResultPayload.ts +156 -98
- package/src/wire/deviceStatusPayload.ts +68 -0
- package/src/wire/instant.ts +4 -1
- package/src/wire/pendingRegistrationPayload.ts +44 -1
- package/src/wire/socialLoginRequestPayload.ts +2 -25
- package/src/wire/transactionPayload.ts +40 -4
- package/build/auth/prepareReceipt.d.ts +0 -150
- package/build/auth/prepareReceipt.js +0 -357
- package/build/crypto/es256Jws.d.ts +0 -56
- package/build/crypto/es256Jws.js +0 -196
- package/src/auth/prepareReceipt.ts +0 -522
- package/src/crypto/es256Jws.ts +0 -240
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { contractViolation, isDaaError } from '../errors'
|
|
20
|
+
import type { DeviceStatus } from '../models/DeviceStatus'
|
|
21
|
+
import type { DaaTransport } from '../transport/DaaTransport'
|
|
22
|
+
import { isUuid } from '../validation/uuid'
|
|
23
|
+
import { toDeviceStatus } from '../wire/deviceStatusPayload'
|
|
24
|
+
import { readResource } from './resourceRequest'
|
|
25
|
+
|
|
26
|
+
/** The add-a-device routes of one AuthKey: this prefix, then its `authKeyId`. */
|
|
27
|
+
export const DEVICE_PATH_PREFIX = '/v1/accounts/auth/devices/'
|
|
28
|
+
|
|
29
|
+
/** How often `watchDeviceStatus` reads the status while nothing fails. */
|
|
30
|
+
export const POLL_INTERVAL_MS = 5_000
|
|
31
|
+
/** The longest wait between reads after errors, and during a cool-down. */
|
|
32
|
+
export const MAX_POLL_INTERVAL_MS = 30_000
|
|
33
|
+
/** Retryable failures in a row after which `watchDeviceStatus` gives up. */
|
|
34
|
+
export const MAX_CONSECUTIVE_ERRORS = 10
|
|
35
|
+
|
|
36
|
+
/** The statuses in which the request can still change; any other ends a watch. */
|
|
37
|
+
const WAITING_STATUSES: ReadonlySet<DeviceStatus['status']> = new Set([
|
|
38
|
+
'pending_approval',
|
|
39
|
+
'pending_activation',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `GET /v1/accounts/auth/devices/{authKeyId}`. A transport throw must already
|
|
44
|
+
* be a `transport` DaaError (the caller wraps the transport).
|
|
45
|
+
*
|
|
46
|
+
* `authKeyId` may come in either case (Swift's `uuidString` is uppercase); it
|
|
47
|
+
* is lowercased before it goes into the path and before the response's
|
|
48
|
+
* `authKeyId`, which DAA writes lowercase, is compared with it.
|
|
49
|
+
*/
|
|
50
|
+
export async function readDeviceStatus(
|
|
51
|
+
transport: DaaTransport,
|
|
52
|
+
authKeyId: string,
|
|
53
|
+
): Promise<DeviceStatus> {
|
|
54
|
+
if (!isUuid(authKeyId)) {
|
|
55
|
+
throw contractViolation('authKeyId must be a UUID')
|
|
56
|
+
}
|
|
57
|
+
const id = authKeyId.toLowerCase()
|
|
58
|
+
const status = await readResource({
|
|
59
|
+
transport,
|
|
60
|
+
path: DEVICE_PATH_PREFIX + id,
|
|
61
|
+
decode: toDeviceStatus,
|
|
62
|
+
})
|
|
63
|
+
if (status.authKeyId.toLowerCase() !== id) {
|
|
64
|
+
throw contractViolation('the device status names a different AuthKey')
|
|
65
|
+
}
|
|
66
|
+
return status
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Read the status until it is no longer `pending_approval` or
|
|
71
|
+
* `pending_activation`, and resolve with that status.
|
|
72
|
+
*
|
|
73
|
+
* Only DAA's answer ends the watch: DAA reports `expired` once `expiresAt`
|
|
74
|
+
* passes on its clock, so this device's clock, which may be wrong, never
|
|
75
|
+
* decides when the request is over. Reads every 5 s while `pending_approval`.
|
|
76
|
+
* During `pending_activation` it reads at `readyAt`, but at least every 30 s,
|
|
77
|
+
* since the cool-down can last hours. After a failure marked `retryable`
|
|
78
|
+
* (`transport`, or `api` with `429`/`5xx`) the wait doubles, up to 30 s, and after 10 in a
|
|
79
|
+
* row it rejects with the last one; any other failure rejects at once. Each
|
|
80
|
+
* wait after a failure is a random time between half of that and all of it, so
|
|
81
|
+
* watches that failed together (a gateway outage) don't all retry together.
|
|
82
|
+
*
|
|
83
|
+
* `onStatus` is called with the first status and with every change; if it
|
|
84
|
+
* throws, the watch rejects with that error. Aborting `signal` stops the watch
|
|
85
|
+
* at once, also during a read, and rejects with the signal's `reason` (an
|
|
86
|
+
* `Error` when the runtime's `AbortSignal` has none); a read that answers
|
|
87
|
+
* after the abort is ignored, and `onStatus` is not called for it.
|
|
88
|
+
*/
|
|
89
|
+
export async function watchDeviceStatus(
|
|
90
|
+
transport: DaaTransport,
|
|
91
|
+
args: {
|
|
92
|
+
readonly authKeyId: string
|
|
93
|
+
readonly onStatus?: (status: DeviceStatus) => void
|
|
94
|
+
readonly signal?: AbortSignal
|
|
95
|
+
},
|
|
96
|
+
): Promise<DeviceStatus> {
|
|
97
|
+
const { authKeyId, onStatus, signal } = args
|
|
98
|
+
let last: DeviceStatus | null = null
|
|
99
|
+
let errors = 0
|
|
100
|
+
let errorWait = POLL_INTERVAL_MS
|
|
101
|
+
for (;;) {
|
|
102
|
+
let status: DeviceStatus
|
|
103
|
+
try {
|
|
104
|
+
status = await untilAborted(() => readDeviceStatus(transport, authKeyId), signal)
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if (signal?.aborted === true) {
|
|
107
|
+
throw abortReason(signal)
|
|
108
|
+
}
|
|
109
|
+
errors += 1
|
|
110
|
+
if (!isRetryable(err) || errors >= MAX_CONSECUTIVE_ERRORS) {
|
|
111
|
+
throw err
|
|
112
|
+
}
|
|
113
|
+
errorWait = Math.min(errorWait * 2, MAX_POLL_INTERVAL_MS)
|
|
114
|
+
await sleep(jittered(errorWait), signal)
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
// The abort can land after the read settled but before this resumes; the
|
|
118
|
+
// app has cancelled by then, so it gets no status and no result.
|
|
119
|
+
if (signal?.aborted === true) {
|
|
120
|
+
throw abortReason(signal)
|
|
121
|
+
}
|
|
122
|
+
errors = 0
|
|
123
|
+
errorWait = POLL_INTERVAL_MS
|
|
124
|
+
if (last === null || !sameStatus(last, status)) {
|
|
125
|
+
onStatus?.(status)
|
|
126
|
+
}
|
|
127
|
+
last = status
|
|
128
|
+
if (!WAITING_STATUSES.has(status.status)) {
|
|
129
|
+
return status
|
|
130
|
+
}
|
|
131
|
+
await sleep(nextRead(status), signal)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A random time between half of `ms` and all of it. */
|
|
136
|
+
function jittered(ms: number): number {
|
|
137
|
+
return Math.round(ms / 2 + Math.random() * (ms / 2))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function nextRead(status: DeviceStatus): number {
|
|
141
|
+
if (status.status !== 'pending_activation') {
|
|
142
|
+
return POLL_INTERVAL_MS
|
|
143
|
+
}
|
|
144
|
+
const untilReady = Date.parse(status.readyAt) - Date.now()
|
|
145
|
+
// The decoder checks `readyAt`'s shape, not its calendar (`2026-13-24…`
|
|
146
|
+
// passes), and JS engines differ in what `Date.parse` accepts. A NaN would
|
|
147
|
+
// make the timer fire at once and the watch poll without pause; read every
|
|
148
|
+
// 30 s instead and let DAA's status end the cool-down.
|
|
149
|
+
if (!Number.isFinite(untilReady)) {
|
|
150
|
+
return MAX_POLL_INTERVAL_MS
|
|
151
|
+
}
|
|
152
|
+
return Math.min(Math.max(untilReady, POLL_INTERVAL_MS), MAX_POLL_INTERVAL_MS)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function sameStatus(a: DeviceStatus, b: DeviceStatus): boolean {
|
|
156
|
+
return JSON.stringify(a) === JSON.stringify(b)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// `retryable` decides for both kinds: a transport that throws its own
|
|
160
|
+
// `DaaError` with `retryable: false` has said a retry cannot help.
|
|
161
|
+
function isRetryable(err: unknown): boolean {
|
|
162
|
+
return (
|
|
163
|
+
isDaaError(err) &&
|
|
164
|
+
(err.detail.kind === 'transport' || err.detail.kind === 'api') &&
|
|
165
|
+
err.detail.retryable
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Only `aborted` and the abort event: older React Native `AbortSignal`
|
|
170
|
+
// polyfills have neither `throwIfAborted()` nor always a `reason`.
|
|
171
|
+
function abortReason(signal: AbortSignal): unknown {
|
|
172
|
+
return signal.reason ?? new Error('DAA: watchDeviceStatus was aborted')
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* `start()`, or a rejection as soon as `signal` aborts, whichever comes first.
|
|
177
|
+
* Nothing starts once `signal` has aborted, and a result that arrives after
|
|
178
|
+
* the abort is dropped; the caller checks `signal.aborted` to tell the two
|
|
179
|
+
* rejections apart. The abort listener is in place before `start()` runs, so
|
|
180
|
+
* an abort during `start()` itself (say, inside the transport's `send`) is
|
|
181
|
+
* not missed.
|
|
182
|
+
*/
|
|
183
|
+
function untilAborted<T>(start: () => Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
184
|
+
if (signal === undefined) {
|
|
185
|
+
return start()
|
|
186
|
+
}
|
|
187
|
+
if (signal.aborted) {
|
|
188
|
+
return Promise.reject(abortReason(signal))
|
|
189
|
+
}
|
|
190
|
+
return new Promise<T>((resolve, reject) => {
|
|
191
|
+
const onAbort = () => reject(abortReason(signal))
|
|
192
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
193
|
+
let promise: Promise<T>
|
|
194
|
+
try {
|
|
195
|
+
promise = start()
|
|
196
|
+
} catch (err: unknown) {
|
|
197
|
+
signal.removeEventListener('abort', onAbort)
|
|
198
|
+
reject(err)
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
promise.then(
|
|
202
|
+
(value) => {
|
|
203
|
+
signal.removeEventListener('abort', onAbort)
|
|
204
|
+
if (signal.aborted) {
|
|
205
|
+
reject(abortReason(signal))
|
|
206
|
+
} else {
|
|
207
|
+
resolve(value)
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
(err: unknown) => {
|
|
211
|
+
signal.removeEventListener('abort', onAbort)
|
|
212
|
+
reject(err)
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
if (signal === undefined) {
|
|
221
|
+
setTimeout(resolve, ms)
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
if (signal.aborted) {
|
|
225
|
+
reject(abortReason(signal))
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
const onAbort = () => {
|
|
229
|
+
clearTimeout(timer)
|
|
230
|
+
reject(abortReason(signal))
|
|
231
|
+
}
|
|
232
|
+
const timer = setTimeout(() => {
|
|
233
|
+
signal.removeEventListener('abort', onAbort)
|
|
234
|
+
resolve()
|
|
235
|
+
}, ms)
|
|
236
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
237
|
+
})
|
|
238
|
+
}
|
package/src/api/loginFailure.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import {
|
|
20
20
|
contractViolation,
|
|
21
|
+
deviceRegistrationFailure,
|
|
21
22
|
idempotencyConflict,
|
|
22
23
|
loginRequestExpired,
|
|
23
24
|
type DaaError,
|
|
@@ -43,8 +44,16 @@ import { readDaaStatusCode } from '../wire/errorEnvelope'
|
|
|
43
44
|
* - `LOGIN_REQUEST_CONSUMED` (`420039`) is `contract_violation`. An identical
|
|
44
45
|
* successful step converges and never returns it, so it means that a
|
|
45
46
|
* different request used the login request.
|
|
46
|
-
* -
|
|
47
|
-
*
|
|
47
|
+
* - The four add-a-device codes, which only Device Registration Complete
|
|
48
|
+
* sends: `DEVICE_REGISTRATION_LIMIT` (`420109`) is
|
|
49
|
+
* `device_registration_limit`, with `retryAfterSeconds` when `Retry-After` is
|
|
50
|
+
* a whole number of seconds; `DEVICE_DENIED` (`420111`) is `device_denied`;
|
|
51
|
+
* `DEVICE_APPROVAL_CONFLICT` (`420112`) is `device_approval_conflict`; and
|
|
52
|
+
* `DEVICE_APPROVAL_UNAVAILABLE` (`420113`) is `device_approval_unavailable`.
|
|
53
|
+
* See `deviceRegistrationFailure`.
|
|
54
|
+
* - DAA also returns `409` for `AUTH_KEY_BINDING_CONFLICT` (`420038`) and for
|
|
55
|
+
* `PASSKEY_OWNER_CREDENTIAL_KIND_MISMATCH` (`420080`), which classify as
|
|
56
|
+
* `api`, not retryable. A `409` without a code that this
|
|
48
57
|
* SDK classifies, or without a readable body, is `api` too. So no status
|
|
49
58
|
* alone produces `idempotency_conflict`.
|
|
50
59
|
*
|
|
@@ -71,5 +80,33 @@ export function loginStepFailure(
|
|
|
71
80
|
correlationId,
|
|
72
81
|
)
|
|
73
82
|
}
|
|
83
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_REGISTRATION_LIMIT')) {
|
|
84
|
+
return deviceRegistrationFailure(
|
|
85
|
+
'device_registration_limit',
|
|
86
|
+
correlationId,
|
|
87
|
+
retryAfterSeconds(response),
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_DENIED')) {
|
|
91
|
+
return deviceRegistrationFailure('device_denied', correlationId)
|
|
92
|
+
}
|
|
93
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_APPROVAL_CONFLICT')) {
|
|
94
|
+
return deviceRegistrationFailure('device_approval_conflict', correlationId)
|
|
95
|
+
}
|
|
96
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_APPROVAL_UNAVAILABLE')) {
|
|
97
|
+
return deviceRegistrationFailure('device_approval_unavailable', correlationId)
|
|
98
|
+
}
|
|
74
99
|
return null
|
|
75
100
|
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `Retry-After` as whole seconds, or `null` when it is absent or in any other
|
|
104
|
+
* form (an HTTP date, a fraction, a sign). DAA sends seconds.
|
|
105
|
+
*/
|
|
106
|
+
function retryAfterSeconds(response: DaaHttpResponse): number | null {
|
|
107
|
+
const value = headerValueIgnoringCase(response.headers, 'Retry-After')?.trim()
|
|
108
|
+
if (value === undefined || !/^\d{1,9}$/.test(value)) {
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
return Number(value)
|
|
112
|
+
}
|
|
@@ -22,11 +22,14 @@
|
|
|
22
22
|
// Signed v1 operations carry `query = null`. Failures are classified on the
|
|
23
23
|
// numeric DAA status code only, through `wire/daaStatusCodes.ts`.
|
|
24
24
|
// An invalid, missing, replayed, or mismatched authorization becomes
|
|
25
|
-
// `contract_violation
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
25
|
+
// `contract_violation` — the credential rejection a caller must handle on every
|
|
26
|
+
// signed request. The one exception is a `DEVICE_AUTHORIZATION_INVALID` whose
|
|
27
|
+
// own `iat`/`exp` fail DAA's 60-second freshness rule against the response's
|
|
28
|
+
// HTTP `Date`: that is `clock_skew` (see `isClockSkewed`). A `409` whose
|
|
29
|
+
// body carries `IDEMPOTENCY_KEY_REUSED` (`420034`) becomes
|
|
30
|
+
// `idempotency_conflict`, with the key recovered from the same request bytes
|
|
31
|
+
// that were signed and sent, not the (unsigned) response body; the caller
|
|
32
|
+
// reconciles the original operation rather than replacing the key.
|
|
30
33
|
//
|
|
31
34
|
// DAA has no code for an expired device authorization, a missing one, or a
|
|
32
35
|
// revoked credential: it reports them as `DEVICE_AUTHORIZATION_INVALID` or,
|
|
@@ -38,7 +41,12 @@
|
|
|
38
41
|
//
|
|
39
42
|
// `AccountsClient.create` (`create_account`),
|
|
40
43
|
// `TransfersClient.create` (`transfer`), and `WithdrawalsClient.create`
|
|
41
|
-
// (`withdrawal`) call `postSignedResource`. `
|
|
44
|
+
// (`withdrawal`) call `postSignedResource`. `ContractExecutionsClient`
|
|
45
|
+
// (`contract_execution`) splits the same POST in two —
|
|
46
|
+
// `authorizeSignedPost` once, then `postAuthorizedResource` for the first send
|
|
47
|
+
// and every retry — because DAA requires a replay to carry the originally
|
|
48
|
+
// accepted authorization, not a fresh one; see
|
|
49
|
+
// `models/PreparedContractExecution.ts`. `DaaUserClient.refreshContext`
|
|
42
50
|
// (`get_device_context`) calls `getSignedResource` — the device-authorization
|
|
43
51
|
// contract treats "signed context refresh" alongside protected writes, and
|
|
44
52
|
// `securekey/SecureKey.ts` lists it alongside them as one of the defined DAA
|
|
@@ -49,13 +57,21 @@ import {
|
|
|
49
57
|
DEVICE_AUTHORIZATION_HEADER,
|
|
50
58
|
deviceAuthorizationProfile,
|
|
51
59
|
idempotencyKeyFromExactBody,
|
|
60
|
+
jwsSegmentJson,
|
|
52
61
|
type DeviceAuthorizationOperation,
|
|
53
62
|
} from '../auth/deviceAuthorization'
|
|
54
|
-
import {
|
|
63
|
+
import {
|
|
64
|
+
apiFailure,
|
|
65
|
+
clockSkew,
|
|
66
|
+
contractViolation,
|
|
67
|
+
devicePending,
|
|
68
|
+
idempotencyConflict,
|
|
69
|
+
type DaaError,
|
|
70
|
+
} from '../errors'
|
|
55
71
|
import type { OwnerAuthKeyResolver } from '../securekey/ownerAuthKeyResolver'
|
|
56
|
-
import type { OwnerAuthKey } from '../securekey/SecureKey'
|
|
72
|
+
import type { DeviceApprovalCheck, OwnerAuthKey } from '../securekey/SecureKey'
|
|
57
73
|
import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
|
|
58
|
-
import { headerValueIgnoringCase } from '../transport/headers'
|
|
74
|
+
import { headerValueIgnoringCase, httpDateMillis } from '../transport/headers'
|
|
59
75
|
import { isDaaStatus } from '../wire/daaStatusCodes'
|
|
60
76
|
import { readDaaStatusCode } from '../wire/errorEnvelope'
|
|
61
77
|
import { decodeResourceResponse } from './resourceRequest'
|
|
@@ -85,6 +101,11 @@ export type DaaUserSigning = Readonly<{
|
|
|
85
101
|
resolveAuthKey: OwnerAuthKeyResolver
|
|
86
102
|
/** `DeviceContext.authKeyId`, which becomes the authorization JWS `kid`. */
|
|
87
103
|
authKeyId: string
|
|
104
|
+
/**
|
|
105
|
+
* The Owner this key signs for, from the same context. Unsigned reads that
|
|
106
|
+
* DAA scopes by Owner, such as the device list an approval reads, need it.
|
|
107
|
+
*/
|
|
108
|
+
clientEntityId: string
|
|
88
109
|
}>
|
|
89
110
|
|
|
90
111
|
export type PostSignedResourceOptions<T> = Readonly<{
|
|
@@ -113,19 +134,14 @@ export async function postSignedResource<T>({
|
|
|
113
134
|
throw contractViolation('postSignedResource only sends POST registry operations')
|
|
114
135
|
}
|
|
115
136
|
|
|
116
|
-
|
|
137
|
+
return postAuthorizedResource({
|
|
117
138
|
transport,
|
|
118
139
|
operation,
|
|
119
|
-
path: profile.canonicalPath,
|
|
120
|
-
authKey,
|
|
121
|
-
authKeyId,
|
|
122
140
|
bodyBytes,
|
|
141
|
+
authorization: await authorizeSignedPost({ operation, authKey, authKeyId, bodyBytes }),
|
|
142
|
+
expectedStatuses: [expectedStatus],
|
|
143
|
+
decode,
|
|
123
144
|
})
|
|
124
|
-
|
|
125
|
-
if (response.status !== expectedStatus) {
|
|
126
|
-
throw mapSignedRequestFailure(response, bodyBytes)
|
|
127
|
-
}
|
|
128
|
-
return decodeResourceResponse({ response, expectedStatus, decode })
|
|
129
145
|
}
|
|
130
146
|
|
|
131
147
|
export type GetSignedResourceOptions<T> = Readonly<{
|
|
@@ -162,71 +178,150 @@ export async function getSignedResource<T>({
|
|
|
162
178
|
throw contractViolation('getSignedResource only sends GET registry operations')
|
|
163
179
|
}
|
|
164
180
|
|
|
181
|
+
const authorization = await authorizeExactRequest({
|
|
182
|
+
authKey,
|
|
183
|
+
authKeyId,
|
|
184
|
+
operation,
|
|
185
|
+
bodyBytes: EMPTY_BODY,
|
|
186
|
+
})
|
|
165
187
|
const response = await sendSignedGet({
|
|
166
188
|
transport,
|
|
167
|
-
operation,
|
|
168
189
|
path: profile.canonicalPath,
|
|
169
|
-
|
|
170
|
-
authKeyId,
|
|
190
|
+
authorization,
|
|
171
191
|
})
|
|
172
192
|
|
|
173
193
|
if (response.status !== expectedStatus) {
|
|
174
|
-
throw mapSignedRequestFailure(response, EMPTY_BODY)
|
|
194
|
+
throw mapSignedRequestFailure(response, EMPTY_BODY, authorization)
|
|
175
195
|
}
|
|
176
196
|
return decodeResourceResponse({ response, expectedStatus, decode })
|
|
177
197
|
}
|
|
178
198
|
|
|
179
|
-
|
|
199
|
+
function sendSignedGet(args: {
|
|
180
200
|
transport: DaaTransport
|
|
181
|
-
operation: DeviceAuthorizationOperation
|
|
182
201
|
path: string
|
|
183
|
-
|
|
184
|
-
authKeyId: string
|
|
202
|
+
authorization: string
|
|
185
203
|
}): Promise<DaaHttpResponse> {
|
|
186
|
-
const compactJws = await authorizeExactRequest({
|
|
187
|
-
authKey: args.authKey,
|
|
188
|
-
authKeyId: args.authKeyId,
|
|
189
|
-
operation: args.operation,
|
|
190
|
-
bodyBytes: EMPTY_BODY,
|
|
191
|
-
})
|
|
192
204
|
return args.transport.send({
|
|
193
205
|
method: 'GET',
|
|
194
206
|
path: args.path,
|
|
195
207
|
query: null,
|
|
196
208
|
headers: {
|
|
197
|
-
[DEVICE_AUTHORIZATION_HEADER]:
|
|
209
|
+
[DEVICE_AUTHORIZATION_HEADER]: args.authorization,
|
|
198
210
|
},
|
|
199
211
|
bodyBytes: null,
|
|
200
212
|
})
|
|
201
213
|
}
|
|
202
214
|
|
|
203
|
-
|
|
215
|
+
function sendAuthorizedPost(args: {
|
|
204
216
|
transport: DaaTransport
|
|
205
|
-
operation: DeviceAuthorizationOperation
|
|
206
217
|
path: string
|
|
207
|
-
authKey: OwnerAuthKey
|
|
208
|
-
authKeyId: string
|
|
209
218
|
bodyBytes: Uint8Array
|
|
219
|
+
authorization: string
|
|
210
220
|
}): Promise<DaaHttpResponse> {
|
|
211
|
-
const compactJws = await authorizeExactRequest({
|
|
212
|
-
authKey: args.authKey,
|
|
213
|
-
authKeyId: args.authKeyId,
|
|
214
|
-
operation: args.operation,
|
|
215
|
-
bodyBytes: args.bodyBytes,
|
|
216
|
-
})
|
|
217
221
|
return args.transport.send({
|
|
218
222
|
method: 'POST',
|
|
219
223
|
path: args.path,
|
|
220
224
|
query: null,
|
|
221
225
|
headers: {
|
|
222
226
|
'Content-Type': 'application/json',
|
|
223
|
-
[DEVICE_AUTHORIZATION_HEADER]:
|
|
227
|
+
[DEVICE_AUTHORIZATION_HEADER]: args.authorization,
|
|
224
228
|
},
|
|
225
229
|
bodyBytes: args.bodyBytes,
|
|
226
230
|
})
|
|
227
231
|
}
|
|
228
232
|
|
|
229
|
-
|
|
233
|
+
export type AuthorizeSignedPostOptions = Readonly<{
|
|
234
|
+
operation: DeviceAuthorizationOperation
|
|
235
|
+
authKey: OwnerAuthKey
|
|
236
|
+
authKeyId: string
|
|
237
|
+
/** Final serialized bytes. The returned authorization is bound to this slice. */
|
|
238
|
+
bodyBytes: Uint8Array
|
|
239
|
+
/** Required for `approve_device` only; see `DeviceAuthorizationRequest.approval`. */
|
|
240
|
+
approval?: DeviceApprovalCheck
|
|
241
|
+
}>
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Sign a POST registry operation's authorization over exact bytes, without
|
|
245
|
+
* sending anything. The signing half of {@link postSignedResource}.
|
|
246
|
+
*/
|
|
247
|
+
export async function authorizeSignedPost({
|
|
248
|
+
operation,
|
|
249
|
+
authKey,
|
|
250
|
+
authKeyId,
|
|
251
|
+
bodyBytes,
|
|
252
|
+
approval,
|
|
253
|
+
}: AuthorizeSignedPostOptions): Promise<string> {
|
|
254
|
+
if (deviceAuthorizationProfile(operation).method !== 'POST') {
|
|
255
|
+
throw contractViolation('authorizeSignedPost only signs POST registry operations')
|
|
256
|
+
}
|
|
257
|
+
return authorizeExactRequest({
|
|
258
|
+
authKey,
|
|
259
|
+
authKeyId,
|
|
260
|
+
operation,
|
|
261
|
+
bodyBytes,
|
|
262
|
+
...(approval === undefined ? {} : { approval }),
|
|
263
|
+
})
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export type PostAuthorizedResourceOptions<T> = Readonly<{
|
|
267
|
+
transport: DaaTransport
|
|
268
|
+
operation: DeviceAuthorizationOperation
|
|
269
|
+
/** The exact bytes `authorization` was signed over. */
|
|
270
|
+
bodyBytes: Uint8Array
|
|
271
|
+
/** A compact JWS from {@link authorizeSignedPost}, sent unchanged. */
|
|
272
|
+
authorization: string
|
|
273
|
+
/** Every status that is a success for this operation, each decoded the same way. */
|
|
274
|
+
expectedStatuses: readonly number[]
|
|
275
|
+
decode: (value: unknown) => T
|
|
276
|
+
/**
|
|
277
|
+
* Endpoint-specific classification of an unexpected status, as on
|
|
278
|
+
* `postResource`. A non-`null` result is thrown; `null` leaves the response
|
|
279
|
+
* to the common signed-request mapping.
|
|
280
|
+
*/
|
|
281
|
+
failure?: (response: DaaHttpResponse) => DaaError | null
|
|
282
|
+
}>
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Send a POST with an authorization signed earlier, unchanged — the sending
|
|
286
|
+
* half of {@link postSignedResource}, and the one to call again on a retry.
|
|
287
|
+
*
|
|
288
|
+
* Nothing here signs, and nothing reads the authorization's `exp`: an exact
|
|
289
|
+
* replay of a request DAA already accepted is answered from its stored result
|
|
290
|
+
* whether or not the JWS has expired, and DAA, not the SDK, decides that.
|
|
291
|
+
* Failures map exactly as {@link postSignedResource}'s do.
|
|
292
|
+
*/
|
|
293
|
+
export async function postAuthorizedResource<T>({
|
|
294
|
+
transport,
|
|
295
|
+
operation,
|
|
296
|
+
bodyBytes,
|
|
297
|
+
authorization,
|
|
298
|
+
expectedStatuses,
|
|
299
|
+
decode,
|
|
300
|
+
failure,
|
|
301
|
+
}: PostAuthorizedResourceOptions<T>): Promise<T> {
|
|
302
|
+
const profile = deviceAuthorizationProfile(operation)
|
|
303
|
+
if (profile.method !== 'POST') {
|
|
304
|
+
throw contractViolation('postAuthorizedResource only sends POST registry operations')
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const response = await sendAuthorizedPost({
|
|
308
|
+
transport,
|
|
309
|
+
path: profile.canonicalPath,
|
|
310
|
+
bodyBytes,
|
|
311
|
+
authorization,
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
if (!expectedStatuses.includes(response.status)) {
|
|
315
|
+
throw failure?.(response) ?? mapSignedRequestFailure(response, bodyBytes, authorization)
|
|
316
|
+
}
|
|
317
|
+
return decodeResourceResponse({ response, expectedStatus: response.status, decode })
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function mapSignedRequestFailure(
|
|
321
|
+
response: DaaHttpResponse,
|
|
322
|
+
bodyBytes: Uint8Array,
|
|
323
|
+
authorization: string,
|
|
324
|
+
): DaaError {
|
|
230
325
|
const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
|
|
231
326
|
const daaStatusCode = readDaaStatusCode(response.bodyBytes)
|
|
232
327
|
const fallback = (): DaaError =>
|
|
@@ -260,8 +355,73 @@ function mapSignedRequestFailure(response: DaaHttpResponse, bodyBytes: Uint8Arra
|
|
|
260
355
|
correlationId,
|
|
261
356
|
)
|
|
262
357
|
}
|
|
358
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_PENDING')) {
|
|
359
|
+
// The key can't sign yet: approved and in its cool-down, or still
|
|
360
|
+
// waiting for approval. Not a credential problem, so not
|
|
361
|
+
// `contract_violation`. Gated on `409`, where every DAA route sends it,
|
|
362
|
+
// like `IDEMPOTENCY_KEY_REUSED` above.
|
|
363
|
+
return response.status === 409 ? devicePending(correlationId) : fallback()
|
|
364
|
+
}
|
|
263
365
|
if (isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_INVALID')) {
|
|
264
|
-
|
|
366
|
+
// DAA's freshness check reports this code (as a `400`), so only this code
|
|
367
|
+
// is refined; a replayed or mismatched authorization is never a clock
|
|
368
|
+
// problem, and a `401` from something other than DAA carries no DAA code.
|
|
369
|
+
return isClockSkewed(response, authorization)
|
|
370
|
+
? clockSkew(correlationId)
|
|
371
|
+
: contractViolation('the device authorization was rejected', correlationId)
|
|
265
372
|
}
|
|
266
373
|
return fallback()
|
|
267
374
|
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* DAA's freshness rule for a device authorization
|
|
378
|
+
* (`OwnerAuthorizationPrevalidator.validateFreshness`): it is refused when
|
|
379
|
+
* `iat > now + 60` or `exp < now - 60`, in whole epoch seconds.
|
|
380
|
+
*/
|
|
381
|
+
const FRESHNESS_SKEW_SECONDS = 60
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Slack for the time between DAA reading its clock and stamping the response
|
|
385
|
+
* `Date`. Only the `exp` side needs it: `Date` is never earlier than the check,
|
|
386
|
+
* so `iat > Date + 60` already proves `iat > now + 60`.
|
|
387
|
+
*/
|
|
388
|
+
const RESPONSE_DATE_SLACK_SECONDS = 5
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Whether DAA refused this authorization because the device clock is wrong,
|
|
392
|
+
* judged from the authorization's own `iat`/`exp` against the response's HTTP
|
|
393
|
+
* `Date`, with DAA's own rule.
|
|
394
|
+
*
|
|
395
|
+
* - `iat` more than 60 s after `Date`: the device clock was ahead when it
|
|
396
|
+
* signed. Compared with the signed `iat`, not `Date.now()`, so neither the
|
|
397
|
+
* whole-second `Date` nor response transit time can push a clock that is
|
|
398
|
+
* within tolerance over the line.
|
|
399
|
+
* - `exp` more than 60 s before `Date`: the authorization had expired, and the
|
|
400
|
+
* device clock now reads more than `exp - iat + 60` seconds (360 s) behind
|
|
401
|
+
* the service — far enough that an authorization signed now would be
|
|
402
|
+
* refused too. A device less far behind passes DAA's rule, so an expiry
|
|
403
|
+
* there is the authorization's age, not the clock: that matters for
|
|
404
|
+
* `contractExecutions.submit`, whose authorization was signed at `prepare`
|
|
405
|
+
* and may simply have aged out, whatever the clock did since.
|
|
406
|
+
*
|
|
407
|
+
* `Date` is unsigned and the transport is the consumer's, so this only chooses
|
|
408
|
+
* between two classifications of a response that has already failed. A
|
|
409
|
+
* missing or unreadable `Date` or claim is not skew.
|
|
410
|
+
*/
|
|
411
|
+
function isClockSkewed(response: DaaHttpResponse, authorization: string): boolean {
|
|
412
|
+
const serverMillis = httpDateMillis(headerValueIgnoringCase(response.headers, 'Date'))
|
|
413
|
+
const claims = jwsSegmentJson(authorization, 1)
|
|
414
|
+
const iat = claims?.['iat']
|
|
415
|
+
const exp = claims?.['exp']
|
|
416
|
+
if (serverMillis === null || typeof iat !== 'number' || typeof exp !== 'number') {
|
|
417
|
+
return false
|
|
418
|
+
}
|
|
419
|
+
const serverSeconds = serverMillis / 1000
|
|
420
|
+
if (iat > serverSeconds + FRESHNESS_SKEW_SECONDS) {
|
|
421
|
+
return true
|
|
422
|
+
}
|
|
423
|
+
return (
|
|
424
|
+
exp < serverSeconds - FRESHNESS_SKEW_SECONDS - RESPONSE_DATE_SLACK_SECONDS &&
|
|
425
|
+
serverMillis - Date.now() > (exp - iat + FRESHNESS_SKEW_SECONDS) * 1000
|
|
426
|
+
)
|
|
427
|
+
}
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
// | Lifetime | durable, survives the app | **one login attempt** |
|
|
32
32
|
// | Scope | `{environment, customer application, Owner (clientEntityId), installation}` | nothing; it is anonymous |
|
|
33
33
|
// | Storage | Secure Enclave / Android Keystore, via `SecureKeyStore` | process memory only |
|
|
34
|
-
// | Exported at | Device Registration Complete (`
|
|
34
|
+
// | Exported at | Device Registration Complete (`deviceKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) |
|
|
35
35
|
// | Selected | only *after* the Social Session response | before Prepare |
|
|
36
36
|
// | Authorizes | DAA operations, via `X-Device-Authorization` | nothing |
|
|
37
37
|
//
|