@webex/webex-core 3.12.0-next.62 → 3.12.0-next.64

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.
@@ -0,0 +1,846 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'credentials specification'
4
+ description: Responsibilities, boundaries, design, invariants, and verification for the webex-core credentials module, covering the supertoken and user-token lifecycle, scope utilities, OAuth grant errors, and credentials configuration.
5
+ tags: [module, specification]
6
+ ---
7
+ <!-- sdd-generated-metadata
8
+ doc_kind: module-spec
9
+ generated_from: module-spec@0.3.0
10
+ generated_by: claude-code
11
+ approved_by: rsarika@cisco.com
12
+ updated_at: 2026-10-07T13:20:21Z
13
+ validation_status: pass-with-warnings
14
+ -->
15
+
16
+ # credentials
17
+
18
+ This source-local document at `src/lib/credentials/docs/README.md` owns the stable specification
19
+ for **credentials**: the `Credentials` plugin, the `Token` model and its collection, the scope
20
+ helpers, the OAuth grant-error taxonomy, and the `CredentialsConfig` defaults in
21
+ `src/credentials-config.js`.
22
+
23
+ The package entry point, plugin registration machinery, the `WebexCore` constructor that normalizes
24
+ the token shapes callers pass in, the logout orchestration, and the `AuthInterceptor` that consumes
25
+ this module belong to the parent module and are specified in [`src/docs/README.md`](../../../docs/README.md).
26
+ The `@persist` and `@waitForValue` decorators and the stores they write to belong to the storage
27
+ sibling module; the interceptor sibling owns request-time authorization.
28
+
29
+ Related context: [repository architecture](../../../../docs/architecture.md) ·
30
+ [documentation index](../../../../docs/index.md) · [agent instructions](../../../../AGENTS.md) ·
31
+ [specification registry](../../../../docs/specs/README.md)
32
+
33
+ ## Metadata
34
+
35
+ | Field | Value |
36
+ | ----------------- | ----------------------------------------------------------------------------------------------- |
37
+ | Owner | Cisco Webex for Developers |
38
+ | Source path | `src/lib/credentials` |
39
+ | Resource kind | Capability module |
40
+ | Status | Active |
41
+ | Last verified | 2026-10-07 |
42
+ | Module id | `src/lib/credentials` |
43
+ | Parent spec | [`src/docs/README.md`](../../../docs/README.md) |
44
+ | Doc kind | Module spec |
45
+ | Coverage score | 93.8% assessed 2026-10-07; 15 of 16 mandatory fields present; critical 8 of 8; independent validation pass-with-warnings 2026-10-07 |
46
+ | Validation status | Pass with warnings — 2026-10-07; runtime `01a1166d-02d9-7772-bc25-1a801fb5f1d1`; 0 Blocking, 8 Important, 3 Medium |
47
+
48
+ ## Applicability
49
+
50
+ | Condition ID | Status | Evidence or reason | Owned section |
51
+ | ------------------------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------- |
52
+ | `module.has_tiers` | N/A | The repository assigns no operational or review tiers | Tier |
53
+ | `module.has_ui` | N/A | No components or rendering; login URLs are strings that a caller navigates to | UI use-case flow |
54
+ | `module.crosses_service_boundaries` | Applicable | Token, downscope, revoke, and client-credentials calls go to the identity broker through `src/lib/credentials/token.js` and `src/lib/credentials/credentials.js` | Cross-boundary use-case flow |
55
+ | `module.holds_client_state` | Applicable | `src/lib/credentials/credentials.js` holds the supertoken, user-token collection, refresh timer, and the refreshing and ready flags | Client state model |
56
+ | `module.enforces_domain_rules` | Applicable | Scope-subset, scope-reduction, token-validity, and refresh-token-preservation rules in `src/lib/credentials/token.js` | Business rules and invariants |
57
+ | `module.is_concurrent_async` | Applicable | De-duplicated and queued refresh, per-scope downscope flights, and expiry and refresh timers in `src/lib/credentials/credentials.js` | Concurrency and reactive flow |
58
+ | `module.owns_persistence` | Applicable | `src/lib/credentials/credentials.js` persists its whole state under one storage key; no schema versioning or migration exists | Data, schema, and migration |
59
+ | `module.stateful_transitions` | Applicable | Credentials lifecycle (refreshing, invalidated) and Token lifecycle (expired, revoked) in `src/lib/credentials/credentials.js` and `src/lib/credentials/token.js` | State machine |
60
+ | `module.exposes_wire_protocol` | Applicable | OAuth grant request forms and the login, logout, and third-party URLs built in `src/lib/credentials/credentials.js` and `src/lib/credentials/token.js` | Protocol and wire format |
61
+ | `module.ui_multi_screen` | N/A | Gated by module.has_ui, which is N/A | UI flow |
62
+ | `module.large_data_model` | N/A | Two small entities (the token model and the credentials aggregate); no large or complex schema | Data model |
63
+ | `module.returns_caller_errors` | Applicable | Grant errors in `src/lib/credentials/grant-errors.js` and the plain error rejections thrown from `src/lib/credentials/token.js` | Caller-visible failure modes |
64
+ | `module.module_specific_conventions` | Applicable | Decorator ordering, config-before-instantiation, and env-var configuration conventions in `src/lib/credentials/token.js` and `src/credentials-config.js` | Module-specific rules |
65
+ | `module.published_package` | Applicable | The credentials plugin, token model, grant errors, and two scope helpers are re-exported through `src/index.js` and consumed by sibling plugins | Export stability |
66
+ | `module.embedded_in_host` | N/A | Registered as a plugin on the SDK object, not mounted into a host application | Host integration and theming |
67
+ | `module.has_design_tradeoff` | Applicable | Downscope fallback to the supertoken, client-secret-gated revocation, and the timer-based expiry flag | Key design trade-off |
68
+ | `module.has_submodules` | N/A | No child modules; computed from the manifest module tree | Sub-modules |
69
+
70
+ ## Evidence register
71
+
72
+ | Evidence | What it establishes |
73
+ | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
74
+ | `src/lib/credentials/credentials.js` | The `Credentials` plugin: login/logout/third-party URL builders, OrgId and user-id extraction, user-token resolution, refresh, invalidate, client-credentials grant, refresh scheduling |
75
+ | `src/lib/credentials/token.js` | The `Token` model: derived capability flags, expiry timer, downscope, refresh, revoke, validate, header rendering, grant-error mapping |
76
+ | `src/lib/credentials/grant-errors.js` | The `OAuthError` family and the `select` lookup from an OAuth `error` string |
77
+ | `src/lib/credentials/scope.js` | `sortScope`, `filterScope`, and `diffScopes` |
78
+ | `src/lib/credentials/token-collection.js` | The collection of user tokens, indexed by `scope` |
79
+ | `src/lib/credentials/index.js` | Plugin registration with proxied `canAuthorize` and `canRefresh`, and the module's named exports |
80
+ | `src/credentials-config.js` | Configuration keys, environment-variable fallbacks, and the derived identity-broker URLs |
81
+ | `src/index.js` | The subset of this module re-exported from the package entry point |
82
+ | `src/config.js` | Where `CredentialsConfig` is instantiated as the `credentials` section of the SDK defaults |
83
+ | `src/lib/constants.js` | The two metric names this module submits |
84
+ | `src/lib/storage/decorators.js` | What `@persist` and `@waitForValue` do to the decorated methods |
85
+ | `src/lib/storage/make-webex-plugin-store.js` | How a plugin's state is serialized before it is written |
86
+ | `src/lib/webex-plugin.js` | The base class: `config`, `logger`, `webex` resolution and the `ready` session flag |
87
+ | `src/interceptors/auth.js` | How the interceptor sibling calls `getUserToken`, `canRefresh`, and `refresh` |
88
+ | `src/lib/services/services.js` | `updateCredentialsConfig`, which rewrites `idbroker`, `identity`, and `authorizeUrl` that this module's derived URLs read |
89
+ | `src/webex-core.js` | `logout` calling `invalidate`, and the constructor shape normalization this module relies on |
90
+ | `test/unit/spec/credentials/credentials.js` | Jest unit behavior of `Credentials`, using a mock SDK and fake timers |
91
+ | `test/unit/spec/credentials/token.js` | Unit behavior of `Token`, with platform-specific branches |
92
+ | `test/unit/spec/credentials/scope.js` | Table-driven unit tests of the three scope helpers |
93
+ | `test/integration/spec/credentials/credentials.js` | Integration behavior against provisioned test users: OrgId extraction, refresh, authorization-string config |
94
+ | `test/integration/spec/credentials/token.js` | Integration downscope, refresh, validate, and revoke against the live token service |
95
+ | `test/integration/spec/unit-browser/token.js` | Browser-runner token refresh with a `refreshCallback`, and previous-token revocation |
96
+ | `test/integration/spec/unit-browser/auth.js` | Browser-runner 401 reauthentication through the interceptor sibling, driven by `Credentials` |
97
+
98
+ ## Purpose and boundary
99
+
100
+ - **Responsibility:** hold the SDK's OAuth tokens and keep them usable. That means one long-lived
101
+ supertoken, a collection of scope-reduced user tokens derived from it, scheduled and on-demand
102
+ refresh, revocation of superseded tokens, and clearing everything on logout.
103
+ - **In scope:** the `Credentials` plugin and its derived `canAuthorize`, `canRefresh`, and
104
+ `isUnverifiedGuest`; the `Token` model; scope sort/filter/diff; the `OAuthError` hierarchy; OrgId
105
+ and user-id extraction from tokens; URL construction for authorize, logout, and third-party login;
106
+ the client-credentials grant; the `credentials` configuration keys and the identity-broker URLs
107
+ derived from them; persistence of credentials state through the storage decorators.
108
+ - **Out of scope:** attaching `Authorization` headers and replaying a 401 (the interceptor sibling);
109
+ the authorization-code, implicit, JWT-login, and SAML flows (separate authorization plugins that call `credentials.set`; no SAML-specific code exists in this module, and JWT refresh is delegated to the authorization plugin);
110
+ the storage adapters and stores themselves (storage sibling); identity-broker and identity URL
111
+ discovery (services siblings, which write `idbroker.url` and `identity.url` into configuration);
112
+ `WebexCore.logout` ordering (parent).
113
+ - **Consumers:** the parent module, the interceptor sibling and both services siblings, and, outside
114
+ the package, the authorization, mercury, metrics, user, encryption, team, support, meetings, and
115
+ contact-center plugins. All of them call into the contract `webex-core-credentials`.
116
+
117
+ ## Structure and key files
118
+
119
+ | Path | Responsibility |
120
+ | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
121
+ | `src/lib/credentials/credentials.js` | The `Credentials` plugin. The only place that decides which token to hand out, when to refresh, and what to clear |
122
+ | `src/lib/credentials/token.js` | The `Token` model. The only place that talks to the token, scope-reduction, and revoke endpoints for a specific token |
123
+ | `src/lib/credentials/grant-errors.js` | `OAuthError`, six subclasses, and the `select` lookup. The error vocabulary for every grant request in this module |
124
+ | `src/lib/credentials/scope.js` | Pure string helpers over space-separated scope lists; the canonical ordering used as the collection index |
125
+ | `src/lib/credentials/token-collection.js` | The user-token collection, keyed by sorted `scope` |
126
+ | `src/lib/credentials/index.js` | Registers the plugin under the name `credentials` and exports the module's public names |
127
+ | `src/credentials-config.js` | The `CredentialsConfig` state class: settable keys with environment fallbacks, and derived identity-broker URLs |
128
+
129
+ ## Public surface
130
+
131
+ | Surface | Contract | Consumer | Compatibility commitment | Source |
132
+ | --- | --- | --- | --- | --- |
133
+ | `webex.credentials` plugin instance | `webex-core-credentials` | Every plugin that authorizes requests | Registered by name `credentials`; `canAuthorize` and `canRefresh` are proxied onto the SDK object | `src/lib/credentials/index.js` |
134
+ | `getUserToken(scope?)` | `webex-core-credentials` | Interceptor sibling, mercury, encryption, metrics, meetings and others | Resolves a `Token` for the requested scope, downscoping on demand; resolves only after pending storage load and any in-flight refresh | `src/lib/credentials/credentials.js` |
135
+ | `refresh()`, `invalidate()` | `webex-core-credentials` | Interceptor sibling, parent logout | `refresh` replaces the supertoken and re-derives user tokens; `invalidate` clears local tokens without a network revoke | `src/lib/credentials/credentials.js` |
136
+ | `getClientToken(options?)` | `webex-core-credentials` | User and support plugins, and the services siblings | Returns an uncached client-credentials token | `src/lib/credentials/credentials.js` |
137
+ | `buildLoginUrl`, `buildLogoutUrl`, `buildThirdPartyLoginUrl` | `webex-core-credentials` | Authorization plugins and applications | Pure string builders; no navigation side effect | `src/lib/credentials/credentials.js` |
138
+ | `getOrgId`, `getUserId`, `extractOrgIdFromJWT`, `extractOrgIdFromUserToken`, `extractUserIdFromToken` | `webex-core-credentials` | Contact-center, user, metrics, and services-v2 code | Throw when the identifier cannot be determined | `src/lib/credentials/credentials.js` |
139
+ | `canAuthorize`, `canRefresh`, `isUnverifiedGuest`, `ready`, `isRefreshing`, `supertoken`, `userTokens` | `webex-core-credentials` | Interceptor sibling, authorization plugins | Observable ampersand properties; change events are emitted on the plugin | `src/lib/credentials/credentials.js` |
140
+ | `Token` | `webex-core-credentials` | Authorization plugins, tests, `Credentials` | Constructed from an object or access-token string; throws without an access token | `src/lib/credentials/token.js` |
141
+ | `grantErrors` | `webex-core-credentials` | Authorization plugins | Maps OAuth `error` strings to subclasses; unknown strings map to the base `OAuthError` | `src/lib/credentials/grant-errors.js` |
142
+ | `filterScope`, `sortScope` | `webex-core-credentials` | Authorization plugins, tests | Pure functions over space-separated scope strings; `diffScopes` is exported from its file but not from the module index | `src/lib/credentials/scope.js` |
143
+ | `CredentialsConfig` and the `credentials` config keys | `webex-core-credentials` | Parent defaults, every caller passing `config.credentials` | Keys and environment fallbacks listed in the configuration key table below | `src/credentials-config.js` |
144
+
145
+ Every row routes to `webex-core-credentials` in `contract_catalog.definitions`, the single contract
146
+ this module provides. It requires `http-core-sdk` (through the parent's `webex.request`),
147
+ `webex-common-js-api`, `common-timers-sdk`, `idbroker-oauth-service`, `ampersand-state-library`, and,
148
+ through the storage sibling, `storage-adapter-spec-suite`. The native source for the package surface
149
+ is `package.json` main and `src/index.js`; no signature is copied here.
150
+
151
+ Configuration keys. The module reads configuration only from `config.credentials` (an instance of `CredentialsConfig`)
152
+ and from environment variables evaluated when `src/credentials-config.js` is first imported. There
153
+ are no feature flags.
154
+
155
+ | Key | Kind | Environment fallbacks, in order | Notes |
156
+ | --- | --- | --- | --- |
157
+ | `idbroker.url` | prop | `IDBROKER_BASE_URL`, then the production broker host | Default object is built per instance; base for every derived broker URL |
158
+ | `identity.url` | prop | `IDENTITY_BASE_URL`, then the production identity host | Base for `setPasswordUrl` |
159
+ | `authorizationString` | prop | `WEBEX_AUTHORIZATION_STRING`, `AUTHORIZATION_STRING` | When set, `Credentials` overwrites `client_id`, `redirect_uri`, `scope`, and `authorizeUrl` from it on the first config change |
160
+ | `authorizeUrl` | prop | `WEBEX_AUTHORIZE_URL`, else `IDBROKER_BASE_URL` plus the authorize path | Fixed string at import time; not derived from `idbroker.url` |
161
+ | `client_id` | prop | `WEBEX_CLIENT_ID`, `COMMON_IDENTITY_CLIENT_ID`, `CLIENT_ID` | Required for downscope and refresh |
162
+ | `client_secret` | prop | `WEBEX_CLIENT_SECRET`, `COMMON_IDENTITY_CLIENT_SECRET`, `CLIENT_SECRET` | Enables Node-side refresh and every revocation; sent as HTTP Basic credentials |
163
+ | `redirect_uri` | prop | `WEBEX_REDIRECT_URI`, `COMMON_IDENTITY_REDIRECT_URI`, `REDIRECT_URI` | Sent on refresh and as logout `goto` |
164
+ | `scope` | prop | `WEBEX_SCOPE`, `WEBEX_SCOPES`, `COMMON_IDENTITY_SCOPE`, `SCOPE` | Upper bound for downscoping |
165
+ | `cisService` | prop | none; default `webex` | Declared but not read by `Credentials`; see Pitfalls |
166
+ | `activationUrl`, `generateOtpUrl`, `validateOtpUrl`, `logoutUrl`, `thirdPartyLoginUrl`, `setPasswordUrl` | derived, uncached | none | Recomputed on each read from `idbroker.url` or `identity.url` |
167
+ | `tokenUrl`, `revokeUrl` | derived, uncached | `TOKEN_URL`, `REVOKE_URL` override the derived value | Used by every grant and revoke request |
168
+ | `refreshCallback` | extra property | none | Browser refresh hook `(webex, token) => Promise<object>`; makes browser tokens refreshable |
169
+ | `jwtRefreshCallback` | extra property | none | JWT-mode refresh hook `(webex) => Promise<jwt>`; makes `canRefresh` true unconditionally |
170
+
171
+ ## Dependencies
172
+
173
+ | Dependency | Why it is required | Failure behavior |
174
+ | --- | --- | --- |
175
+ | `webex.request` (http-core request pipeline through the parent; see the http-core spec) | Every token, downscope, revoke, and client-credentials call. A transport failure resolves as `statusCode: 0` and the status interceptor converts it to a rejection | Rejections propagate; only HTTP 400 responses are re-mapped to grant errors, everything else is passed through unchanged |
176
+ | Common utilities (`oneFlight`, `whileInFlight`, `tap`, `makeStateDataType`, `encodeState`, `base64`, `Exception`, `inBrowser`; see the common spec) | De-duplication, the in-flight flag, state-data typing for `Token`, OAuth state encoding, base64url decoding, the error base class, platform detection | Load-time dependency |
177
+ | Common timers (`safeSetTimeout`; see the common-timers spec) | Token expiry flag and refresh scheduling; the returned handle is the platform timer handle and is not keeping a Node process alive | Handle is cancelled with `clearTimeout`; a pending timer is not cancelled when its owner is dropped |
178
+ | Storage sibling (`@persist`, `@waitForValue`, bounded store) | Persist state on change, restore at startup, and hold token-dependent methods until restore has been attempted | Restore failures other than not-found are logged and rejected by the decorator; `waitForValue` blocks the decorated methods until then |
179
+ | `webex.internal.metrics` (code only) | Submits `JS_SDK_CREDENTIALS_DOWNSCOPE_FAILED` and `JS_SDK_CREDENTIALS_TOKEN_REFRESH_SCOPE_MISMATCH` | Called without a guard; a missing metrics plugin makes those two paths throw |
180
+ | `webex.internal.services` (code only) | `refresh` calls `updateCredentialsConfig` before refreshing so broker URLs reflect the service catalog | Guarded by an existence check; skipped when services is absent |
181
+ | `webex.authorization.requestAccessTokenFromJwt` (code only) | JWT-mode refresh delegates the token exchange | Unguarded; throws if the authorization plugin is absent |
182
+ | `jsonwebtoken` (code only) | `jwt.decode` for the OrgId `realm` claim | Decode only, signature is never verified; a non-JWT yields a thrown error |
183
+ | `lodash`, `querystring`, `url` (code only) | Cloning, string and set helpers, query-string building, authorization-string parsing | Load-time dependency |
184
+ | `ampersand-state`, `ampersand-collection` (code only) | `Token`, `Credentials`, and `CredentialsConfig` are state classes; `TokenCollection` is a collection | Load-time dependency |
185
+
186
+ ## Requirements
187
+
188
+ | ID | WHAT | WHY | Source evidence | Test or example evidence | Assumptions or gaps | Confidence |
189
+ | --- | --- | --- | --- | --- | --- | --- |
190
+ | `MOD-001` | `Token` construction throws `` `access_token` is required`` when no access token is present; a bare string is accepted as the access token | A token object with no secret can never authorize anything, so it fails at the point of creation | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` | none | Present |
191
+ | `MOD-002` | `Token` splits an access token written as `<type> <token>` into `token_type` and `access_token` when no `token_type` is supplied; `token_type` otherwise defaults to `Bearer` | Tokens arrive both as full header values and as bare strings; the unit tests cover both forms | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/unit/spec/credentials/credentials.js` | none | Present |
192
+ | `MOD-003` | Token `expires` and `refresh_token_expires` are computed as `now + *_in * 1000` when only the `*_in` form is supplied; `scope` is stored alphabetized | The service returns relative lifetimes while the model compares absolute times; scope is the collection index and must be deterministic | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` | Gap: an explicit `expires` taking precedence over `expires_in` is not asserted | Present |
193
+ | `MOD-004` | `isExpired` is a derived flag backed by a private boolean that a one-shot timer flips at `expires`; a token constructed already past `expires` is expired immediately | Avoids `cache: false` on a derived property, per the in-source comment | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` | Gap: the timer is never cancelled and `_isExpired` is never reset when `expires` is later extended | Present |
194
+ | `MOD-005` | `canAuthorize` is true iff an access token exists and the token is not expired; `canDownscope` additionally requires `client_id` in configuration | A token must not be presented, or used to mint children, after it has lapsed | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` | none | Present |
195
+ | `MOD-006` | `Token.canRefresh` requires a refresh token plus `refreshCallback` in a browser build, or plus `client_secret` in Node | Not stated in code or tests. Code shows only that the browser delegates to a host callback and Node uses the client secret | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/integration/spec/unit-browser/token.js` | WHY not stated in code or tests. The two platform branches only run under their own runner | Weak |
196
+ | `MOD-007` | `toString` returns `<token_type> <access_token>` and throws `cannot stringify Token` when either is missing | The result is used verbatim as the `Authorization` header value | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` | none | Present |
197
+ | `MOD-008` | `Token.downscope` rejects when the token is expired, cannot downscope, requests a scope outside `config.scope`, or requests a scope equal to the full configured scope; otherwise it POSTs a scope-reduction grant without an auth header and returns a new `Token` carrying the sorted requested scope | The service answers only `invalid scope`, which misleads when the whole set is the problem, so the module reports the cause itself | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/integration/spec/credentials/token.js` | Gap: the success path's response mapping is asserted only through the scope sort and the live integration test; the equal-to-full-scope rejection is covered only by the integration test | Present |
198
+ | `MOD-009` | `Token.downscope` calls are de-duplicated per scope string | Not stated in code or tests | `src/lib/credentials/token.js` | none found | WHY not stated in code or tests. Gap: no test issues two concurrent downscopes | Weak |
199
+ | `MOD-010` | `Token.refresh` throws `Not enough information available to refresh this access token` when `canRefresh` is false | Not stated in code or tests | `src/lib/credentials/token.js` | none found | WHY not stated in code or tests. Gap: the throw is untested. Note it is a synchronous throw, not a rejection | Weak |
200
+ | `MOD-011` | In Node, `Token.refresh` POSTs a `refresh_token` grant to the token URL with the client id and secret as Basic credentials and `shouldRefreshAccessToken: false`; in a browser it awaits `config.refreshCallback(webex, token)` | Not stated in code or tests (including the reason for `shouldRefreshAccessToken: false`) | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/integration/spec/unit-browser/token.js` | WHY not stated in code or tests. The request shape (form fields, auth) is not asserted | Weak |
201
+ | `MOD-012` | A refresh result without a `refresh_token` inherits the current token's `refresh_token`, `refresh_token_expires`, and `refresh_token_expires_in` | The identity service does not send a new refresh token on refresh, per the in-source comment | `src/lib/credentials/token.js` | `test/integration/spec/credentials/token.js` | Gap: no unit test pins the inheritance | Present |
202
+ | `MOD-013` | `Token.refresh` rejects with `new token matches current token` when the service returns the same access token, and logs the old and new token values at error level unless `NODE_ENV` is `production` | Identical tokens indicate a service defect; the values are logged for diagnosis outside production only | `src/lib/credentials/token.js` | none found | Gap: untested. See the security pitfall | Present |
203
+ | `MOD-014` | After a refresh, the new `Token` records the old one as `previousToken` and keeps the old scope; the next refresh revokes the older `previousToken` first | Two valid tokens overlap so that a request in flight with the old token is not cut off | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/integration/spec/unit-browser/token.js` | The revoke call is neither awaited nor error-handled | Present |
204
+ | `MOD-015` | `Token.revoke` resolves without a request when the token is expired, cannot authorize, or no `client_secret` is configured; otherwise it POSTs to the revoke URL and, on success, unsets `access_token`, `expires`, `expires_in`, and `token_type` while keeping the refresh-token fields | The revoke endpoint requires client credentials, and the refresh token must survive for later refresh | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js`, `test/integration/spec/credentials/token.js` | Browsers never revoke; the in-source comment records this as a known limitation | Present |
205
+ | `MOD-016` | A non-400 failure from a grant, refresh, or revoke call is re-rejected unchanged; a 400 is converted to the matching grant-error subclass built from the underlying response | The unit test selects the error class from the OAuth `error` string, so callers can branch on class | `src/lib/credentials/token.js`, `src/lib/credentials/grant-errors.js` | `test/unit/spec/credentials/credentials.js` | Gap: `processGrantError` itself has no direct test; the one assertion constructs the error class by hand | Present |
206
+ | `MOD-017` | `grantErrors.select` returns the subclass for `invalid_request`, `invalid_client`, `invalid_grant`, `unauthorized_client`, `unsupported_grant_type`, and `invalid_scope`, and the base `OAuthError` for anything else | Not stated in code or tests; only the `select` fallback to the base class is code-evident | `src/lib/credentials/grant-errors.js` | `test/unit/spec/credentials/credentials.js` | WHY not stated in code or tests. Gap: only `invalid_request` is exercised | Weak |
207
+ | `MOD-018` | `OAuthError` exposes `error`, `errorDescription`, and `errorUri` as enumerable properties and the source response as a non-enumerable `res`; its message is the error description | Not stated in code or tests (including why `res` is non-enumerable) | `src/lib/credentials/grant-errors.js` | none found | WHY not stated in code or tests. Gap: untested | Weak |
208
+ | `MOD-019` | `sortScope` returns an alphabetized space-joined string and `''` for empty input; `filterScope` removes one or several scopes then sorts; `diffScopes` returns the sorted items of the first list absent from the second | Scope strings are compared and indexed as strings, so their order must be canonical | `src/lib/credentials/scope.js` | `test/unit/spec/credentials/scope.js` | The spec file also imports a helper that does not exist in the source; it is unused | Present |
209
+ | `MOD-020` | `TokenCollection` indexes user tokens by `scope` | `getUserToken` looks a child token up by its sorted scope | `src/lib/credentials/token-collection.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
210
+ | `MOD-021` | `Credentials` accepts a supertoken as a string, as `access_token`, or under `authorization` or `authorization.supertoken`; anything with an `expires` schedules a refresh | The unit tests enumerate token strings at seven nested paths in both `ST` and `Bearer ST` forms | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
211
+ | `MOD-022` | On the first `change:config`, a non-empty `authorizationString` overwrites `client_id`, `redirect_uri`, `scope`, and `authorizeUrl`, the last as the string before its `?` | The developer portal hands out one authorization string that carries all four values | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js`, `test/integration/spec/credentials/credentials.js` | The listener is registered once; later config changes are not re-parsed | Present |
212
+ | `MOD-023` | `canRefresh` is true whenever `jwtRefreshCallback` is configured, else follows the supertoken; `canAuthorize` is true when the supertoken can authorize or `canRefresh` is true | In JWT mode only the consumer can mint a token, so the SDK must assume it can | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Gap: the `jwtRefreshCallback` branch has no test in this package | Present |
213
+ | `MOD-024` | `buildLoginUrl` defaults `response_type` to `token` for client type `public` and `code` otherwise, forces `client_id`, `redirect_uri`, and `scope` from configuration, requires `state` to be an object, and base64url-encodes a non-empty state, omitting an empty one | State must survive the redirect; configuration, not the caller, is the source of identity | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Gap: the `public` to `token` default is untested, and a caller-supplied `scope` is silently replaced | Present |
214
+ | `MOD-025` | `buildLogoutUrl` appends `cisService` and `goto` and lets caller options override both | Not stated in code or tests; the unit tests show a `token` parameter and a `goto` override | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | WHY not stated in code or tests. The `cisService` value comes from an undeclared `service` key; see Pitfalls | Weak |
215
+ | `MOD-026` | `buildThirdPartyLoginUrl` requires `oauth2provider` and `returnURL`, validates `state`, and builds a query on `thirdPartyLoginUrl` | The in-source comment marks both options required for the social-provider sign-in | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
216
+ | `MOD-027` | `getOrgId` tries the JWT `realm` claim first, then the third underscore-separated section of a user token, and throws if neither works | Client-authenticated tokens are JWTs; user tokens embed the org in their text | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js`, `test/integration/spec/credentials/credentials.js` | The JWT is decoded, never signature-verified | Present |
217
+ | `MOD-028` | `getUserId` returns `cis_uuid` from the first of the supertoken then user tokens whose payload carries one, and throws otherwise | The code and tests show a supertoken-then-user-tokens search order; no rationale is stated | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
218
+ | `MOD-029` | `isUnverifiedGuest` is true iff the supertoken's middle section decodes to a payload with `user_type` equal to `guest`; any parse failure yields false | The in-source comment notes that the non-guest token is formatted differently, so parse failures are expected | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
219
+ | `MOD-030` | `getUserToken` defaults its scope to the supertoken's scope minus `spark:kms`, sorts the scope, returns the supertoken when the scope equals its own, otherwise the cached user token, otherwise downscopes and caches | Not stated in code or tests; the unit test asserts that the default scope omits `spark:kms` | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | WHY for omitting `spark:kms` not stated in code or tests | Weak |
220
+ | `MOD-031` | `getUserToken` rejects with `Current state cannot produce an access token` when `canAuthorize` is false | After logout no token may be returned | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
221
+ | `MOD-032` | `getUserToken` waits for the storage restore attempt and, while `isRefreshing` is true, for the next `change:isRefreshing` before choosing a token; concurrent calls for one scope share a flight | A caller must not receive a token a refresh is about to supersede | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Gap: the wait on storage restore has no test here | Present |
222
+ | `MOD-033` | When downscoping fails, `Credentials.downscope` logs a warning, submits the downscope-failed metric with the requested scope and reason, and resolves a token copied from the supertoken | The SDK stays usable when the scope-reduction endpoint is unavailable, at the cost of broader privileges | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | The fallback ignores the requested scope when the supertoken has its own; see Pitfalls | Present |
223
+ | `MOD-034` | `refresh` is serialized per instance, sets `isRefreshing` for its duration, delegates to `jwtRefreshCallback` then the authorization plugin in JWT mode, and otherwise refreshes the supertoken | One refresh at a time prevents refresh-token races and concurrent mint storms | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Gap: the JWT branch is untested here, and `isRefreshing` toggling is asserted only indirectly | Present |
224
+ | `MOD-035` | After a supertoken refresh, `refresh` stores the new supertoken, clears the old timer, warns and submits a metric when configured scopes are missing from the supertoken, downscopes each existing user token to its still-valid scope, revokes the old one, swaps it in, and reschedules | Child tokens must be re-derived from the new supertoken so none outlive the old grant | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | The reschedule assertion compares against an undefined `expires`, so it does not prove the argument | Present |
225
+ | `MOD-036` | An `OAuthError` from the supertoken refresh removes the supertoken and all user tokens, triggers `client:InvalidRequestError` on the SDK object, and rethrows | An invalid refresh token is unrecoverable and the application needs the chance to log the user out | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | The test stubs `unset` and asserts only inside `catch`; user-token removal is unasserted | Present |
226
+ | `MOD-037` | `scheduleRefresh` refreshes immediately when the time has passed, otherwise sets one timer for a random 60 to 90 percent of the remaining lifetime | The source documents a 60 to 90 percent window ahead of expiry; the reason for the randomization is not stated in code or tests | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | WHY for randomization not stated in code or tests. The result of the immediate or timed `refresh()` is not observed | Weak |
227
+ | `MOD-038` | `invalidate` clears the refresh timer, unsets the supertoken, and removes every user token, logging and continuing on individual failures; it makes no network call | The code logs and continues on each failure, so invalidate does not stop part-way | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none | Present |
228
+ | `MOD-039` | `getClientToken` POSTs a `client_credentials` grant, default scope `webexsquare:admin`, with Basic client credentials and `shouldRefreshAccessToken: false`, returns a `Token`, and does not cache it; 400 responses map to grant errors | The source comment says such tokens have limited use and are deliberately not cached | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | The 400 branch is untested | Present |
229
+ | `MOD-040` | The whole `Credentials` state is persisted through the storage decorator on every change and restored at startup into the parent's `credentials` slot | Not stated in code or tests; the decorator persists and restores the state | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | WHY not stated in code or tests. The test asserts the write and the delete; restore at startup is not asserted here | Weak |
230
+ | `MOD-041` | `ready` becomes true when the SDK emits `loaded` | The session-flag comment says it becomes true once the loaded event fires | `src/lib/credentials/credentials.js` | none found | Gap: untested | Present |
231
+ | `MOD-042` | `CredentialsConfig` derives broker URLs uncached from `idbroker.url` and `identity.url`, with environment overrides for `tokenUrl` and `revokeUrl` | The in-source comment says URLs are updated when the identity broker changes | `src/credentials-config.js` | `test/unit/spec/credentials/credentials.js` | Gap: no direct test of the derived properties or the environment fallbacks | Present |
232
+ | `MOD-043` | `CredentialsConfig` allows extra properties | The in-source comment cites dynamic keys such as `jwtRefreshCallback` | `src/credentials-config.js` | `test/integration/spec/credentials/credentials.js` | The integration test sets a declared key only | Present |
233
+
234
+ ## Design overview
235
+
236
+ **Two layers with a clear split of knowledge.** `Token` knows how to turn itself into other tokens:
237
+ it holds the endpoints, the grant forms, and the rules for a single access token, and returns new
238
+ `Token` objects rather than mutating itself, apart from revocation. `Credentials` knows which tokens
239
+ exist and when to use them: it owns the one supertoken and the `userTokens` collection, decides
240
+ whether a request needs a downscope, and is the only holder of refresh scheduling, the refresh flag,
241
+ and logout clearing.
242
+
243
+ **One supertoken, many scope-reduced children.** The supertoken carries every scope the application
244
+ configured. `getUserToken` hands out either it or a child downscoped to a requested scope, caching
245
+ children by sorted scope string, which is why `sortScope` is applied on both write and read. A child
246
+ is cheap to derive and cannot be refreshed itself; after a supertoken refresh the module rebuilds
247
+ every child rather than refreshing them, revoking each old child.
248
+
249
+ **Expiry and refresh are timer-driven.** `Token` flips a private boolean at `expires` so its derived
250
+ `isExpired` property can stay cached; `Credentials` schedules a refresh at a randomized fraction of
251
+ the remaining lifetime. Neither timer is aware of the other, so a refresh can already be running when
252
+ a token flips to expired, which is why `getUserToken` waits on `isRefreshing`.
253
+
254
+ **Failure is absorbed where it can be.** A failed downscope falls back to the supertoken; a failed
255
+ revoke is logged; a failed removal during invalidate is logged. The one failure not absorbed is an
256
+ OAuth error on the supertoken refresh, which wipes all tokens and signals the application.
257
+
258
+ **Persistence is declarative.** `@persist('@')` on `initialize` writes the whole object after
259
+ changes settle and `@waitForValue('@')` holds token-dependent methods until the restore attempt has
260
+ finished. See Data, schema, and migration discipline.
261
+
262
+ ## Data flow and sequence coverage
263
+
264
+ The transport is HTTPS form-encoded POSTs (and one JSON POST in `validate`) made through
265
+ `webex.request` to the identity broker, plus in-process calls between plugins. Six operation groups
266
+ differ in actors, ordering, or outcome and are diagrammed separately. URL construction and OrgId or
267
+ user-id extraction are pure functions with no ordering or failure path beyond a thrown error and are
268
+ covered by the use-case table instead.
269
+
270
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
271
+ | --- | --- | --- | --- |
272
+ | Startup and restore | Construct `Credentials`, restore from storage, schedule refresh, mark ready | Diagram 1 | Storage not-found is tolerated; expired supertoken refreshes at once |
273
+ | Token resolution | `getUserToken(scope)` returns a token | Diagram 2 | Waits on restore and refresh; downscope failure falls back to the supertoken; unauthorizable state rejects |
274
+ | Supertoken refresh | Timer, interceptor, or caller calls `refresh()` | Diagram 3 | OAuth error clears all tokens and signals the application; revoke failure ignored |
275
+ | Token-level grants | `Token.downscope`, `Token.refresh`, `Token.revoke` | Diagram 4 | Non-400 passes through unchanged; 400 becomes a grant error; refresh throws synchronously when not capable; revoke is a no-op without a secret |
276
+ | Client credentials | `getClientToken` returns an uncached token | Diagram 4 | 400 mapped to a grant error, others pass through |
277
+ | Invalidate | Logout clears local tokens and timer | Diagram 5 | Each removal failure logged and skipped |
278
+
279
+ **Diagram 1. Startup and restore**
280
+
281
+ ```mermaid
282
+ sequenceDiagram
283
+ participant A as Application
284
+ participant W as SDK object
285
+ participant C as Credentials
286
+ participant S as Bounded storage
287
+ A->>W: construct with token shape
288
+ W->>C: initialize(attrs)
289
+ C->>C: set supertoken from attrs
290
+ opt supertoken has expires
291
+ C->>C: scheduleRefresh(expires)
292
+ end
293
+ C->>W: listen once for change:config
294
+ C->>W: listen once for loaded
295
+ W->>S: read stored state for the Credentials key
296
+ alt state found
297
+ S-->>W: stored supertoken and user tokens
298
+ W->>C: set restored values
299
+ else not found
300
+ S-->>W: not-found, ignored
301
+ end
302
+ W->>C: change:config (authorizationString parsed if present)
303
+ W->>C: loaded
304
+ C->>C: ready = true
305
+ ```
306
+
307
+ **Diagram 2. Token resolution**
308
+
309
+ ```mermaid
310
+ sequenceDiagram
311
+ participant I as Caller
312
+ participant C as Credentials
313
+ participant S as Storage
314
+ participant T as supertoken
315
+ I->>C: getUserToken(scope)
316
+ C->>S: wait for restore attempt
317
+ opt isRefreshing
318
+ C->>C: wait for next change:isRefreshing
319
+ end
320
+ alt canAuthorize is false
321
+ C-->>I: reject "Current state cannot produce an access token"
322
+ else scope equals supertoken scope
323
+ C-->>I: supertoken
324
+ else cached user token has an access token
325
+ C-->>I: cached token
326
+ else downscope
327
+ C->>T: downscope(scope) (request and grant errors in Diagram 4)
328
+ alt success
329
+ T-->>C: new Token
330
+ C->>C: add to userTokens
331
+ else failure
332
+ T-->>C: rejection
333
+ C->>C: warn and submit downscope-failed metric
334
+ C->>C: copy supertoken into a Token
335
+ end
336
+ C-->>I: token
337
+ end
338
+ ```
339
+
340
+ **Diagram 3. Supertoken refresh**
341
+
342
+ ```mermaid
343
+ sequenceDiagram
344
+ participant X as Timer or caller
345
+ participant C as Credentials
346
+ participant ST as supertoken
347
+ participant E as Token service
348
+ X->>C: refresh()
349
+ Note over C: concurrent calls share this flight, isRefreshing = true
350
+ alt jwtRefreshCallback configured
351
+ C->>X: jwtRefreshCallback(webex)
352
+ C->>C: authorization plugin requestAccessTokenFromJwt
353
+ else standard
354
+ C->>C: services.updateCredentialsConfig() if present
355
+ C->>ST: refresh()
356
+ ST->>E: refresh_token grant, or host refreshCallback in a browser
357
+ alt OAuth error
358
+ E-->>ST: 400 invalid_*
359
+ ST-->>C: grant error
360
+ C->>C: unset supertoken, remove all user tokens
361
+ C->>X: trigger client:InvalidRequestError, rethrow
362
+ else success
363
+ ST-->>C: new supertoken
364
+ C->>C: clear timer, store supertoken
365
+ opt configured scope missing from supertoken
366
+ C->>C: warn and submit scope-mismatch metric
367
+ end
368
+ loop each existing user token
369
+ C->>C: downscope to still-valid scope
370
+ C->>E: revoke old token (failure logged)
371
+ C->>C: replace in userTokens
372
+ end
373
+ C->>C: scheduleRefresh(new expires)
374
+ end
375
+ end
376
+ Note over C: isRefreshing = false on both outcomes
377
+ ```
378
+
379
+ **Diagram 4. Token-level grants and client credentials**
380
+
381
+ ```mermaid
382
+ sequenceDiagram
383
+ participant C as Caller
384
+ participant T as Token or Credentials
385
+ participant H as Host refreshCallback
386
+ participant E as Token service
387
+ C->>T: revoke()
388
+ alt expired, cannot authorize, or no client_secret
389
+ T-->>C: resolve, no request
390
+ else
391
+ T->>E: POST revoke (Basic client credentials)
392
+ alt success
393
+ E-->>T: ok
394
+ T->>T: unset access_token, expires, expires_in, token_type
395
+ T-->>C: resolve
396
+ else 400
397
+ E-->>T: 400 OAuth error body
398
+ T-->>C: reject with grant error
399
+ else non-400
400
+ E-->>T: other failure
401
+ T-->>C: reject unchanged
402
+ end
403
+ end
404
+ C->>T: downscope(scope)
405
+ alt expired, no client_id, scope outside config, or scope equals full config scope
406
+ T-->>C: reject with Error
407
+ else
408
+ T->>E: POST scope-reduction grant, no auth header
409
+ alt success
410
+ E-->>T: token body
411
+ T-->>C: new Token with sorted scope
412
+ else 400
413
+ E-->>T: 400 OAuth error body
414
+ T-->>C: reject with grant error
415
+ else non-400
416
+ E-->>T: other failure
417
+ T-->>C: reject unchanged
418
+ end
419
+ end
420
+ C->>T: Token.refresh()
421
+ alt canRefresh is false
422
+ T-->>C: throw synchronously "Not enough information available to refresh this access token"
423
+ else browser build
424
+ T->>H: refreshCallback(webex, token)
425
+ alt no object produced
426
+ H-->>T: falsy or non-object
427
+ T-->>C: reject "refreshCallback() did not produce an object"
428
+ else object produced
429
+ H-->>T: token fields
430
+ end
431
+ else Node build
432
+ T->>E: POST refresh_token grant (Basic client credentials)
433
+ alt 400
434
+ E-->>T: 400 OAuth error body
435
+ T-->>C: reject with grant error
436
+ else non-400
437
+ E-->>T: other failure
438
+ T-->>C: reject unchanged
439
+ else success
440
+ E-->>T: token body
441
+ end
442
+ end
443
+ opt a result was obtained
444
+ alt same access token as current
445
+ T-->>C: reject "new token matches current token"
446
+ else different
447
+ T->>T: inherit refresh_token fields if absent, set previousToken
448
+ T->>T: revoke older previousToken (not awaited)
449
+ T-->>C: new Token
450
+ end
451
+ end
452
+ C->>T: getClientToken(options)
453
+ T->>E: POST client_credentials grant (Basic client credentials)
454
+ alt success
455
+ E-->>T: token body
456
+ T-->>C: new Token, not cached
457
+ else 400
458
+ E-->>T: 400 OAuth error body
459
+ T-->>C: reject with grant error
460
+ else non-400
461
+ E-->>T: other failure
462
+ T-->>C: reject unchanged
463
+ end
464
+ ```
465
+
466
+ **Diagram 5. Invalidate**
467
+
468
+ ```mermaid
469
+ sequenceDiagram
470
+ participant W as WebexCore.logout
471
+ participant C as Credentials
472
+ participant S as Bounded storage
473
+ W->>S: clear stores
474
+ W->>C: invalidate()
475
+ C->>C: clearTimeout(refreshTimer), unset it
476
+ C->>C: unset supertoken (failure logged)
477
+ loop while userTokens not empty
478
+ C->>C: remove first token (failure logged)
479
+ end
480
+ C-->>W: resolve
481
+ Note over C,S: change events trigger a debounced persist of the now-empty state
482
+ ```
483
+
484
+ ## Class and component relationships
485
+
486
+ ```mermaid
487
+ classDiagram
488
+ class WebexPlugin
489
+ class Credentials["src/lib/credentials/credentials.js"] {
490
+ +supertoken Token
491
+ +userTokens TokenCollection
492
+ +isRefreshing boolean
493
+ +ready boolean
494
+ +refreshTimer handle
495
+ +getUserToken(scope) Promise
496
+ +refresh() Promise
497
+ +invalidate() Promise
498
+ +getClientToken(options) Promise
499
+ }
500
+ class Token["src/lib/credentials/token.js"] {
501
+ +access_token string
502
+ +refresh_token string
503
+ +expires number
504
+ +scope string
505
+ +previousToken Token
506
+ +downscope(scope) Promise
507
+ +refresh() Promise
508
+ +revoke() Promise
509
+ }
510
+ class TokenCollection["src/lib/credentials/token-collection.js"]
511
+ class GrantErrors["src/lib/credentials/grant-errors.js"]
512
+ class Scope["src/lib/credentials/scope.js"]
513
+ class CredentialsConfig["src/credentials-config.js"]
514
+ WebexPlugin <|-- Credentials
515
+ WebexPlugin <|-- Token
516
+ Credentials *-- Token : supertoken
517
+ Credentials *-- TokenCollection : userTokens
518
+ TokenCollection o-- Token : indexed by scope
519
+ Token --> Token : previousToken
520
+ Credentials ..> Scope : sort, filter, diff
521
+ Token ..> Scope
522
+ Token ..> GrantErrors : maps 400 responses
523
+ Credentials ..> GrantErrors : getClientToken
524
+ Credentials ..> CredentialsConfig : reads config
525
+ Token ..> CredentialsConfig
526
+ ```
527
+
528
+ `Token` and `Credentials` both extend the shared plugin base from the parent, so each reaches
529
+ configuration, the logger, and the SDK object through the same `config`, `logger`, and `webex`
530
+ accessors. A `Token` finds its SDK object through its parent or its collection, as `src/lib/webex-plugin.js` resolves it.
531
+
532
+ ## Use cases and flows
533
+
534
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
535
+ | --- | --- | --- | --- | --- |
536
+ | `UC-001` | Application with an existing access token | Construct the SDK with a token string or object; `Credentials` stores it as the supertoken and schedules a refresh if it has an expiry | A token with no access token is rejected at construction | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
537
+ | `UC-002` | Interceptor sibling | `getUserToken()` returns a token without the key-management scope; the interceptor writes `toString()` into the header | After logout the call rejects and no header is written | `src/lib/credentials/credentials.js`, `src/interceptors/auth.js`, `test/unit/spec/credentials/credentials.js` |
538
+ | `UC-003` | Encryption or mercury plugin | `getUserToken('spark:kms')` gets a child with only that scope, cached for later calls | A downscope failure returns the supertoken and reports a metric | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
539
+ | `UC-004` | Interceptor sibling on a 401 | When `canRefresh` is true it calls `refresh()` and replays the request; concurrent 401s share one refresh | An OAuth error ends the session and triggers `client:InvalidRequestError` | `src/interceptors/auth.js`, `test/integration/spec/unit-browser/auth.js` |
540
+ | `UC-005` | Timer | At 60 to 90 percent of the supertoken lifetime `refresh()` runs; user tokens are rebuilt and old ones revoked | A revoke failure is logged and does not stop the replacement | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
541
+ | `UC-006` | Browser application with a login page | `buildLoginUrl({state})` returns the broker authorize URL with encoded state; the caller navigates | `state` must be an object | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
542
+ | `UC-007` | Application using a social provider | `buildThirdPartyLoginUrl({oauth2provider, returnURL})` returns the third-party login URL | A missing provider or return URL throws | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
543
+ | `UC-008` | Application logging out | `WebexCore.logout` clears storage then calls `invalidate()`; `buildLogoutUrl` produces the broker logout address | The invalidated instance cannot produce a token | `src/webex-core.js`, `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
544
+ | `UC-009` | Integrator in JWT mode | Supply `jwtRefreshCallback`; `refresh()` obtains a JWT from it and hands it to the authorization plugin | The SDK treats `canRefresh` as true regardless of the supertoken | `src/lib/credentials/credentials.js` |
545
+ | `UC-010` | Service account | `getClientToken({scope})` returns a fresh client-credentials token every time | A 400 becomes a grant error | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
546
+ | `UC-011` | Meetings or metrics plugin | `getOrgId()` returns the organization from the token | Throws when the token matches neither shape | `src/lib/credentials/credentials.js`, `test/unit/spec/credentials/credentials.js` |
547
+
548
+ ### Cross-boundary use-case flow
549
+
550
+ | Boundary | Transport | Ordering | Compatibility | Timeout and retry | Recovery |
551
+ | --- | --- | --- | --- | --- | --- |
552
+ | SDK to identity broker token endpoint (refresh, client credentials, scope reduction) | HTTPS form POST via `webex.request`; Basic client credentials on refresh and client credentials, none on scope reduction | One request per call; `Credentials.refresh` runs downscopes after the supertoken refresh settles and runs them in parallel | Grant types are `refresh_token`, `client_credentials`, and a scope-reduction URN | No timeout or retry here. Refresh, revoke, and client-credentials requests set `shouldRefreshAccessToken: false`; the scope-reduction request instead sets `addAuthHeader: false` | Failures reject; only refresh failures with an OAuth error trigger clearing |
553
+ | SDK to broker revoke endpoint | HTTPS form POST | After the replacement token exists | Revokes an access token with a type hint | None | Failure logged and ignored on the refresh path |
554
+ | SDK to host application | `refreshCallback` or `jwtRefreshCallback` | Called inside the refresh flight | Callback contract is `(webex, token)` or `(webex)` | Unbounded; the module imposes no timeout on the callback | Rejection or a falsy result rejects the refresh |
555
+ | SDK to authorization plugin | Direct method call in JWT mode | After the JWT callback resolves | Plugin must expose `requestAccessTokenFromJwt` | None | Rejection rejects the refresh |
556
+
557
+ ## Client state model
558
+
559
+ | State or slice | Owner | Initial state | Transition triggers | Reset or persistence boundary |
560
+ | --- | --- | --- | --- | --- |
561
+ | `supertoken` | `Credentials` | Unset, or the token passed at construction or restored from storage | Constructor input, authorization plugins calling `set`, successful `refresh`, `invalidate`, OAuth refresh failure | Persisted; cleared by `invalidate` and by OAuth refresh failure |
562
+ | `userTokens` | `Credentials` | Empty | `getUserToken` adds, `refresh` replaces, `invalidate` and OAuth refresh failure empty it | Persisted; the collection is keyed by sorted scope |
563
+ | `refreshTimer` | `Credentials` | Undefined | `scheduleRefresh` sets; `refresh` and `invalidate` clear | Session only; never persisted |
564
+ | `isRefreshing` | `Credentials` | `false` | Set by the refresh flight for its duration | Session only |
565
+ | `ready` | `Credentials` | `false` | SDK `loaded` event | Session only |
566
+ | `Token._isExpired` | each `Token` | `false`, or `true` if constructed past `expires` | One-shot timer at `expires` | Session only; never reset |
567
+ | `Token.previousToken` | each `Token` | Unset | Assigned on refresh; cleared when its revoke is requested | Session only |
568
+ | `config.credentials` | `CredentialsConfig` | Environment-derived defaults | Caller config, `authorizationString` parsing, services rewriting `idbroker`, `identity`, `authorizeUrl` | Not persisted; owned by the parent's config |
569
+
570
+ ## Business rules and invariants
571
+
572
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
573
+ | --- | --- | --- | --- | --- |
574
+ | `INV-001` | A `Token` always has an access token at construction | A token without a secret is meaningless | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` |
575
+ | `INV-002` | A token may authorize only while it has an access token and is not expired | Never present a lapsed or revoked token | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` |
576
+ | `INV-003` | A downscoped token's scope is a strict subset of the configured scope | Child tokens must narrow privilege, per the in-source rationale about unhelpful service errors | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` |
577
+ | `INV-004` | Scope strings used as an index or for comparison are always in sorted order | The collection and the supertoken short-circuit compare strings | `src/lib/credentials/scope.js`, `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/scope.js` |
578
+ | `INV-005` | See `MOD-012`: a refreshed token never loses its refresh token | The service never issues a new one on refresh | `src/lib/credentials/token.js` | none found |
579
+ | `INV-006` | See `MOD-015`: revocation never removes the refresh-token fields | The session must remain refreshable after its access token is revoked | `src/lib/credentials/token.js` | `test/unit/spec/credentials/token.js` |
580
+ | `INV-007` | See `MOD-013`: a refresh never yields an unchanged access token | Would defeat revocation of the previous token | `src/lib/credentials/token.js` | none found |
581
+ | `INV-008` | After `invalidate`, `getUserToken` rejects | Logout must prevent further token handout | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` |
582
+ | `INV-009` | At most one refresh of a given `Credentials` instance runs at a time, and `getUserToken` does not complete while it runs | Prevents handing out a token about to be revoked | `src/lib/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` |
583
+
584
+ ## Concurrency and reactive flow
585
+
586
+ - **Execution model:** promise-based on the host event loop with two kinds of timers (per-token
587
+ expiry flag, one refresh timer per `Credentials`) and ampersand change events. No threads or
588
+ workers.
589
+ - **Ordering guarantees:** `refresh` fully settles the supertoken, then the user-token rebuild, then
590
+ schedules the next refresh. User-token rebuilds run in parallel with each other. `getUserToken`
591
+ completes after the refresh flag falls, so it observes the post-refresh state. The persisted write
592
+ is debounced to the next tick, so it reflects the state after one `set` has finished.
593
+ - **Idempotency and retry:** `Credentials.refresh`, `Credentials.invalidate`, `Token.refresh`, and
594
+ `Token.revoke` return the in-progress promise to concurrent callers; `Token.downscope` and
595
+ `getUserToken` do so per scope. There is no retry anywhere; a failed refresh is retried only by the
596
+ next 401 replay or the next timer.
597
+ - **Shared-state protection:** the single-flight decorators and `isRefreshing` serialize refresh;
598
+ nothing locks `userTokens`, so a `getUserToken` running before a refresh began can still add a token
599
+ after it. The `refreshTimer` is a single slot; `scheduleRefresh` does not cancel a handle already
600
+ in it.
601
+ - **Blocking restrictions:** the host `refreshCallback` and `jwtRefreshCallback` run inside the
602
+ refresh flight, so a slow callback holds `getUserToken` for every scope. Nothing times them out.
603
+
604
+ ## Data, schema, and migration discipline
605
+
606
+ | Store or schema | Owned entities or keys | Source of truth | Migration and compatibility rule |
607
+ | --- | --- | --- | --- |
608
+ | Bounded plugin store, namespace `Credentials`, key `@` | The serialized plugin: `supertoken` and each user token with every stored `Token` property, including `access_token` and `refresh_token` | `src/lib/credentials/credentials.js`, `src/lib/storage/make-webex-plugin-store.js` | None. Restore feeds the stored object to the parent's `credentials` slot, so the persisted shape is the current prop set and must stay readable by `initialize` |
609
+
610
+ Session properties (`isRefreshing`, `ready`, `refreshTimer`, `Token._isExpired`, `previousToken`) are
611
+ not serialized. The store walks the serialized object and drops empty arrays, and an entirely empty object
612
+ serializes to nothing; the unit test observes a not-found result after `invalidate`. There is no
613
+ retention limit, version marker, or backfill. Tokens are written in plain text (see Pitfalls); `WebexCore.logout` clears both
614
+ stores before `invalidate` runs.
615
+
616
+ ## State machine
617
+
618
+ **Credentials**
619
+
620
+ ```mermaid
621
+ stateDiagram-v2
622
+ [*] --> Unauthenticated
623
+ Unauthenticated --> Authenticated: supertoken set (constructor, plugin, restore)
624
+ Authenticated --> Refreshing: refresh() (timer, 401, caller)
625
+ Refreshing --> Authenticated: new supertoken and children stored
626
+ Refreshing --> Authenticated: refresh rejected, not an OAuth error
627
+ Refreshing --> Unauthenticated: OAuth error, tokens cleared, client:InvalidRequestError
628
+ Authenticated --> Unauthenticated: invalidate()
629
+ Refreshing --> Unauthenticated: invalidate()
630
+ ```
631
+
632
+ **Token**
633
+
634
+ ```mermaid
635
+ stateDiagram-v2
636
+ [*] --> Valid: access_token present, expires in future or unset
637
+ [*] --> Expired: constructed past expires
638
+ Valid --> Expired: expires timer fires
639
+ Valid --> Revoked: revoke() succeeds
640
+ Expired --> [*]: replaced by refresh or removed from store
641
+ Revoked --> [*]: replaced by refresh or removed from store
642
+ Valid --> [*]: replaced by refresh (previous token revoked at next refresh)
643
+ ```
644
+
645
+ Guards and rejected transitions: `refresh()` is rejected unless `canRefresh`; `downscope` is rejected
646
+ while expired or without a client id; `revoke` is a silent no-op while expired, revoked, or without a
647
+ client secret. `Expired` is one-way: the flag is never cleared on the same object, so recovery always
648
+ produces a new `Token`. A revoked token keeps its refresh-token fields and can still seed a
649
+ refresh. In the Credentials diagram the `Refreshing` flag is `isRefreshing`, and `Unauthenticated`
650
+ means `canAuthorize` is false.
651
+
652
+ ## Protocol and wire format
653
+
654
+ | Message or frame | Version | Producer or serializer | Consumer or parser | Compatibility and ordering rule |
655
+ | --- | --- | --- | --- | --- |
656
+ | Authorize URL query (`response_type`, `client_id`, `redirect_uri`, `scope`, `state`) | OAuth 2.0 | `src/lib/credentials/credentials.js` | The identity broker | `state` is base64url-encoded JSON, omitted when empty; the identity broker echoes it back |
657
+ | Third-party login URL (`oauth2provider`, `returnURL`, `state`) | Broker-specific | `src/lib/credentials/credentials.js` | The identity broker | State encoded identically to the authorize URL |
658
+ | Logout URL (`cisService`, `goto`, plus caller options) | Broker-specific | `src/lib/credentials/credentials.js` | The identity broker | Caller options override both defaults |
659
+ | Client-credentials grant form | OAuth 2.0 | `src/lib/credentials/credentials.js` | The identity broker | Form fields `grant_type`, `scope`, `self_contained_token`; client credentials in Basic auth |
660
+ | Refresh-token grant form | OAuth 2.0 | `src/lib/credentials/token.js` | The identity broker | Form fields `grant_type`, `redirect_uri`, `refresh_token`; client credentials in Basic auth |
661
+ | Scope-reduction grant form | Cisco extension (`urn:cisco:oauth:grant-type:scope-reduction`) | `src/lib/credentials/token.js` | The identity broker | Form fields `grant_type`, `token`, `scope`, `client_id`, `self_contained_token`; no auth header; the token travels in the body |
662
+ | Revoke form | OAuth 2.0 | `src/lib/credentials/token.js` | The identity broker | Form fields `token`, `token_type_hint`; client credentials in Basic auth |
663
+ | Token response body | OAuth 2.0 | The identity broker | `src/lib/credentials/token.js` | `expires_in` and `refresh_token_expires_in` seconds are converted to absolute millisecond timestamps |
664
+ | OAuth error body (`error`, `error_description`, `error_uri`) | OAuth 2.0 | The identity broker | `src/lib/credentials/grant-errors.js` | Interpreted only on HTTP 400 |
665
+ | Persisted `@` record | Unversioned | `src/lib/storage/make-webex-plugin-store.js` | `src/lib/credentials/credentials.js` | See Data, schema, and migration discipline |
666
+
667
+ The broker is an external service (`idbroker-oauth-service`); its endpoint specification is not in
668
+ this repository, so the field lists above are what this module sends and reads, not a copy of the
669
+ service contract.
670
+
671
+ ## Caller-visible failure modes
672
+
673
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
674
+ | --- | --- | --- | --- | --- |
675
+ | No access token at `Token` construction | Throws `` `access_token` is required`` | Fix the input | None | `src/lib/credentials/token.js` |
676
+ | `getUserToken` when nothing can authorize | Rejects `Current state cannot produce an access token` | Re-authenticate | Caller-owned | `src/lib/credentials/credentials.js` |
677
+ | Downscope of an expired or unconfigured token | Rejects with `cannot downscope expired access token` or `cannot downscope access token` | Treated by `Credentials` as a downscope failure and falls back | Supertoken fallback | `src/lib/credentials/token.js` |
678
+ | Requested scope outside configured scope | Rejects `new scope (...) is not subset of the available scopes (...)` | Fix the scope | Fallback for `getUserToken` | `src/lib/credentials/token.js` |
679
+ | Requested scope equals the full configured scope | Rejects `token: scope reduction requires a reduced scope` | Use the supertoken | Fallback for `getUserToken` | `src/lib/credentials/token.js` |
680
+ | `Token.refresh` without capability | Throws synchronously `Not enough information available to refresh this access token` | Check `canRefresh` first | None | `src/lib/credentials/token.js` |
681
+ | Browser refresh without a callback result | Rejects `token: refreshCallback() did not produce an object` | Fix the callback | Next 401 or timer | `src/lib/credentials/token.js` |
682
+ | Service returned the same access token | Rejects `new token matches current token` | Report a service defect | Next 401 or timer | `src/lib/credentials/token.js` |
683
+ | OAuth error on supertoken refresh | Grant error rethrown, tokens cleared, `client:InvalidRequestError` triggered | Log the user out | None | `src/lib/credentials/credentials.js`, `src/lib/credentials/grant-errors.js` |
684
+ | 400 from a token call | `OAuthError` subclass chosen by the `error` string | Branch on the class | Caller-owned | `src/lib/credentials/grant-errors.js` |
685
+ | Non-400 from a token call | The original request error | Handle as an HTTP error | Caller-owned | `src/lib/credentials/token.js` |
686
+ | `buildLoginUrl` with a non-object `state`, or `buildThirdPartyLoginUrl` without provider or return URL | Throws | Fix the input | None | `src/lib/credentials/credentials.js` |
687
+ | `getOrgId` on an unrecognized token | Throws `the provided token is not a valid format, token has N sections` or a JWT error | Handle absence | None | `src/lib/credentials/credentials.js` |
688
+ | `getUserId` with no usable token | Throws `could not extract the user ID from any available token` | Handle absence | None | `src/lib/credentials/credentials.js` |
689
+ | `Token.validate` in production | Throws `must not be used in production` | Do not call outside tests | None | `src/lib/credentials/token.js` |
690
+ | `toString` without a token | Throws `cannot stringify Token` | Check `canAuthorize` | None | `src/lib/credentials/token.js` |
691
+
692
+ ## Pitfalls and constraints
693
+
694
+ - **Token values reach the log outside production.** `Token.refresh` logs the current and new
695
+ access tokens at error level whenever `NODE_ENV` is not `production`. The only redaction
696
+ mechanism in this module is that environment check; nothing masks tokens elsewhere. `Token.toString`
697
+ returns the full header value and the downscope fallback logs the raw failure reason or response
698
+ body.
699
+ - **Tokens are persisted in plain text.** `@persist('@')` writes the access and refresh tokens of
700
+ the supertoken and every user token. Protection is entirely the storage adapter's. `client_secret` is
701
+ configuration, not a property of `Credentials`, so it is not persisted by this module.
702
+ - **`client_secret` is a deliberate Node-only secret.** It signs refresh, revoke, and client-credentials
703
+ calls as Basic credentials. In browser builds the secret is absent, so `Token.revoke` becomes a
704
+ silent no-op and refresh requires the host `refreshCallback`.
705
+ - **`buildLogoutUrl` reads an undeclared key.** It uses `config.service` for `cisService`, but
706
+ `CredentialsConfig` declares `cisService` and no `service`. With default configuration the
707
+ parameter is emitted empty; the unit tests pass because the mock SDK sets `service` explicitly.
708
+ - **`buildLoginUrl` mutates its argument and ignores caller scope.** It writes `client_id`,
709
+ `redirect_uri`, and `scope` onto the object passed in before cloning it, discarding any `scope` the
710
+ caller supplied. The `public` client type applies only when no options object is passed: an options
711
+ object without `clientType` yields `response_type: code`.
712
+ - **The downscope fallback may ignore the requested scope.** `Credentials.downscope` builds the
713
+ fallback as `{scope, ...supertoken.serialize()}`, so a supertoken with its own scope overrides the
714
+ requested one, and the cached child is then keyed under the supertoken's scope. It also passes
715
+ `{parent: this}` to `Promise.resolve` instead of to the `Token` constructor, where it has no effect;
716
+ the token gets its SDK object only once it joins `userTokens` (inferred from the `webex` resolution
717
+ in `src/lib/webex-plugin.js`, not exercised).
718
+ - **Refresh and expiry promises are fire-and-forget.** The timer callback and the already-expired
719
+ branch of `scheduleRefresh` call `refresh()` and drop the promise, and `Token.refresh` calls
720
+ `previousToken.revoke()` without awaiting it, so rejections from those paths are unobserved.
721
+ - **A stale refresh timer survives an OAuth failure.** The OAuth error path unsets the supertoken
722
+ but does not clear `refreshTimer`; if a manual refresh failed while the timer was still pending, the
723
+ timer later calls `refresh()` with no supertoken (inferred from the code; not exercised).
724
+ - **JWT mode does not reschedule.** The `jwtRefreshCallback` branch returns after the authorization
725
+ plugin sets the new supertoken; `scheduleRefresh` is called only from `initialize` and after a
726
+ standard refresh, so in JWT mode the next refresh is driven by a 401 replay, not a timer.
727
+ - **Expiry timers and `isExpired` never reverse.** Each `Token` arms a timer that is never cancelled,
728
+ and `_isExpired` is never reset. Extending `expires` on a live object does not un-expire it.
729
+ - **Metrics and authorization plugins are assumed present.** The downscope-failure and scope-mismatch
730
+ paths call `webex.internal.metrics` unguarded, and JWT-mode refresh calls the authorization plugin
731
+ unguarded.
732
+ - **Token JWT parsing is unverified.** `getOrgId` uses `jwt.decode`, which does not validate a
733
+ signature, so the result is only as trustworthy as the token source.
734
+ - **Configuration is read at specific moments.** Environment variables are read once when
735
+ `src/credentials-config.js` loads; `authorizeUrl` is a fixed string and does not follow later
736
+ `idbroker.url` changes except through `updateCredentialsConfig`. `Token` capability flags that
737
+ depend on configuration are not re-evaluated when configuration changes, per the in-source notes, so
738
+ `client_id`, `client_secret`, and `refreshCallback` must be set before a `Token` is created.
739
+ - **`Token.validate` is for tests.** It uses a non-production conversation endpoint and throws in
740
+ production; it is not part of any runtime flow.
741
+
742
+ ## Module-specific rules
743
+
744
+ - **Do:** apply `@oneFlight` outermost, then `@whileInFlight`, then `@waitForValue`, as `refresh`
745
+ does in `src/lib/credentials/credentials.js`; the order decides whether a second caller joins the
746
+ existing flight and whether the flag is raised before storage is ready.
747
+ - **Do:** pass scope strings through `sortScope` before comparing them or using them as a collection
748
+ index.
749
+ - **Do:** set `client_id`, `client_secret`, and `refreshCallback` before constructing a `Token`.
750
+ - **Do:** follow the existing pattern for client-authenticated token-endpoint calls in
751
+ `src/lib/credentials/token.js` and `src/lib/credentials/credentials.js`: Basic client credentials plus
752
+ `shouldRefreshAccessToken: false`.
753
+ - **Do not:** persist or log a token value outside a non-production branch.
754
+ - **Do not:** add a configuration key to `CredentialsConfig` that `Credentials` or `Token` does not
755
+ read; `cisService` is the existing example of this mismatch.
756
+ - **Do not:** call `Token.validate` from runtime code.
757
+
758
+ ## Export stability
759
+
760
+ | Export or entry point | Consumer | Stability | Versioning and deprecation rule | Declaration or API report |
761
+ | --- | --- | --- | --- | --- |
762
+ | `Credentials` | Parent, authorization plugins, tests | Consumed by sibling plugins; breaking changes to methods listed under Public surface break them | No deprecation mechanism in this module; the parent package version governs | `src/lib/credentials/index.js` |
763
+ | `Token` | Authorization plugins, tests | Same as above; constructor shape is relied on by tests and plugins | None in this module | `src/lib/credentials/index.js` |
764
+ | `grantErrors` | Authorization plugins | Class names and `select` are consumed by plugin code | None in this module | `src/lib/credentials/index.js` |
765
+ | `filterScope`, `sortScope` | Authorization plugins | Pure helpers consumed by plugins | None in this module | `src/lib/credentials/index.js` |
766
+ | Package entry re-exports | Application code through the package | Exactly `Credentials`, `filterScope`, `grantErrors`, `sortScope`, `Token` | Owned by the parent entry point | `src/index.js` |
767
+
768
+ No API report or type declaration exists for this module; the sources above are the declaration.
769
+ `diffScopes` is deliberately absent from the module and package exports.
770
+
771
+ ## Key design trade-off
772
+
773
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
774
+ | --- | --- | --- | --- |
775
+ | A failed downscope falls back to a copy of the supertoken | The SDK keeps working when the scope-reduction endpoint is unavailable | The request carries broader privilege than asked for; the fallback is reported only through a log and a metric | `src/lib/credentials/credentials.js` |
776
+ | Revocation is skipped without a client secret | No unauthenticated revoke attempt is made from browsers | Browser sessions never revoke; superseded tokens remain valid until they expire | `src/lib/credentials/token.js` |
777
+ | Expiry is a timer-set boolean, not a time comparison | The derived `isExpired` stays cached | Per-token timers that cannot be cancelled and a flag that cannot be reset | `src/lib/credentials/token.js` |
778
+ | A failed OAuth refresh wipes every token and signals the application instead of retrying | An unrecoverable session is surfaced promptly | A transient service error that happens to be reported as an OAuth error ends the session | `src/lib/credentials/credentials.js` |
779
+ | The previous token is revoked only at the next refresh | A request in flight with the old token is not cut off | Up to two valid access tokens exist per refresh cycle | `src/lib/credentials/token.js` |
780
+ | Child tokens are rebuilt, not refreshed, after a supertoken refresh | One refresh grant per cycle and no per-child refresh state | One downscope and one revoke per child per refresh | `src/lib/credentials/credentials.js` |
781
+
782
+ ## Verification
783
+
784
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
785
+ | --- | --- | --- | --- | --- |
786
+ | `MOD-001`, `INV-001` | Unit | `test/unit/spec/credentials/token.js` | `test/unit/spec/credentials/token.js` (missing token throws) | none |
787
+ | `MOD-002` | Unit | `test/unit/spec/credentials/token.js` | none found | The explicit `token_type` precedence is not asserted |
788
+ | `MOD-003` | Unit | `test/unit/spec/credentials/token.js` | none found | Explicit `expires` precedence is unasserted |
789
+ | `MOD-004` | Unit | `test/unit/spec/credentials/token.js` (fake timers) | `test/unit/spec/credentials/token.js` (already expired) | No test for extending `expires` |
790
+ | `MOD-005`, `INV-002` | Unit | `test/unit/spec/credentials/token.js` | `test/unit/spec/credentials/token.js` | none |
791
+ | `MOD-006` | Unit, Integration | `test/unit/spec/credentials/token.js`, `test/integration/spec/unit-browser/token.js` | `test/unit/spec/credentials/token.js` | Browser branch only under the browser runner |
792
+ | `MOD-007` | Unit | `test/unit/spec/credentials/token.js` | `test/unit/spec/credentials/token.js` | none |
793
+ | `MOD-008`, `INV-003` | Unit, Integration | `test/unit/spec/credentials/token.js`, `test/integration/spec/credentials/token.js` | `test/unit/spec/credentials/token.js` | Equal-to-full-scope rejection is integration only |
794
+ | `MOD-009` | none | none found | none found | No concurrent-downscope test |
795
+ | `MOD-010` | none | none found | none found | The synchronous throw is untested |
796
+ | `MOD-011` | Unit, Integration | `test/unit/spec/credentials/token.js`, `test/integration/spec/credentials/token.js` | none found | Request fields and Basic auth are not asserted |
797
+ | `MOD-012`, `INV-005` | Integration | `test/integration/spec/credentials/token.js` | none found | No unit test; relies on a live service |
798
+ | `MOD-013`, `INV-007` | none | none found | none found | The identical-token path and the production log branch are untested |
799
+ | `MOD-014` | Unit, Integration | `test/unit/spec/credentials/token.js`, `test/integration/spec/unit-browser/token.js` | none found | Revoke failure on the previous token is not tested |
800
+ | `MOD-015`, `INV-006` | Unit, Integration | `test/unit/spec/credentials/token.js`, `test/integration/spec/credentials/token.js` | `test/unit/spec/credentials/token.js` (three no-op cases) | The request payload is not asserted |
801
+ | `MOD-016` | Unit | `test/unit/spec/credentials/credentials.js` | none found | `processGrantError` and the plain-`OAuthError` carve-out are untested |
802
+ | `MOD-017` | Unit | `test/unit/spec/credentials/credentials.js` | none found | Five of six codes, and the fallback, are unasserted |
803
+ | `MOD-018` | none | none found | none found | No test of the parsed properties |
804
+ | `MOD-019`, `INV-004` | Unit | `test/unit/spec/credentials/scope.js` | `test/unit/spec/credentials/scope.js` (empty and undefined inputs) | none |
805
+ | `MOD-020` | Unit | `test/unit/spec/credentials/credentials.js` | none found | none |
806
+ | `MOD-021` | Unit | `test/unit/spec/credentials/credentials.js` (fourteen path and format cases) | none found | none |
807
+ | `MOD-022` | Unit, Integration | `test/unit/spec/credentials/credentials.js`, `test/integration/spec/credentials/credentials.js` | none found | none |
808
+ | `MOD-023` | Unit | `test/unit/spec/credentials/credentials.js` | none found | The `jwtRefreshCallback` branch has no test |
809
+ | `MOD-024` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` (state validation) | The `public` default and caller-scope override are untested |
810
+ | `MOD-025` | Unit | `test/unit/spec/credentials/credentials.js` | none found | The undeclared `service` key is hidden by the mock |
811
+ | `MOD-026` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` (missing fields) | none |
812
+ | `MOD-027` | Unit, Integration | `test/unit/spec/credentials/credentials.js`, `test/integration/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none |
813
+ | `MOD-028` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none |
814
+ | `MOD-029` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none |
815
+ | `MOD-030` | Unit | `test/unit/spec/credentials/credentials.js` | none found | none |
816
+ | `MOD-031`, `INV-008` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | none |
817
+ | `MOD-032`, `INV-009` | Unit | `test/unit/spec/credentials/credentials.js` | none found | Storage-restore wait untested |
818
+ | `MOD-033` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Effect of the supertoken scope on the fallback is unasserted |
819
+ | `MOD-034` | Unit | `test/unit/spec/credentials/credentials.js` | none found | JWT branch and flag toggling untested |
820
+ | `MOD-035` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` (revoke rejects, scope mismatch) | Reschedule argument not proven |
821
+ | `MOD-036` | Unit | `test/unit/spec/credentials/credentials.js` | none found | Weak: `unset` stubbed, assertions inside `catch` |
822
+ | `MOD-037` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` (expired path) | No assertion on a failing refresh from the timer |
823
+ | `MOD-038` | Unit | `test/unit/spec/credentials/credentials.js` | none found | Individual removal failure branches untested |
824
+ | `MOD-039` | Unit | `test/unit/spec/credentials/credentials.js` | none found | 400 mapping untested |
825
+ | `MOD-040` | Unit | `test/unit/spec/credentials/credentials.js` | `test/unit/spec/credentials/credentials.js` | Restore not asserted |
826
+ | `MOD-041` | none | none found | none found | `ready` untested |
827
+ | `MOD-042` | none | none found | none found | Derived URLs and environment fallbacks untested |
828
+ | `MOD-043` | Integration | `test/integration/spec/credentials/credentials.js` | none found | Extra-property acceptance is not asserted |
829
+
830
+ **Tiers and runners.** The three files under `test/unit/spec/credentials` run under Jest through
831
+ `yarn workspace @webex/webex-core test:unit`, using the shared mock SDK and fake timers; platform
832
+ branches use the Mocha-helper `browserOnly`, `nodeOnly`, and `skipInBrowser` wrappers, which decide
833
+ per platform which variant runs. The files under `test/integration/spec/credentials` need
834
+ provisioned test users and a live identity service and run under Mocha or Karma; the two files under
835
+ `test/integration/spec/unit-browser` use the mock SDK despite the integration location, and several
836
+ cases in them are `browserOnly`. `test/integration/spec/unit-browser/auth.js` exercises the interceptor
837
+ sibling's 401 path and belongs by subject to that module; it is listed here only because it drives
838
+ `Credentials.refresh`.
839
+
840
+ **Coverage gaps worth acting on.** The JWT refresh mode, the `ready` flag, the derived configuration
841
+ URLs, the identical-token guard, `previousToken` revoke failure, and concurrent flight sharing have no
842
+ test. The suite's three weakest assertions are the `client:InvalidRequestError` case (assertions run
843
+ only on rejection and `unset` is stubbed), the reschedule check (compares to an undefined `expires`),
844
+ and the scope unit spec importing a helper that the source does not define. Confidence in `MOD-036` and `MOD-035`
845
+ is therefore lower than the Present label suggests. This specification records current behavior; the
846
+ items under Pitfalls are recorded as they are, not as endorsements.