@serfab/cadre-core 1.23.0 → 1.24.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.
Files changed (313) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +145 -44
  8. package/dist/cadre-node.js +239 -79
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,285 +1,285 @@
1
- /**
2
- * The app's side of signing in to a hosting provider: OAuth 2 authorization code with PKCE
3
- * (RFC 6749 §4.1, RFC 7636), the flow for a public client that holds no secret, against the
4
- * endpoints a provider descriptor names (`docs/architecture.md` → "Provider descriptor and
5
- * sign-in"). Opening the browser is the app's or its kit's; this module builds the URL it
6
- * opens, reads the redirect it comes back with, exchanges and refreshes tokens, and keeps a
7
- * token fresh for the provider client ({@link createTokenSource}).
8
- *
9
- * Imports `@noble/hashes` for SHA-256 and the CSPRNG (`crypto.getRandomValues`, which the
10
- * React Native kit polyfills) and `uint8arrays` for base64url, so it loads on React Native
11
- * and in the browser as well as Node. Codes and tokens are credentials: none is ever logged.
12
- */
13
-
14
- import debug from 'debug';
15
- import { sha256 } from '@noble/hashes/sha2.js';
16
- import { randomBytes } from '@noble/hashes/utils.js';
17
- import { toString as uint8ArrayToString } from 'uint8arrays';
18
- import { requireFetch } from '../fetch-impl.js';
19
- import type { ProviderDescriptor } from './descriptor.js';
20
-
21
- const log = debug('sereus:cadre:provider-oauth');
22
-
23
- /**
24
- * A sign-in fault, with a machine-readable `code`: the provider's own OAuth error code
25
- * (`invalid_grant`, `access_denied`, ... per RFC 6749 §5.2) when it answered one;
26
- * `state-mismatch` or `missing-code` when the redirect could not be read; `invalid_response`
27
- * when the token endpoint answered something that is not a token response; `reauthorize`
28
- * when a refresh was refused, the app's cue to run the authorization again.
29
- */
30
- export class ProviderAuthError extends Error {
31
- constructor(readonly code: string, description?: string, options?: { cause?: unknown }) {
32
- super(description ? `${code}: ${description}` : code, options);
33
- this.name = 'ProviderAuthError';
34
- }
35
- }
36
-
37
- /** What a token exchange or refresh yields, with `expiresAt` already in epoch milliseconds. */
38
- export interface ProviderTokens {
39
- accessToken: string;
40
- refreshToken: string;
41
- /** Epoch ms when `accessToken` stops working. */
42
- expiresAt: number;
43
- scopes: string[];
44
- }
45
-
46
- /** A PKCE pair (RFC 7636): the verifier the app keeps, and the S256 challenge it sends first. */
47
- export interface Pkce {
48
- verifier: string;
49
- challenge: string;
50
- }
51
-
52
- /** The S256 challenge for `verifier`: base64url(SHA-256(ascii(verifier))), unpadded. */
53
- export function pkceChallenge(verifier: string): string {
54
- return uint8ArrayToString(sha256(new TextEncoder().encode(verifier)), 'base64url');
55
- }
56
-
57
- /** A fresh pair: 32 random bytes as a 43-character base64url verifier, and its challenge. */
58
- export function createPkce(): Pkce {
59
- const verifier = uint8ArrayToString(randomBytes(32), 'base64url');
60
- return { verifier, challenge: pkceChallenge(verifier) };
61
- }
62
-
63
- /** A random `state` for one authorization, which {@link readAuthorizationRedirect} checks the redirect against. */
64
- export function createAuthorizationState(): string {
65
- return uint8ArrayToString(randomBytes(16), 'base64url');
66
- }
67
-
68
- export interface AuthorizationUrlOptions {
69
- /** The client id the app registered with the provider. */
70
- clientId: string;
71
- /** One of that client's registered redirect URIs, exactly as registered. */
72
- redirectUri: string;
73
- state: string;
74
- /** The S256 challenge of the verifier the app keeps ({@link createPkce}). */
75
- challenge: string;
76
- /** Scopes to ask for; defaults to every scope the descriptor lists. */
77
- scopes?: readonly string[];
78
- }
79
-
80
- /** The authorize URL to open in the system browser: `response_type=code`, the client, the redirect URI, the scopes space-joined, the state and the S256 challenge. */
81
- export function authorizationUrl(descriptor: ProviderDescriptor, options: AuthorizationUrlOptions): string {
82
- const url = new URL(descriptor.oauth.authorizeUrl);
83
- url.searchParams.set('response_type', 'code');
84
- url.searchParams.set('client_id', options.clientId);
85
- url.searchParams.set('redirect_uri', options.redirectUri);
86
- url.searchParams.set('scope', (options.scopes ?? descriptor.oauth.scopes).join(' '));
87
- url.searchParams.set('state', options.state);
88
- url.searchParams.set('code_challenge', options.challenge);
89
- url.searchParams.set('code_challenge_method', 'S256');
90
- return url.toString();
91
- }
92
-
93
- /** What the browser came back with: a code to exchange, or the provider's refusal (RFC 6749 §4.1.2.1). */
94
- export type AuthorizationRedirect =
95
- | { code: string }
96
- | { error: string; description?: string };
97
-
98
- /**
99
- * Read the redirect URL the browser returned to the app. Throws `ProviderAuthError`
100
- * (`state-mismatch`) when its `state` is not `expectedState`, whichever outcome it carries,
101
- * and (`missing-code`) when it carries neither a code nor an error. The code is a credential
102
- * and never appears in a message or a log line.
103
- */
104
- export function readAuthorizationRedirect(url: string, options: { expectedState: string }): AuthorizationRedirect {
105
- const params = new URL(url).searchParams;
106
- if (params.get('state') !== options.expectedState) {
107
- throw new ProviderAuthError('state-mismatch', 'the redirect\'s state is not the one this authorization sent');
108
- }
109
- const error = params.get('error');
110
- if (error !== null) {
111
- const description = params.get('error_description');
112
- return description === null ? { error } : { error, description };
113
- }
114
- const code = params.get('code');
115
- if (code === null || code === '') {
116
- throw new ProviderAuthError('missing-code', 'the redirect carries neither a code nor an error');
117
- }
118
- return { code };
119
- }
120
-
121
- export interface ExchangeAuthorizationCodeOptions {
122
- clientId: string;
123
- /** The redirect URI the authorization was sent with, exactly. */
124
- redirectUri: string;
125
- code: string;
126
- /** The verifier of the challenge the authorization was sent with. */
127
- verifier: string;
128
- fetch?: typeof fetch;
129
- }
130
-
131
- /** `grant_type=authorization_code` at the descriptor's token endpoint, form-encoded; a refusal is a `ProviderAuthError` with the provider's error code. */
132
- export async function exchangeAuthorizationCode(descriptor: ProviderDescriptor, options: ExchangeAuthorizationCodeOptions): Promise<ProviderTokens> {
133
- return await requestTokens(descriptor, {
134
- grant_type: 'authorization_code',
135
- code: options.code,
136
- code_verifier: options.verifier,
137
- client_id: options.clientId,
138
- redirect_uri: options.redirectUri,
139
- }, options.fetch);
140
- }
141
-
142
- export interface RefreshTokensOptions {
143
- clientId: string;
144
- refreshToken: string;
145
- fetch?: typeof fetch;
146
- }
147
-
148
- /** `grant_type=refresh_token`: rotates the pair (the presented one stops working); a refusal is a `ProviderAuthError` with the provider's error code. */
149
- export async function refreshTokens(descriptor: ProviderDescriptor, options: RefreshTokensOptions): Promise<ProviderTokens> {
150
- return await requestTokens(descriptor, {
151
- grant_type: 'refresh_token',
152
- refresh_token: options.refreshToken,
153
- client_id: options.clientId,
154
- }, options.fetch);
155
- }
156
-
157
- /** Hands the provider client a working bearer; see {@link createTokenSource}. */
158
- export interface TokenSource {
159
- /** The current access token, refreshed first when it is within a minute of expiry. */
160
- accessToken(): Promise<string>;
161
- /**
162
- * The provider answered 401 to `stale`: refresh and return the new token. A refresh that
163
- * already replaced `stale` is not repeated, so two requests refused at once cost one
164
- * rotation.
165
- */
166
- invalidate(stale?: string): Promise<string>;
167
- }
168
-
169
- export interface TokenSourceOptions {
170
- descriptor: ProviderDescriptor;
171
- clientId: string;
172
- /** The tokens the app holds, from the exchange or from its store. */
173
- tokens: ProviderTokens;
174
- /** Called with the new pair after every refresh; the old pair has stopped working by then. */
175
- persist: (tokens: ProviderTokens) => void | Promise<void>;
176
- fetch?: typeof fetch;
177
- /** The clock, for tests. */
178
- now?: () => number;
179
- }
180
-
181
- /** A token is refreshed this long before it expires, so a request does not leave with one about to lapse. */
182
- export const TOKEN_REFRESH_MARGIN_MS = 60_000;
183
-
184
- /**
185
- * A {@link TokenSource} over one token pair: refreshes within {@link TOKEN_REFRESH_MARGIN_MS}
186
- * of expiry and on `invalidate`, calls `persist` after every refresh, and shares one refresh
187
- * among concurrent callers (a rotation spends the presented refresh token, so two at once
188
- * would leave one caller with a refused pair). A refused refresh throws
189
- * `ProviderAuthError('reauthorize')`: the pair is gone and the app signs in again; a network
190
- * failure is rethrown as is, since the pair may still be good.
191
- */
192
- export function createTokenSource(options: TokenSourceOptions): TokenSource {
193
- const now = options.now ?? Date.now;
194
- let current = options.tokens;
195
- let inFlight: Promise<ProviderTokens> | null = null;
196
-
197
- const refresh = (): Promise<ProviderTokens> => {
198
- if (!inFlight) {
199
- inFlight = rotate().finally(() => { inFlight = null; });
200
- }
201
- return inFlight;
202
- };
203
-
204
- async function rotate(): Promise<ProviderTokens> {
205
- let next: ProviderTokens;
206
- try {
207
- next = await refreshTokens(options.descriptor, { clientId: options.clientId, refreshToken: current.refreshToken, fetch: options.fetch });
208
- } catch (error) {
209
- if (error instanceof ProviderAuthError) {
210
- log('token refresh refused (%s); the app must authorize again', error.code);
211
- throw new ProviderAuthError('reauthorize', `the provider refused to refresh the token (${error.code})`, { cause: error });
212
- }
213
- throw error;
214
- }
215
- current = next;
216
- await options.persist(next);
217
- log('token refreshed; expires in %ds', Math.round((next.expiresAt - now()) / 1000));
218
- return next;
219
- }
220
-
221
- return {
222
- async accessToken(): Promise<string> {
223
- const fresh = now() < current.expiresAt - TOKEN_REFRESH_MARGIN_MS ? current : await refresh();
224
- return fresh.accessToken;
225
- },
226
- async invalidate(stale?: string): Promise<string> {
227
- if (stale !== undefined && stale !== current.accessToken) return current.accessToken;
228
- return (await refresh()).accessToken;
229
- },
230
- };
231
- }
232
-
233
- /** One token-endpoint request (RFC 6749 §4.1.3, §6): form-encoded in, a token response or a `{ error, error_description }` refusal out. */
234
- async function requestTokens(descriptor: ProviderDescriptor, form: Record<string, string>, fetchImpl?: typeof fetch): Promise<ProviderTokens> {
235
- const doFetch = requireFetch(fetchImpl);
236
- const requestedAt = Date.now();
237
- const response = await doFetch(descriptor.oauth.tokenUrl, {
238
- method: 'POST',
239
- headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
240
- body: new URLSearchParams(form).toString(),
241
- });
242
- const body = await readJson(response);
243
- if (!response.ok) {
244
- const error = body && typeof body.error === 'string' ? body.error : 'invalid_response';
245
- const description = body && typeof body.error_description === 'string'
246
- ? body.error_description
247
- : `the token endpoint answered ${response.status}`;
248
- throw new ProviderAuthError(error, description);
249
- }
250
- return tokensFrom(body, requestedAt);
251
- }
252
-
253
- /** The response's JSON object, or null when the body is not one. */
254
- async function readJson(response: Response): Promise<Record<string, unknown> | null> {
255
- try {
256
- const parsed: unknown = await response.json();
257
- return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
258
- } catch (error) {
259
- log('token endpoint answered %d with a body that is not JSON: %o', response.status, error);
260
- return null;
261
- }
262
- }
263
-
264
- /** `{ access_token, expires_in, refresh_token, scope }` as {@link ProviderTokens}; `expires_in` counts from when the request left. */
265
- function tokensFrom(body: Record<string, unknown> | null, requestedAt: number): ProviderTokens {
266
- const accessToken = body?.access_token;
267
- const refreshToken = body?.refresh_token;
268
- const expiresIn = body?.expires_in;
269
- if (typeof accessToken !== 'string' || accessToken === '') {
270
- throw new ProviderAuthError('invalid_response', 'the token response carries no access_token');
271
- }
272
- if (typeof refreshToken !== 'string' || refreshToken === '') {
273
- throw new ProviderAuthError('invalid_response', 'the token response carries no refresh_token, which a token source needs to outlive the access token');
274
- }
275
- if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
276
- throw new ProviderAuthError('invalid_response', 'the token response carries no positive expires_in');
277
- }
278
- const scope = body?.scope;
279
- return {
280
- accessToken,
281
- refreshToken,
282
- expiresAt: requestedAt + expiresIn * 1000,
283
- scopes: typeof scope === 'string' ? scope.split(' ').filter((entry) => entry !== '') : [],
284
- };
285
- }
1
+ /**
2
+ * The app's side of signing in to a hosting provider: OAuth 2 authorization code with PKCE
3
+ * (RFC 6749 §4.1, RFC 7636), the flow for a public client that holds no secret, against the
4
+ * endpoints a provider descriptor names (`docs/hosting/provider.md` → "The provider descriptor and
5
+ * sign-in"). Opening the browser is the app's or its kit's; this module builds the URL it
6
+ * opens, reads the redirect it comes back with, exchanges and refreshes tokens, and keeps a
7
+ * token fresh for the provider client ({@link createTokenSource}).
8
+ *
9
+ * Imports `@noble/hashes` for SHA-256 and the CSPRNG (`crypto.getRandomValues`, which the
10
+ * React Native kit polyfills) and `uint8arrays` for base64url, so it loads on React Native
11
+ * and in the browser as well as Node. Codes and tokens are credentials: none is ever logged.
12
+ */
13
+
14
+ import debug from 'debug';
15
+ import { sha256 } from '@noble/hashes/sha2.js';
16
+ import { randomBytes } from '@noble/hashes/utils.js';
17
+ import { toString as uint8ArrayToString } from 'uint8arrays';
18
+ import { requireFetch } from '../fetch-impl.js';
19
+ import type { ProviderDescriptor } from './descriptor.js';
20
+
21
+ const log = debug('sereus:cadre:provider-oauth');
22
+
23
+ /**
24
+ * A sign-in fault, with a machine-readable `code`: the provider's own OAuth error code
25
+ * (`invalid_grant`, `access_denied`, ... per RFC 6749 §5.2) when it answered one;
26
+ * `state-mismatch` or `missing-code` when the redirect could not be read; `invalid_response`
27
+ * when the token endpoint answered something that is not a token response; `reauthorize`
28
+ * when a refresh was refused, the app's cue to run the authorization again.
29
+ */
30
+ export class ProviderAuthError extends Error {
31
+ constructor(readonly code: string, description?: string, options?: { cause?: unknown }) {
32
+ super(description ? `${code}: ${description}` : code, options);
33
+ this.name = 'ProviderAuthError';
34
+ }
35
+ }
36
+
37
+ /** What a token exchange or refresh yields, with `expiresAt` already in epoch milliseconds. */
38
+ export interface ProviderTokens {
39
+ accessToken: string;
40
+ refreshToken: string;
41
+ /** Epoch ms when `accessToken` stops working. */
42
+ expiresAt: number;
43
+ scopes: string[];
44
+ }
45
+
46
+ /** A PKCE pair (RFC 7636): the verifier the app keeps, and the S256 challenge it sends first. */
47
+ export interface Pkce {
48
+ verifier: string;
49
+ challenge: string;
50
+ }
51
+
52
+ /** The S256 challenge for `verifier`: base64url(SHA-256(ascii(verifier))), unpadded. */
53
+ export function pkceChallenge(verifier: string): string {
54
+ return uint8ArrayToString(sha256(new TextEncoder().encode(verifier)), 'base64url');
55
+ }
56
+
57
+ /** A fresh pair: 32 random bytes as a 43-character base64url verifier, and its challenge. */
58
+ export function createPkce(): Pkce {
59
+ const verifier = uint8ArrayToString(randomBytes(32), 'base64url');
60
+ return { verifier, challenge: pkceChallenge(verifier) };
61
+ }
62
+
63
+ /** A random `state` for one authorization, which {@link readAuthorizationRedirect} checks the redirect against. */
64
+ export function createAuthorizationState(): string {
65
+ return uint8ArrayToString(randomBytes(16), 'base64url');
66
+ }
67
+
68
+ export interface AuthorizationUrlOptions {
69
+ /** The client id the app registered with the provider. */
70
+ clientId: string;
71
+ /** One of that client's registered redirect URIs, exactly as registered. */
72
+ redirectUri: string;
73
+ state: string;
74
+ /** The S256 challenge of the verifier the app keeps ({@link createPkce}). */
75
+ challenge: string;
76
+ /** Scopes to ask for; defaults to every scope the descriptor lists. */
77
+ scopes?: readonly string[];
78
+ }
79
+
80
+ /** The authorize URL to open in the system browser: `response_type=code`, the client, the redirect URI, the scopes space-joined, the state and the S256 challenge. */
81
+ export function authorizationUrl(descriptor: ProviderDescriptor, options: AuthorizationUrlOptions): string {
82
+ const url = new URL(descriptor.oauth.authorizeUrl);
83
+ url.searchParams.set('response_type', 'code');
84
+ url.searchParams.set('client_id', options.clientId);
85
+ url.searchParams.set('redirect_uri', options.redirectUri);
86
+ url.searchParams.set('scope', (options.scopes ?? descriptor.oauth.scopes).join(' '));
87
+ url.searchParams.set('state', options.state);
88
+ url.searchParams.set('code_challenge', options.challenge);
89
+ url.searchParams.set('code_challenge_method', 'S256');
90
+ return url.toString();
91
+ }
92
+
93
+ /** What the browser came back with: a code to exchange, or the provider's refusal (RFC 6749 §4.1.2.1). */
94
+ export type AuthorizationRedirect =
95
+ | { code: string }
96
+ | { error: string; description?: string };
97
+
98
+ /**
99
+ * Read the redirect URL the browser returned to the app. Throws `ProviderAuthError`
100
+ * (`state-mismatch`) when its `state` is not `expectedState`, whichever outcome it carries,
101
+ * and (`missing-code`) when it carries neither a code nor an error. The code is a credential
102
+ * and never appears in a message or a log line.
103
+ */
104
+ export function readAuthorizationRedirect(url: string, options: { expectedState: string }): AuthorizationRedirect {
105
+ const params = new URL(url).searchParams;
106
+ if (params.get('state') !== options.expectedState) {
107
+ throw new ProviderAuthError('state-mismatch', 'the redirect\'s state is not the one this authorization sent');
108
+ }
109
+ const error = params.get('error');
110
+ if (error !== null) {
111
+ const description = params.get('error_description');
112
+ return description === null ? { error } : { error, description };
113
+ }
114
+ const code = params.get('code');
115
+ if (code === null || code === '') {
116
+ throw new ProviderAuthError('missing-code', 'the redirect carries neither a code nor an error');
117
+ }
118
+ return { code };
119
+ }
120
+
121
+ export interface ExchangeAuthorizationCodeOptions {
122
+ clientId: string;
123
+ /** The redirect URI the authorization was sent with, exactly. */
124
+ redirectUri: string;
125
+ code: string;
126
+ /** The verifier of the challenge the authorization was sent with. */
127
+ verifier: string;
128
+ fetch?: typeof fetch;
129
+ }
130
+
131
+ /** `grant_type=authorization_code` at the descriptor's token endpoint, form-encoded; a refusal is a `ProviderAuthError` with the provider's error code. */
132
+ export async function exchangeAuthorizationCode(descriptor: ProviderDescriptor, options: ExchangeAuthorizationCodeOptions): Promise<ProviderTokens> {
133
+ return await requestTokens(descriptor, {
134
+ grant_type: 'authorization_code',
135
+ code: options.code,
136
+ code_verifier: options.verifier,
137
+ client_id: options.clientId,
138
+ redirect_uri: options.redirectUri,
139
+ }, options.fetch);
140
+ }
141
+
142
+ export interface RefreshTokensOptions {
143
+ clientId: string;
144
+ refreshToken: string;
145
+ fetch?: typeof fetch;
146
+ }
147
+
148
+ /** `grant_type=refresh_token`: rotates the pair (the presented one stops working); a refusal is a `ProviderAuthError` with the provider's error code. */
149
+ export async function refreshTokens(descriptor: ProviderDescriptor, options: RefreshTokensOptions): Promise<ProviderTokens> {
150
+ return await requestTokens(descriptor, {
151
+ grant_type: 'refresh_token',
152
+ refresh_token: options.refreshToken,
153
+ client_id: options.clientId,
154
+ }, options.fetch);
155
+ }
156
+
157
+ /** Hands the provider client a working bearer; see {@link createTokenSource}. */
158
+ export interface TokenSource {
159
+ /** The current access token, refreshed first when it is within a minute of expiry. */
160
+ accessToken(): Promise<string>;
161
+ /**
162
+ * The provider answered 401 to `stale`: refresh and return the new token. A refresh that
163
+ * already replaced `stale` is not repeated, so two requests refused at once cost one
164
+ * rotation.
165
+ */
166
+ invalidate(stale?: string): Promise<string>;
167
+ }
168
+
169
+ export interface TokenSourceOptions {
170
+ descriptor: ProviderDescriptor;
171
+ clientId: string;
172
+ /** The tokens the app holds, from the exchange or from its store. */
173
+ tokens: ProviderTokens;
174
+ /** Called with the new pair after every refresh; the old pair has stopped working by then. */
175
+ persist: (tokens: ProviderTokens) => void | Promise<void>;
176
+ fetch?: typeof fetch;
177
+ /** The clock, for tests. */
178
+ now?: () => number;
179
+ }
180
+
181
+ /** A token is refreshed this long before it expires, so a request does not leave with one about to lapse. */
182
+ export const TOKEN_REFRESH_MARGIN_MS = 60_000;
183
+
184
+ /**
185
+ * A {@link TokenSource} over one token pair: refreshes within {@link TOKEN_REFRESH_MARGIN_MS}
186
+ * of expiry and on `invalidate`, calls `persist` after every refresh, and shares one refresh
187
+ * among concurrent callers (a rotation spends the presented refresh token, so two at once
188
+ * would leave one caller with a refused pair). A refused refresh throws
189
+ * `ProviderAuthError('reauthorize')`: the pair is gone and the app signs in again; a network
190
+ * failure is rethrown as is, since the pair may still be good.
191
+ */
192
+ export function createTokenSource(options: TokenSourceOptions): TokenSource {
193
+ const now = options.now ?? Date.now;
194
+ let current = options.tokens;
195
+ let inFlight: Promise<ProviderTokens> | null = null;
196
+
197
+ const refresh = (): Promise<ProviderTokens> => {
198
+ if (!inFlight) {
199
+ inFlight = rotate().finally(() => { inFlight = null; });
200
+ }
201
+ return inFlight;
202
+ };
203
+
204
+ async function rotate(): Promise<ProviderTokens> {
205
+ let next: ProviderTokens;
206
+ try {
207
+ next = await refreshTokens(options.descriptor, { clientId: options.clientId, refreshToken: current.refreshToken, fetch: options.fetch });
208
+ } catch (error) {
209
+ if (error instanceof ProviderAuthError) {
210
+ log('token refresh refused (%s); the app must authorize again', error.code);
211
+ throw new ProviderAuthError('reauthorize', `the provider refused to refresh the token (${error.code})`, { cause: error });
212
+ }
213
+ throw error;
214
+ }
215
+ current = next;
216
+ await options.persist(next);
217
+ log('token refreshed; expires in %ds', Math.round((next.expiresAt - now()) / 1000));
218
+ return next;
219
+ }
220
+
221
+ return {
222
+ async accessToken(): Promise<string> {
223
+ const fresh = now() < current.expiresAt - TOKEN_REFRESH_MARGIN_MS ? current : await refresh();
224
+ return fresh.accessToken;
225
+ },
226
+ async invalidate(stale?: string): Promise<string> {
227
+ if (stale !== undefined && stale !== current.accessToken) return current.accessToken;
228
+ return (await refresh()).accessToken;
229
+ },
230
+ };
231
+ }
232
+
233
+ /** One token-endpoint request (RFC 6749 §4.1.3, §6): form-encoded in, a token response or a `{ error, error_description }` refusal out. */
234
+ async function requestTokens(descriptor: ProviderDescriptor, form: Record<string, string>, fetchImpl?: typeof fetch): Promise<ProviderTokens> {
235
+ const doFetch = requireFetch(fetchImpl);
236
+ const requestedAt = Date.now();
237
+ const response = await doFetch(descriptor.oauth.tokenUrl, {
238
+ method: 'POST',
239
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
240
+ body: new URLSearchParams(form).toString(),
241
+ });
242
+ const body = await readJson(response);
243
+ if (!response.ok) {
244
+ const error = body && typeof body.error === 'string' ? body.error : 'invalid_response';
245
+ const description = body && typeof body.error_description === 'string'
246
+ ? body.error_description
247
+ : `the token endpoint answered ${response.status}`;
248
+ throw new ProviderAuthError(error, description);
249
+ }
250
+ return tokensFrom(body, requestedAt);
251
+ }
252
+
253
+ /** The response's JSON object, or null when the body is not one. */
254
+ async function readJson(response: Response): Promise<Record<string, unknown> | null> {
255
+ try {
256
+ const parsed: unknown = await response.json();
257
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
258
+ } catch (error) {
259
+ log('token endpoint answered %d with a body that is not JSON: %o', response.status, error);
260
+ return null;
261
+ }
262
+ }
263
+
264
+ /** `{ access_token, expires_in, refresh_token, scope }` as {@link ProviderTokens}; `expires_in` counts from when the request left. */
265
+ function tokensFrom(body: Record<string, unknown> | null, requestedAt: number): ProviderTokens {
266
+ const accessToken = body?.access_token;
267
+ const refreshToken = body?.refresh_token;
268
+ const expiresIn = body?.expires_in;
269
+ if (typeof accessToken !== 'string' || accessToken === '') {
270
+ throw new ProviderAuthError('invalid_response', 'the token response carries no access_token');
271
+ }
272
+ if (typeof refreshToken !== 'string' || refreshToken === '') {
273
+ throw new ProviderAuthError('invalid_response', 'the token response carries no refresh_token, which a token source needs to outlive the access token');
274
+ }
275
+ if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
276
+ throw new ProviderAuthError('invalid_response', 'the token response carries no positive expires_in');
277
+ }
278
+ const scope = body?.scope;
279
+ return {
280
+ accessToken,
281
+ refreshToken,
282
+ expiresAt: requestedAt + expiresIn * 1000,
283
+ scopes: typeof scope === 'string' ? scope.split(' ').filter((entry) => entry !== '') : [],
284
+ };
285
+ }