ark-oauth-client-node 0.0.0-stage → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +84 -0
- package/LICENSE +21 -0
- package/README.md +528 -2
- package/package.json +64 -4
- package/src/access.js +234 -0
- package/src/app-config.js +73 -0
- package/src/client.js +780 -0
- package/src/config.js +164 -0
- package/src/crypto.js +59 -0
- package/src/denied-page.js +83 -0
- package/src/discovery.js +101 -0
- package/src/errors.js +88 -0
- package/src/express.js +820 -0
- package/src/http.js +153 -0
- package/src/index.js +42 -0
- package/src/jwks.js +122 -0
- package/src/jwt.js +294 -0
- package/src/pkce.js +42 -0
- package/src/session.js +135 -0
- package/src/tokens.js +120 -0
- package/src/version.js +10 -0
- package/types/index.d.ts +672 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.2.0
|
|
4
|
+
|
|
5
|
+
**Renamed to `ark-oauth-client-node`.** Up to 2.1.8 this package was published as
|
|
6
|
+
`ark-oauth-client`. That name is deprecated and gets no further releases. The new name makes the
|
|
7
|
+
package distinct from the Python `ark-oauth-client` on PyPI and the browser `ark-oauth-client-js`.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm uninstall ark-oauth-client
|
|
11
|
+
npm install ark-oauth-client-node
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Then change the import specifier from `'ark-oauth-client'` to `'ark-oauth-client-node'`, and
|
|
15
|
+
`'ark-oauth-client/express'` to `'ark-oauth-client-node/express'`. There is no API change: the
|
|
16
|
+
same exports, options and types, and session data and the denial cookie are read as before.
|
|
17
|
+
|
|
18
|
+
The built-in access-denied page names the package in its footer as `ark-oauth-client-node 2.2.0`.
|
|
19
|
+
|
|
20
|
+
Published with `Ark.oAuth.Oidc` 2.2.0, a security release. Upgrade the provider too. Its single
|
|
21
|
+
sign-on sessions from before the upgrade are not recognised, so every user signs in at the provider
|
|
22
|
+
once more.
|
|
23
|
+
|
|
24
|
+
## 2.1.1
|
|
25
|
+
|
|
26
|
+
The first release of the Node client published to npm, at the version `Ark.oAuth.Client` and the
|
|
27
|
+
Python `ark-oauth-client` already carry. It catches up with 2.1.0 on both and fixes what a review
|
|
28
|
+
before publishing found.
|
|
29
|
+
|
|
30
|
+
**Account switching on a shared browser**, as in the .NET and Python 2.1.0 releases. Everything is
|
|
31
|
+
off or unchanged by default:
|
|
32
|
+
|
|
33
|
+
* `accountSwitch.requireArkClaims` moves the entitlement check to the callback. An account with no
|
|
34
|
+
`ark_claims` for this client is refused before any session is written, and its refresh token is
|
|
35
|
+
revoked.
|
|
36
|
+
* A built-in access-denied page at `/ark/no-access`. It names the signed-in account and offers
|
|
37
|
+
"Sign in as a different user", which challenges with `prompt=login`, and "Sign out completely".
|
|
38
|
+
It has no script, a strict CSP, and the library version in its footer. A browser that is signed
|
|
39
|
+
in but lacks a guarded claim lands here instead of on a bare 403.
|
|
40
|
+
* `/ark/switch-user` and `/ark/sign-out` accept only a same-origin POST.
|
|
41
|
+
* `req.ark.switchUser()`, `signOutEverywhere()`, `signOutLocally()` and `deniedAccount()`, and
|
|
42
|
+
`ArkChallengeProperties`. The `events.onEvaluateAccess` and `events.onAccessDenied` hooks let
|
|
43
|
+
you supply your own rule or your own page. The denial cookie uses the Python client's format
|
|
44
|
+
byte for byte.
|
|
45
|
+
|
|
46
|
+
**Also new**
|
|
47
|
+
|
|
48
|
+
* `ArkAuthConfig.fromMapping` binds an `appsettings.json` `ark_oauth_client` section unchanged, in
|
|
49
|
+
C#, camel or snake spelling.
|
|
50
|
+
* `auth.checkSetup(req)` reports the redirect URI the request would really send. The report also
|
|
51
|
+
names the tenant, admin console and integration page.
|
|
52
|
+
* `VERSION`, read from package.json.
|
|
53
|
+
|
|
54
|
+
**Fixed**
|
|
55
|
+
|
|
56
|
+
* A request that waited on another request's refresh kept the retired refresh token in its copy of
|
|
57
|
+
the session. With any store that copies (Redis, a database), its next token read presented that
|
|
58
|
+
token again, and the provider revoked the whole family. Every waiter now receives the rotated
|
|
59
|
+
tokens, and a refresh re-reads the store first.
|
|
60
|
+
* A refresh that failed for a transient reason threw, which failed the request. It now keeps the
|
|
61
|
+
session, and the next request tries again.
|
|
62
|
+
* `usePar` defaulted to `false`, which hid the tenant's `require_pushed_authorization_requests`.
|
|
63
|
+
* `extraAuthorizationParams` / `extra` could replace `state`, `nonce`, the PKCE challenge or the
|
|
64
|
+
redirect URI. Protocol parameters now win.
|
|
65
|
+
* The client-credentials cache ignored the secret. A caller presenting a wrong secret was handed a
|
|
66
|
+
token another caller had obtained with the right one.
|
|
67
|
+
* A bearer challenge copied error text, including a forged token's `kid`, into
|
|
68
|
+
`WWW-Authenticate`. A CR/LF there made `setHeader` throw inside an async handler. That text is
|
|
69
|
+
now escaped.
|
|
70
|
+
* `form_post` bodies are capped at 64 KiB, values are taken as strings only, and `state` is looked
|
|
71
|
+
up as an own property.
|
|
72
|
+
* `trustProxy` honoured `X-Forwarded-Host` without `X-Forwarded-Proto`. It now needs both, as the
|
|
73
|
+
Python client does.
|
|
74
|
+
* `responseMode: 'form_post'` with a `SameSite=Lax` cookie can never complete a sign-in. It is now
|
|
75
|
+
refused at startup.
|
|
76
|
+
* Non-numeric `nbf`/`iat` claims, and token segments that are not JSON objects, are rejected.
|
|
77
|
+
Before, they were skipped or surfaced as a `TypeError`.
|
|
78
|
+
* A provider error sent back without `state` was reported as "could not be matched to a request
|
|
79
|
+
from this browser". The provider's own `error` and description are now shown. The error is
|
|
80
|
+
displayed only; nothing is redeemed.
|
|
81
|
+
* The set of unknown `kid`s is bounded, and device-grant polling no longer leaks abort listeners.
|
|
82
|
+
* `refreshLeewaySeconds` now defaults to 120, the .NET and Python window.
|
|
83
|
+
|
|
84
|
+
Requires Node 20+. Still no runtime dependencies.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Immanuel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,529 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ark-oauth-client-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The OAuth 2.1 / OpenID Connect client for **Node.js** applications talking to an
|
|
4
|
+
[ARK Identity Server](../README.md).
|
|
5
|
+
|
|
6
|
+
There is one URL to configure — the issuer, `{BaseUrl}/{TenantId}`. Endpoints, signing keys and
|
|
7
|
+
capabilities are read from the provider's discovery document, so the application does not have to
|
|
8
|
+
be redeployed when a key rotates or an endpoint moves.
|
|
9
|
+
|
|
10
|
+
No runtime dependencies. Everything is built on `node:crypto` and the global `fetch`.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install ark-oauth-client-node
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
> **Renamed in 2.2.0.** Up to 2.1.8 this package was published as `ark-oauth-client`, which is
|
|
17
|
+
> deprecated and gets no further releases. The API is unchanged: replace the dependency and change
|
|
18
|
+
> the import specifier from `'ark-oauth-client'` to `'ark-oauth-client-node'`
|
|
19
|
+
> (and `'ark-oauth-client/express'` to `'ark-oauth-client-node/express'`).
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Contents
|
|
24
|
+
|
|
25
|
+
- [Quick start](#quick-start)
|
|
26
|
+
- [What it implements](#what-it-implements)
|
|
27
|
+
- [Configuration](#configuration)
|
|
28
|
+
- [The middleware](#the-middleware)
|
|
29
|
+
- [Account switching on a shared browser](#account-switching-on-a-shared-browser)
|
|
30
|
+
- [Loading appsettings.json](#loading-appsettingsjson)
|
|
31
|
+
- [Protecting an API](#protecting-an-api)
|
|
32
|
+
- [Sessions](#sessions)
|
|
33
|
+
- [Using the client directly](#using-the-client-directly)
|
|
34
|
+
- [Checking the setup](#checking-the-setup)
|
|
35
|
+
- [Errors](#errors)
|
|
36
|
+
- [Registering the client](#registering-the-client)
|
|
37
|
+
- [Security notes](#security-notes)
|
|
38
|
+
- [Troubleshooting](#troubleshooting)
|
|
39
|
+
- [Development](#development)
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
import express from 'express';
|
|
47
|
+
import { arkExpress } from 'ark-oauth-client-node';
|
|
48
|
+
|
|
49
|
+
const app = express();
|
|
50
|
+
|
|
51
|
+
const auth = arkExpress({
|
|
52
|
+
authority: 'https://idp.example.com/my_idp', // {BaseUrl}/{TenantId}
|
|
53
|
+
clientId: 'my-app',
|
|
54
|
+
clientSecret: process.env.ARK_CLIENT_SECRET, // omit for public clients
|
|
55
|
+
redirectUri: 'https://app.example.com/signin-oidc',
|
|
56
|
+
postLogoutRedirectUri: 'https://app.example.com/',
|
|
57
|
+
secret: process.env.ARK_SESSION_SECRET // signs the session cookie
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
app.use(auth); // serves /login, /signin-oidc and /logout
|
|
61
|
+
|
|
62
|
+
app.get('/', (req, res) => {
|
|
63
|
+
res.send(req.ark.isAuthenticated ? `Hello ${req.ark.user.name}` : '<a href="/login">Sign in</a>');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
app.get('/billing', auth.requireClaims('billing.admin'), (req, res) => res.send('billing'));
|
|
67
|
+
|
|
68
|
+
app.listen(3000);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
That is the whole integration. Authorization code + PKCE, `state`, `nonce`, `iss`, `at_hash`,
|
|
72
|
+
JWKS rotation, silent token refresh and sign-out are handled underneath.
|
|
73
|
+
|
|
74
|
+
Runnable versions of this and every other flow are in [`examples/`](examples/) — `examples/web-app.js`
|
|
75
|
+
needs no dependencies at all.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## What it implements
|
|
80
|
+
|
|
81
|
+
| Specification | What the client does |
|
|
82
|
+
|---|---|
|
|
83
|
+
| OpenID Connect Discovery 1.0 | Reads and caches `/.well-known/openid-configuration`; verifies `issuer` matches the configured authority |
|
|
84
|
+
| RFC 8414 metadata | Falls back to the `oauth-authorization-server` spelling for other providers |
|
|
85
|
+
| Authorization code (RFC 6749) | The only interactive flow; implicit and hybrid are gone in OAuth 2.1 and are not offered |
|
|
86
|
+
| PKCE (RFC 7636) | Always sent, `S256` only, verifier from `crypto.randomBytes` |
|
|
87
|
+
| OpenID Connect Core 1.0 | ID token verification: signature, `iss`, `aud`, `azp`, `exp`, `nbf`, `iat`, `nonce`, `at_hash`, `c_hash`, `auth_time`/`max_age` |
|
|
88
|
+
| RFC 7517 JWKS | Cached, and refetched on an unseen `kid`, so a two-phase key rotation needs no restart |
|
|
89
|
+
| RFC 9068 access tokens | `typ: at+jwt` enforced, so an ID token cannot be presented to an API in its place |
|
|
90
|
+
| Refresh (RFC 6749 §6) | Rotation-aware, scope narrowing, one refresh per session at a time |
|
|
91
|
+
| Client credentials | With per-client-and-scope caching |
|
|
92
|
+
| Device grant (RFC 8628) | Polling that handles `authorization_pending` and `slow_down` |
|
|
93
|
+
| PAR (RFC 9126) | `usePar: true`, or automatically when the tenant requires it |
|
|
94
|
+
| Introspection (RFC 7662) | With client authentication |
|
|
95
|
+
| Revocation (RFC 7009) | Called on sign-out, so the refresh-token family really ends |
|
|
96
|
+
| RP-Initiated Logout 1.0 | `id_token_hint`, `post_logout_redirect_uri`, `state` |
|
|
97
|
+
| RFC 9207 `iss` | Checked on every authorization response |
|
|
98
|
+
| Dynamic registration (RFC 7591/7592) | Register, read and delete |
|
|
99
|
+
| Client authentication | `client_secret_basic`, `client_secret_post`, `private_key_jwt`, `none` |
|
|
100
|
+
|
|
101
|
+
Ark's per-user-per-client authorization claims (`ark_claims` in the access token) are surfaced as
|
|
102
|
+
`req.ark.claims`, and are what `requireClaims()` checks.
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Configuration
|
|
107
|
+
|
|
108
|
+
Only `authority` and `clientId` are required; `redirectUri` too for interactive sign-in.
|
|
109
|
+
|
|
110
|
+
| Option | Default | Meaning |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `authority` | — | The issuer URL: `{BaseUrl}/{TenantId}` |
|
|
113
|
+
| `authServerUrl` + `tenantId` | — | Alternative to `authority`; joined for you, matching the .NET client's config shape |
|
|
114
|
+
| `clientId` | — | The client id registered with the tenant |
|
|
115
|
+
| `clientSecret` | `null` | Confidential clients only. Omit for SPA, native and CLI clients |
|
|
116
|
+
| `tokenEndpointAuthMethod` | derived | `client_secret_basic` when a secret is set, `private_key_jwt` when a key is, otherwise `none` |
|
|
117
|
+
| `privateKeyJwt` | `null` | `{ privateKey, kid, alg }` — PEM, JWK or `KeyObject` |
|
|
118
|
+
| `redirectUri` | — | Absolute, no fragment, `https` unless loopback. The server matches it **exactly** |
|
|
119
|
+
| `postLogoutRedirectUri` | — | Must also be registered |
|
|
120
|
+
| `scopes` | `openid profile email offline_access` | `offline_access` is what earns a refresh token |
|
|
121
|
+
| `audience` | `null` | Expected `aud` when verifying access tokens in an API |
|
|
122
|
+
| `usePar` | `false` | Push authorization parameters over the back channel |
|
|
123
|
+
| `responseMode` | `query` | `query`, `fragment` or `form_post` |
|
|
124
|
+
| `prompt`, `acrValues`, `extraAuthorizationParams` | — | Passed through to `/authorize` |
|
|
125
|
+
| `clockToleranceSeconds` | `60` | Leeway on `exp`, `nbf` and `iat` |
|
|
126
|
+
| `requireHttps` | `true` | Only ever `false` for local development |
|
|
127
|
+
| `requireTokenHashes` | `true` | Require `at_hash`/`c_hash`; Ark always sends them |
|
|
128
|
+
| `timeoutMs` | `10000` | Per-request timeout |
|
|
129
|
+
| `metadataTtlMs`, `jwksTtlMs` | `300000` | Cache lifetimes, matching the server's `max-age=300` |
|
|
130
|
+
| `jwksMinRefreshIntervalMs` | `10000` | How soon an unseen `kid` may trigger another JWKS fetch |
|
|
131
|
+
| `fetch` | global | Inject your own for tracing, proxies or tests |
|
|
132
|
+
|
|
133
|
+
Mistakes here are caught at construction, not at a user's sign-in: a `redirectUri` with a fragment,
|
|
134
|
+
a plain-http authority, `private_key_jwt` with no key, a `clientSecret` alongside
|
|
135
|
+
`tokenEndpointAuthMethod: 'none'`.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## The middleware
|
|
140
|
+
|
|
141
|
+
`arkExpress(options)` returns a plain Connect-style middleware. It works with Express, with
|
|
142
|
+
`@fastify/middie`, with `koa-connect`, and with a bare `http.createServer` — the package depends on
|
|
143
|
+
none of them.
|
|
144
|
+
|
|
145
|
+
It claims these paths and passes everything else through:
|
|
146
|
+
|
|
147
|
+
| Path | Purpose |
|
|
148
|
+
|---|---|
|
|
149
|
+
| `loginPath` (`/login`) | Starts a sign-in. `?returnTo=/somewhere` comes back to that page — same-origin paths only |
|
|
150
|
+
| `callbackPath` (path of `redirectUri`, else `/signin-oidc`) | Completes it. **Never add a route of your own here** |
|
|
151
|
+
| `logoutPath` (`/logout`) | Revokes the refresh token, destroys the session, clears the cookie, then redirects to the provider's `end_session_endpoint` |
|
|
152
|
+
| `/ark/no-access`, `/ark/switch-user`, `/ark/sign-out` | The access-denied page and its two POSTs — see [account switching](#account-switching-on-a-shared-browser) |
|
|
153
|
+
|
|
154
|
+
### `req.ark`
|
|
155
|
+
|
|
156
|
+
| Member | |
|
|
157
|
+
|---|---|
|
|
158
|
+
| `isAuthenticated` | |
|
|
159
|
+
| `user` | ID token claims, plus UserInfo when `fetchUserInfo: true` |
|
|
160
|
+
| `sub` | |
|
|
161
|
+
| `claims` | Ark authorization claims — **what to authorise on** |
|
|
162
|
+
| `scopes` | Granted scopes |
|
|
163
|
+
| `tokens` | The `TokenSet` |
|
|
164
|
+
| `await accessToken()` | The access token, renewed first if it is close to expiring |
|
|
165
|
+
| `await authorize(headers?)` | Returns headers with `Authorization: Bearer …` set, for a downstream call |
|
|
166
|
+
| `hasClaim(…)`, `hasScope(…)` | |
|
|
167
|
+
| `await login({ returnTo, prompt, loginHint })`, `await logout({ returnTo })` | Drive the flows from your own routes |
|
|
168
|
+
| `await switchUser({ returnUrl })` | Drop this session and challenge with `prompt=login` |
|
|
169
|
+
| `await signOutEverywhere()`, `await signOutLocally()` | Provider session too, or this application only |
|
|
170
|
+
| `deniedAccount()` | Who the last denial was about, for an access-denied page of your own |
|
|
171
|
+
|
|
172
|
+
Read the access token through `accessToken()` on every call rather than keeping it: it is renewed
|
|
173
|
+
underneath you, and the refresh token it was renewed with is retired the moment that happens.
|
|
174
|
+
|
|
175
|
+
### Guards
|
|
176
|
+
|
|
177
|
+
```js
|
|
178
|
+
app.get('/account', auth.requireAuth(), handler);
|
|
179
|
+
app.get('/billing', auth.requireClaims('billing.admin'), handler);
|
|
180
|
+
app.get('/reports', auth.requireScopes('reports.read'), handler);
|
|
181
|
+
app.get('/admin', auth.requireAuth({ claims: ['tenant.root'], scopes: ['admin'] }), handler);
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
An unauthenticated **browser** request is redirected to the login page with a `returnTo`. Anything
|
|
185
|
+
else — `fetch`, XHR, a mobile client — gets `401` with an RFC 6750 challenge, because redirecting a
|
|
186
|
+
background request to a sign-in page produces a CORS error rather than anything the caller can act
|
|
187
|
+
on. A signed-in user missing a claim gets `403`, never a redirect loop — for a browser, the
|
|
188
|
+
access-denied page with a way out; for anything else, an RFC 6750 `insufficient_scope` body.
|
|
189
|
+
|
|
190
|
+
### Middleware options
|
|
191
|
+
|
|
192
|
+
| Option | Default | |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `secret` | — | **Required**, 16+ characters. Signs the session cookie. Same value on every instance |
|
|
195
|
+
| `client` | — | Reuse an existing `ArkOAuthClient` instead of configuring one here |
|
|
196
|
+
| `store` | `MemorySessionStore` | See [Sessions](#sessions) |
|
|
197
|
+
| `cookieName` | `ark_session` | |
|
|
198
|
+
| `cookie` | `{ httpOnly: true, secure: true, sameSite: 'Lax', path: '/' }` | `secure: false` only for local http |
|
|
199
|
+
| `sessionTtlSeconds` | `28800` | Matches the server's default session lifetime |
|
|
200
|
+
| `refreshLeewaySeconds` | `120` | Renew the access token this long before it expires — the .NET and Python window |
|
|
201
|
+
| `fetchUserInfo` | `false` | Also call `/userinfo` at sign-in and merge it into `req.ark.user` |
|
|
202
|
+
| `defaultReturnTo` | `/` | |
|
|
203
|
+
| `errorPath` | `null` | Where a failed sign-in lands, with `?auth_error=…`. Otherwise a plain 400 |
|
|
204
|
+
| `onError` | `null` | `(error, req, res, next)` — full control instead of `errorPath` |
|
|
205
|
+
| `trustProxy` | `true` | Honour `X-Forwarded-Proto` + `X-Forwarded-Host` (both, or neither) when deriving this app's own origin. Turn it off when nothing in front of the app sets them |
|
|
206
|
+
| `accountSwitch` | all off | See [below](#account-switching-on-a-shared-browser) |
|
|
207
|
+
| `events` | `{}` | `onEvaluateAccess`, `onAccessDenied` |
|
|
208
|
+
|
|
209
|
+
`responseMode: 'form_post'` is a cross-site POST, which a browser sends without a `SameSite=Lax`
|
|
210
|
+
cookie; the middleware refuses to start with that combination rather than fail every sign-in. Use
|
|
211
|
+
`cookie: { sameSite: 'None', secure: true }` with it, or stay on the default `query`.
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## Account switching on a shared browser
|
|
216
|
+
|
|
217
|
+
Single sign-on is browser-wide. Once one person has signed in anywhere, the provider's session
|
|
218
|
+
answers the authorize request of every other client in that browser: the next person opens this
|
|
219
|
+
application, is silently signed in **as the first person**, is told they have no access — and has no
|
|
220
|
+
way out, because the sign-in link returns to the same session and gives the same answer.
|
|
221
|
+
|
|
222
|
+
The fix is the same in all three Ark clients and, as there, **off by default**:
|
|
223
|
+
|
|
224
|
+
```js
|
|
225
|
+
const auth = arkExpress({
|
|
226
|
+
authority, clientId, secret,
|
|
227
|
+
accountSwitch: {
|
|
228
|
+
requireArkClaims: true, // refuse, at the callback, an account with no ark_claims here
|
|
229
|
+
appDisplayName: 'Billing Portal',
|
|
230
|
+
supportEmail: 'help@example.com'
|
|
231
|
+
},
|
|
232
|
+
events: {
|
|
233
|
+
// Optional: your own entitlement rule, replacing the configured one.
|
|
234
|
+
onEvaluateAccess: ({ arkClaims, allowedByConfiguration }) => allowedByConfiguration || arkClaims.includes('tenant.root'),
|
|
235
|
+
// Optional: log it, or draw your own page (respond, or set denied.handled = true).
|
|
236
|
+
onAccessDenied: (denied, req, res) => console.warn('access denied', denied.email, denied.reason)
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
* **`requireArkClaims`** moves the entitlement check to the callback. An account the provider issued
|
|
242
|
+
no `ark_claims` for is refused *before* the session is written — the browser never holds a session
|
|
243
|
+
for somebody who cannot use the application — and its refresh token is revoked. `requiredClaims`
|
|
244
|
+
narrows it to particular values. **Set `requiredClaims` in practice:** the Ark server issues the
|
|
245
|
+
whole access-mapping list as `ark_claims`, identity names (`sub`, `email`, …) included, so a
|
|
246
|
+
mapping with no authorization claim still satisfies "any `ark_claims`".
|
|
247
|
+
* **`/ark/no-access`** names the account that is signed in and offers **Sign in as a different user**,
|
|
248
|
+
which challenges with `prompt=login` so the provider draws its sign-in form instead of answering
|
|
249
|
+
from its session. It is a self-contained page — no script, a strict CSP,
|
|
250
|
+
`ark-oauth-client-node <version>` in the footer. A guarded route a signed-in browser lacks a claim for lands here too.
|
|
251
|
+
* **`/ark/switch-user`** and **`/ark/sign-out`** accept only a same-origin `POST`. The return URL is
|
|
252
|
+
kept to same-origin paths. `endProviderSessionOnSwitch: true` makes switching a full provider
|
|
253
|
+
sign-out, for a kiosk.
|
|
254
|
+
|
|
255
|
+
| `accountSwitch` option | Default | |
|
|
256
|
+
|---|---|---|
|
|
257
|
+
| `enabled` | `true` | Serve the endpoints and send a browser's 403 to the page |
|
|
258
|
+
| `requireArkClaims` | `false` | The check that makes the case recoverable |
|
|
259
|
+
| `requiredClaims` | `[]` | At least one of these (case-insensitive); empty means any |
|
|
260
|
+
| `accessDeniedPath`, `switchUserPath`, `signOutPath` | `/ark/…` | Local paths only |
|
|
261
|
+
| `serveDefaultPage` | `true` | Off when `accessDeniedPath` is your own route; read `req.ark.deniedAccount()` there |
|
|
262
|
+
| `appDisplayName` | client id | |
|
|
263
|
+
| `showSignedInAccount`, `allowFullSignOut` | `true` | |
|
|
264
|
+
| `endProviderSessionOnSwitch` | `false` | |
|
|
265
|
+
| `prompt` | `login` | |
|
|
266
|
+
| `homePath` | `/` | Fallback for a missing or off-site return URL |
|
|
267
|
+
| `supportUrl`, `supportEmail` | — | Shown as "Need access?" on the page |
|
|
268
|
+
|
|
269
|
+
The account named on the page travels from the callback in a five-minute, `HttpOnly` cookie sealed
|
|
270
|
+
with AES-256-GCM under a key derived from `secret` — the Python client's format, byte for byte.
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Loading appsettings.json
|
|
275
|
+
|
|
276
|
+
An Ark application usually already has an `ark_oauth_client` section. `ArkAuthConfig.fromMapping`
|
|
277
|
+
reads it unchanged — C# (`ClientId`), camel or snake spellings, the whole file or just the section:
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
import { readFileSync } from 'node:fs';
|
|
281
|
+
import { arkExpress, ArkAuthConfig } from 'ark-oauth-client-node';
|
|
282
|
+
|
|
283
|
+
const settings = JSON.parse(readFileSync('appsettings.json', 'utf8'));
|
|
284
|
+
app.use(arkExpress({ ...ArkAuthConfig.fromMapping(settings), secret: process.env.ARK_SESSION_SECRET }));
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`Authority` (or `AuthServerUrl` + `TenantId`), `ClientId`, `ClientSecret`, `Scopes`, `CallbackPath`,
|
|
288
|
+
`LoginPath`, `LogoutPath`, `AuthErrorPath`, `CookieName`, `RoleClaimType`, `RequireHttpsMetadata`,
|
|
289
|
+
`ExpireMins`, `PostLogoutRedirectUri` and `AccountSwitch` are read. The v1 keys (`RsaPublic`,
|
|
290
|
+
`Issuer`, `Tenants`, `RedirectUri`) are ignored on purpose: the redirect URI is derived from
|
|
291
|
+
`CallbackPath`, as the .NET handler does.
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## Protecting an API
|
|
296
|
+
|
|
297
|
+
```js
|
|
298
|
+
import { arkBearer } from 'ark-oauth-client-node';
|
|
299
|
+
|
|
300
|
+
const bearer = arkBearer({
|
|
301
|
+
authority: 'https://idp.example.com/my_idp',
|
|
302
|
+
clientId: 'my-api',
|
|
303
|
+
audience: 'my_idp_api' // omit to skip the audience check
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
app.use('/api', bearer);
|
|
307
|
+
app.get('/api/me', (req, res) => res.json({ sub: req.ark.sub, claims: req.ark.claims }));
|
|
308
|
+
app.get('/api/reports', bearer.require({ claims: ['reports.read'] }), handler);
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Verification is local, against the cached JWKS, so a request costs no round trip to the identity
|
|
312
|
+
server. `optional: true` lets anonymous requests through with `req.ark.isAuthenticated === false`.
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
## Sessions
|
|
317
|
+
|
|
318
|
+
Tokens never reach the browser. The cookie carries an opaque session id and an HMAC over it;
|
|
319
|
+
the access token, refresh token and claims stay server-side in a store.
|
|
320
|
+
|
|
321
|
+
`MemorySessionStore` is the default and is fine for one process. Behind a load balancer, or across
|
|
322
|
+
a restart, supply a shared store — any object with these methods:
|
|
323
|
+
|
|
324
|
+
```js
|
|
325
|
+
const redisStore = {
|
|
326
|
+
async get(id) { const v = await redis.get(`ark:${id}`); return v ? JSON.parse(v) : null; },
|
|
327
|
+
async set(id, data, ttl) { await redis.set(`ark:${id}`, JSON.stringify(data), { EX: ttl }); },
|
|
328
|
+
async destroy(id) { await redis.del(`ark:${id}`); },
|
|
329
|
+
async touch(id, ttl) { await redis.expire(`ark:${id}`, ttl); }
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const auth = arkExpress({ /* … */, store: redisStore });
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
One thing to know when you do. This server **rotates refresh tokens**, and presenting a retired one
|
|
336
|
+
is treated as theft of the whole family. Concurrent refreshes within a process are serialised for
|
|
337
|
+
you; across processes they are not, so a shared store should also carry a short lock around the
|
|
338
|
+
refresh if your traffic can put two requests for the same session on two instances at the same
|
|
339
|
+
instant.
|
|
340
|
+
|
|
341
|
+
---
|
|
342
|
+
|
|
343
|
+
## Using the client directly
|
|
344
|
+
|
|
345
|
+
For CLIs, workers, Fastify/Koa/Hapi, or any flow the middleware does not cover.
|
|
346
|
+
|
|
347
|
+
```js
|
|
348
|
+
import { ArkOAuthClient } from 'ark-oauth-client-node';
|
|
349
|
+
|
|
350
|
+
const client = new ArkOAuthClient({ authority, clientId, clientSecret, redirectUri });
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### Authorization code by hand
|
|
354
|
+
|
|
355
|
+
```js
|
|
356
|
+
// 1. starting a sign-in
|
|
357
|
+
const tx = await client.createAuthorizationUrl({ returnTo: '/dashboard' });
|
|
358
|
+
// store tx (state, nonce, codeVerifier) server-side, keyed to this browser
|
|
359
|
+
redirect(tx.url);
|
|
360
|
+
|
|
361
|
+
// 2. on the callback
|
|
362
|
+
const tokens = await client.handleCallback(req.query, tx);
|
|
363
|
+
tokens.accessToken; tokens.idToken; tokens.refreshToken;
|
|
364
|
+
tokens.claims; // validated ID token claims
|
|
365
|
+
tokens.arkClaims(); // Ark authorization claims
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
`state`, `nonce` and `codeVerifier` are the entire security of the flow. Keep them somewhere the
|
|
369
|
+
user cannot read or edit — a hidden form field or a plain cookie hands an attacker exactly the
|
|
370
|
+
three values the checks are made of.
|
|
371
|
+
|
|
372
|
+
### Refresh
|
|
373
|
+
|
|
374
|
+
```js
|
|
375
|
+
const next = await client.refresh(tokens.refreshToken); // store what comes back: the old one is now dead
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
### Client credentials
|
|
379
|
+
|
|
380
|
+
```js
|
|
381
|
+
const token = await client.clientCredentials({ scopes: ['reports.read'] }); // cached until near expiry
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
### Device grant
|
|
385
|
+
|
|
386
|
+
```js
|
|
387
|
+
const authorization = await client.deviceAuthorization({ scopes: ['openid', 'profile'] });
|
|
388
|
+
console.log(`Go to ${authorization.verification_uri} and enter ${authorization.user_code}`);
|
|
389
|
+
const tokens = await client.pollDeviceToken(authorization);
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
### The rest
|
|
393
|
+
|
|
394
|
+
```js
|
|
395
|
+
await client.userInfo(accessToken);
|
|
396
|
+
await client.introspect(token, { tokenTypeHint: 'refresh_token' });
|
|
397
|
+
await client.revoke(refreshToken);
|
|
398
|
+
await client.endSessionUrl({ idTokenHint: tokens.idToken, state });
|
|
399
|
+
await client.verifyAccessToken(token, { scopes: ['reports.read'], arkClaims: ['billing.admin'] });
|
|
400
|
+
await client.verifyIdToken(idToken, { nonce });
|
|
401
|
+
await client.pushAuthorizationRequest(params);
|
|
402
|
+
await client.registerClient(metadata, initialAccessToken);
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
---
|
|
406
|
+
|
|
407
|
+
## Checking the setup
|
|
408
|
+
|
|
409
|
+
```js
|
|
410
|
+
const report = await client.checkSetup();
|
|
411
|
+
if (report.problems.length) console.warn(report.problems);
|
|
412
|
+
|
|
413
|
+
// Inside the app: the redirect URI this request would really send, and who is signed in.
|
|
414
|
+
app.get('/setup', async (req, res) => res.json(await auth.checkSetup(req)));
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Pairs local configuration with the provider's live metadata and returns what does not line up:
|
|
418
|
+
a wrong port, a stopped provider, an issuer mismatch, a scope this client is not registered for, an
|
|
419
|
+
authentication method the tenant does not offer, PAR required but not enabled. Render it on a health
|
|
420
|
+
page, or run `node examples/setup-check.js` in CI. Without it, the first symptom of any of these is
|
|
421
|
+
`invalid_request` on a page a user is looking at.
|
|
422
|
+
|
|
423
|
+
---
|
|
424
|
+
|
|
425
|
+
## Errors
|
|
426
|
+
|
|
427
|
+
Every error carries what is needed to decide what to do next, rather than a string to grep.
|
|
428
|
+
|
|
429
|
+
| Class | Meaning | Usual response |
|
|
430
|
+
|---|---|---|
|
|
431
|
+
| `ArkConfigError` | This application is misconfigured | Fix and redeploy; thrown at construction where possible |
|
|
432
|
+
| `ArkOAuthError` | The server refused. `.error` is the RFC 6749 code, `.status` the HTTP status, `.endpoint` the URL | Branch on `.error` |
|
|
433
|
+
| `ArkTokenError` | A token failed validation — signature, issuer, audience, expiry, `nonce`, `at_hash` | Never retry. The answer cannot be trusted |
|
|
434
|
+
| `ArkCallbackError` | The authorization response does not belong to a request this client started | Treat as CSRF or a mix-up attempt |
|
|
435
|
+
| `ArkNetworkError` | The call did not complete: refused, DNS, timeout | Retry with backoff |
|
|
436
|
+
|
|
437
|
+
```js
|
|
438
|
+
import { ArkOAuthError } from 'ark-oauth-client-node';
|
|
439
|
+
|
|
440
|
+
try {
|
|
441
|
+
await client.refresh(token);
|
|
442
|
+
} catch (error) {
|
|
443
|
+
if (error instanceof ArkOAuthError && error.error === 'invalid_grant') signInAgain();
|
|
444
|
+
else throw error;
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
---
|
|
449
|
+
|
|
450
|
+
## Registering the client
|
|
451
|
+
|
|
452
|
+
In the admin console at `/{tenant}/admin`, or from the generated setup page at
|
|
453
|
+
`/{tenant}/oauth2/integrate/{client_id}`:
|
|
454
|
+
|
|
455
|
+
| Field | Value |
|
|
456
|
+
|---|---|
|
|
457
|
+
| Redirect URI | Exactly your `redirectUri`, e.g. `https://app.example.com/signin-oidc` |
|
|
458
|
+
| Post-logout redirect URI | Your `postLogoutRedirectUri` |
|
|
459
|
+
| Grant types | `authorization_code`, `refresh_token` |
|
|
460
|
+
| Scopes | `openid`, `profile`, `email`, `offline_access` |
|
|
461
|
+
| Auth method | `none` for a public client, `client_secret_basic` for a confidential one |
|
|
462
|
+
|
|
463
|
+
Then **give each user access to the client**. Ark maps users to clients explicitly, and without a
|
|
464
|
+
mapping sign-in fails in a way that looks exactly like a wrong password.
|
|
465
|
+
|
|
466
|
+
A server-side Node application needs nothing in the tenant's `CorsOrigins` — that list is for
|
|
467
|
+
browser clients redeeming their own codes.
|
|
468
|
+
|
|
469
|
+
---
|
|
470
|
+
|
|
471
|
+
## Security notes
|
|
472
|
+
|
|
473
|
+
- **Tokens never reach the browser.** The cookie is an opaque id plus a signature; it is `HttpOnly`,
|
|
474
|
+
`Secure` and `SameSite=Lax`.
|
|
475
|
+
- **The session id is replaced at sign-in**, so an id planted before authentication is never the one
|
|
476
|
+
that ends up authenticated.
|
|
477
|
+
- **`state` is compared in constant time**, and `iss` is checked on every authorization response.
|
|
478
|
+
- **A missing `nonce` or `at_hash` fails as hard as a wrong one.** Absence is the easiest check to
|
|
479
|
+
skip and the easiest one to attack.
|
|
480
|
+
- **`alg: none` is refused**, and the accepted algorithms are decided before the token's own header
|
|
481
|
+
is read.
|
|
482
|
+
- **JWKS refetching is rate-limited**, and a `kid` already known to be absent never triggers another
|
|
483
|
+
fetch — otherwise a stream of forged tokens turns this client into a request amplifier pointed at
|
|
484
|
+
your identity server.
|
|
485
|
+
- **`returnTo` accepts same-origin paths only**, so the login route cannot become an open redirect.
|
|
486
|
+
- **Sign-out revokes the refresh token** before ending the local session; so do switching accounts
|
|
487
|
+
and a refused sign-in.
|
|
488
|
+
- **A refresh is shared, and its result reaches every waiting request.** With rotation on, a request
|
|
489
|
+
left holding the retired refresh token would present it again and revoke the whole family.
|
|
490
|
+
- **Bodies are bounded and parameters are strings.** A callback or account form over 64 KiB is
|
|
491
|
+
refused; `state` is looked up as an own property only.
|
|
492
|
+
- **Error text never reaches a header unescaped.** A forged token's `kid` cannot inject a header or
|
|
493
|
+
crash the process through a `WWW-Authenticate` challenge.
|
|
494
|
+
- **Extra authorization parameters cannot replace** `state`, `nonce`, the PKCE challenge or the
|
|
495
|
+
redirect URI.
|
|
496
|
+
|
|
497
|
+
---
|
|
498
|
+
|
|
499
|
+
## Troubleshooting
|
|
500
|
+
|
|
501
|
+
| Symptom | Cause |
|
|
502
|
+
|---|---|
|
|
503
|
+
| `redirect_uri does not match a registered value` | The registered value differs by a character — scheme, port, trailing slash. Matching is exact, with one carve-out for loopback ports |
|
|
504
|
+
| Sign-in fails as though the password were wrong | The user has no access mapping to this client |
|
|
505
|
+
| The next person at a shared browser is signed in as the previous one | SSO. Turn on `accountSwitch.requireArkClaims`; the access-denied page offers `prompt=login` |
|
|
506
|
+
| `responseMode 'form_post' needs cookie: { sameSite: 'None' … }` at startup | See [Middleware options](#middleware-options) |
|
|
507
|
+
| `this sign-in could not be matched to a request from this browser` | The login expired (10 minutes), or the process restarted with the in-memory store |
|
|
508
|
+
| `invalid_grant` on the second refresh | A retired refresh token was presented; the family is revoked. Always store what a refresh returns |
|
|
509
|
+
| `the provider … identifies itself as '…'` | `authority` is not the issuer. It is `{BaseUrl}/{TenantId}`, tenant id included |
|
|
510
|
+
| `no key with kid '…' is published` | A token from a different provider — or a rotation more than `jwksMinRefreshIntervalMs` ago that has not been refetched yet |
|
|
511
|
+
| `unable to verify the first certificate` in development | The provider's development certificate is not trusted by Node. Trust it, or set `NODE_TLS_REJECT_UNAUTHORIZED=0` **locally only** |
|
|
512
|
+
|
|
513
|
+
---
|
|
514
|
+
|
|
515
|
+
## Development
|
|
516
|
+
|
|
517
|
+
```bash
|
|
518
|
+
npm test # 135 tests, no install required
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
The suite runs against `test/stub-idp.js`, an in-process stand-in for the Ark server that mirrors
|
|
522
|
+
its wire behaviour: the same paths, RS256 with a `kid` and two keys across a rotation, `at+jwt`
|
|
523
|
+
access tokens carrying `ark_claims`, ID tokens with `at_hash`/`c_hash`, `iss` on the authorization
|
|
524
|
+
response, refresh-token rotation where a replay revokes the family, and RFC 6749 §5.2 error bodies.
|
|
525
|
+
It is useful in your own tests too.
|
|
526
|
+
|
|
527
|
+
**Requirements:** Node 20 or newer. ESM; on Node 22.12+ `require()` of this package works as well.
|
|
528
|
+
|
|
529
|
+
**License:** MIT.
|