@qelos/integrator-nuxt 4.0.0 → 4.0.1
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/README.md +112 -59
- package/package.json +1 -1
- package/src/cookies.test.ts +112 -0
- package/src/cookies.ts +49 -0
- package/src/middleware.ts +65 -78
- package/src/module.ts +28 -5
- package/src/proxy-target.test.ts +110 -0
- package/src/proxy-target.ts +30 -0
- package/src/runtime/api-proxy.ts +36 -0
- package/src/sdk-factory.ts +17 -89
- package/src/types.ts +9 -33
package/README.md
CHANGED
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
# @qelos/integrator-nuxt
|
|
2
2
|
|
|
3
|
-
Nuxt 3 integrator for [Qelos](https://qelos.io).
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
A token-refresh hook keeps the access token fresh: when the SDK detects an
|
|
9
|
-
expired access token, it transparently refreshes it — either through the
|
|
10
|
-
request's refresh token or, for cookie-only sessions, through the access
|
|
11
|
-
cookie itself — and writes the rotated cookie pair back on the response.
|
|
3
|
+
Nuxt 3 integrator for [Qelos](https://qelos.io). It plugs into a Nuxt app's
|
|
4
|
+
Nitro server to make the Nuxt host act as a same-origin BFF for a managed
|
|
5
|
+
Qelos app: requests under `/api/**` are proxied to Qelos, and every other
|
|
6
|
+
request resolves the current user up front so your route handlers and Vue
|
|
7
|
+
components can use them directly.
|
|
12
8
|
|
|
13
9
|
## Install
|
|
14
10
|
|
|
@@ -16,6 +12,10 @@ cookie itself — and writes the rotated cookie pair back on the response.
|
|
|
16
12
|
pnpm add @qelos/integrator-nuxt
|
|
17
13
|
```
|
|
18
14
|
|
|
15
|
+
> Requires Node 18+ — the middleware uses
|
|
16
|
+
> [`Response.headers.getSetCookie()`](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)
|
|
17
|
+
> to pipe individual upstream `Set-Cookie` headers back to the client.
|
|
18
|
+
|
|
19
19
|
## Configure
|
|
20
20
|
|
|
21
21
|
```ts
|
|
@@ -25,8 +25,6 @@ export default defineNuxtConfig({
|
|
|
25
25
|
qelos: {
|
|
26
26
|
appUrl: 'https://your-qelos-app.com',
|
|
27
27
|
// Optional — defaults shown:
|
|
28
|
-
accessTokenCookie: 'q_access_token',
|
|
29
|
-
refreshTokenCookie: 'q_refresh_token',
|
|
30
28
|
requireAuth: false,
|
|
31
29
|
skipPaths: ['/api/_auth', '/health'],
|
|
32
30
|
},
|
|
@@ -36,6 +34,83 @@ export default defineNuxtConfig({
|
|
|
36
34
|
You can also override any field at runtime via `NUXT_QELOS_*` env vars (Nuxt
|
|
37
35
|
runtime-config conventions apply).
|
|
38
36
|
|
|
37
|
+
## API proxy
|
|
38
|
+
|
|
39
|
+
The module registers a catch-all `/api/**` Nitro server handler that
|
|
40
|
+
transparently proxies any request the consuming Nuxt app does not handle
|
|
41
|
+
itself to the configured Qelos managed-app origin. This lets the Nuxt app
|
|
42
|
+
act as a same-origin BFF: `@qelos/sdk` calls from the browser, server, or
|
|
43
|
+
the Qelos web SDK can all hit `/api/...` on the Nuxt host and reach Qelos
|
|
44
|
+
without CORS or cross-site cookie pain.
|
|
45
|
+
|
|
46
|
+
User-defined `server/api/*.ts` (and `server/routes/*.ts`) routes still
|
|
47
|
+
take precedence — the proxy only catches requests no other handler matched.
|
|
48
|
+
|
|
49
|
+
### Cookie domain rewrite
|
|
50
|
+
|
|
51
|
+
The proxy forwards the incoming `Cookie` header as-is (the Qelos session
|
|
52
|
+
cookie name is treated as opaque) and forwards upstream `Set-Cookie`
|
|
53
|
+
headers back to the client, rewriting the `Domain=` attribute on every
|
|
54
|
+
upstream cookie to the inbound request's own host. That way the session
|
|
55
|
+
cookie set by Qelos is valid on the Nuxt app's domain regardless of which
|
|
56
|
+
host Qelos issues cookies from.
|
|
57
|
+
|
|
58
|
+
### Resolving the proxy target
|
|
59
|
+
|
|
60
|
+
The managed Qelos app URL (`qelos.appUrl`) is the proxy target. Env vars are
|
|
61
|
+
only dev-time overrides for when the configured `appUrl` isn't reachable from
|
|
62
|
+
the local host:
|
|
63
|
+
|
|
64
|
+
1. `NUXT_QELOS_PROXY_TARGET` env var.
|
|
65
|
+
2. `QELOS_IP` env var (dev fallback).
|
|
66
|
+
3. `QELOS_API_IP` env var (dev fallback).
|
|
67
|
+
4. `qelos.appUrl`.
|
|
68
|
+
|
|
69
|
+
If none of these are set, the handler responds with `503` so misconfiguration
|
|
70
|
+
fails loudly.
|
|
71
|
+
|
|
72
|
+
### Opting out
|
|
73
|
+
|
|
74
|
+
Set `qelos.disableProxy: true` in `nuxt.config.ts` to skip registration of
|
|
75
|
+
the proxy handler — useful when the Nuxt app implements every `/api/*`
|
|
76
|
+
route itself or terminates the proxy elsewhere (CDN, reverse proxy, etc.).
|
|
77
|
+
|
|
78
|
+
WebSocket upgrades are not proxied; route them explicitly if needed.
|
|
79
|
+
|
|
80
|
+
## Middleware
|
|
81
|
+
|
|
82
|
+
On every non-`/api/` request, the server middleware identifies the current
|
|
83
|
+
user by calling the managed Qelos app directly:
|
|
84
|
+
|
|
85
|
+
1. Resolve the upstream origin the same way the `/api/**` proxy does
|
|
86
|
+
(`NUXT_QELOS_PROXY_TARGET` → `QELOS_IP` → `QELOS_API_IP` →
|
|
87
|
+
`qelos.appUrl`).
|
|
88
|
+
2. Issue `fetch('${upstream}/api/me')` with the incoming request's `Cookie`
|
|
89
|
+
header forwarded verbatim — the Qelos session cookie name is opaque to
|
|
90
|
+
the integrator, so the whole header is piped through unchanged. Any
|
|
91
|
+
incoming `Authorization` header is forwarded too.
|
|
92
|
+
3. For every `Set-Cookie` header on the upstream response, rewrite the
|
|
93
|
+
`Domain=` attribute to the inbound request's `Host` (port stripped) and
|
|
94
|
+
append it to the outgoing response. This is how session rotations from
|
|
95
|
+
Qelos reach the browser when the managed app and the Nuxt host live on
|
|
96
|
+
different origins.
|
|
97
|
+
4. On `2xx`, parse the JSON body and expose it as
|
|
98
|
+
`event.context.qelos.user`. On any other status (or a network error),
|
|
99
|
+
leave `user = null` — and respond with `401` if `qelos.requireAuth` is
|
|
100
|
+
set.
|
|
101
|
+
|
|
102
|
+
The middleware is independent from the `/api/**` proxy: the proxy handles
|
|
103
|
+
forwarding of API calls themselves, while the middleware identifies the
|
|
104
|
+
user on every page/non-API request before your route handlers run. To
|
|
105
|
+
avoid double-hitting Qelos for `/api/me` (once for proxying, once for user
|
|
106
|
+
resolution), the module adds `/api/` to `skipPaths` automatically when the
|
|
107
|
+
proxy is enabled.
|
|
108
|
+
|
|
109
|
+
> The middleware does not attempt to strip the `Secure` attribute from
|
|
110
|
+
> rotated cookies. In local dev over plain HTTP, browsers will drop
|
|
111
|
+
> `Secure` cookies — configure the managed Qelos app to issue non-`Secure`
|
|
112
|
+
> cookies in that environment, or run the Nuxt host over HTTPS.
|
|
113
|
+
|
|
39
114
|
## Use in server routes
|
|
40
115
|
|
|
41
116
|
The recommended wrapper, `defineQelosEventHandler`, gives you a typed `qelos`
|
|
@@ -76,13 +151,16 @@ export default defineEventHandler((event) => {
|
|
|
76
151
|
|
|
77
152
|
`event.context.qelos` is typed as `QelosRequestContext`:
|
|
78
153
|
|
|
79
|
-
| field | description
|
|
80
|
-
|
|
81
|
-
| `user` | `IUser`
|
|
82
|
-
| `workspace` | The active `IWorkspace` for the request, or `null`.
|
|
83
|
-
| `workspaces` | All workspaces the user has access to.
|
|
84
|
-
| `sdk` | A request-scoped `QelosSDK` instance bound to the
|
|
85
|
-
|
|
154
|
+
| field | description |
|
|
155
|
+
|--------------|------------------------------------------------------------------|
|
|
156
|
+
| `user` | The `IUser` body returned by `/api/me`, or `null` when anonymous. |
|
|
157
|
+
| `workspace` | The active `IWorkspace` for the request, or `null`. |
|
|
158
|
+
| `workspaces` | All workspaces the user has access to. |
|
|
159
|
+
| `sdk` | A request-scoped `QelosSDK` instance bound to the live cookies. |
|
|
160
|
+
|
|
161
|
+
The `sdk` reads cookies from the current `H3Event` on every call, so any
|
|
162
|
+
session rotation piped through by the middleware is picked up automatically
|
|
163
|
+
by subsequent SDK requests in the same handler.
|
|
86
164
|
|
|
87
165
|
## Use in components / pages
|
|
88
166
|
|
|
@@ -104,7 +182,7 @@ const { user, workspace, workspaces, isAuthenticated } = useQelos();
|
|
|
104
182
|
```
|
|
105
183
|
|
|
106
184
|
For data calls from the browser, prefer hitting your own server routes (so
|
|
107
|
-
|
|
185
|
+
session cookies stay on the server):
|
|
108
186
|
|
|
109
187
|
```vue
|
|
110
188
|
<script setup lang="ts">
|
|
@@ -117,41 +195,18 @@ If you need direct browser access to the Qelos API, use
|
|
|
117
195
|
server-side SDK in this package is bound to per-request cookies and isn't
|
|
118
196
|
intended for client use.
|
|
119
197
|
|
|
120
|
-
##
|
|
121
|
-
|
|
122
|
-
When the access token is rejected, the SDK tries to recover, in order:
|
|
198
|
+
## Workspace resolution
|
|
123
199
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
200
|
+
`event.context.qelos.workspace` defaults to whatever the managed Qelos app
|
|
201
|
+
reports on `user.workspace` from `/api/me`. That field is non-null only when
|
|
202
|
+
the user has already activated a workspace on the Qelos side; when it is
|
|
203
|
+
`null`, the frontend is expected to prompt the user to either activate an
|
|
204
|
+
existing workspace or create a new one. The middleware deliberately does
|
|
205
|
+
**not** auto-pick `workspaces[0]` — that would silently put the user into
|
|
206
|
+
the wrong workspace.
|
|
129
207
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
(`HttpOnly`, `SameSite=Lax`).
|
|
133
|
-
|
|
134
|
-
### Manual cookie refresh
|
|
135
|
-
|
|
136
|
-
Long-lived integrator-hosted sessions can also call the SDK directly to
|
|
137
|
-
proactively refresh the cookie token, e.g. from a Nitro route handler:
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
// server/api/session/refresh.post.ts
|
|
141
|
-
import { defineQelosEventHandler } from '@qelos/integrator-nuxt';
|
|
142
|
-
|
|
143
|
-
export default defineQelosEventHandler(async ({ qelos }) => {
|
|
144
|
-
const result = await qelos.sdk.authentication.refreshCookieToken();
|
|
145
|
-
// result.headers['set-cookie'] — fresh cookie value to forward
|
|
146
|
-
return { user: result.payload.user };
|
|
147
|
-
});
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
## Custom workspace resolution / refresh hook
|
|
151
|
-
|
|
152
|
-
If the default behavior (first workspace from `sdk.workspaces.getList()` and a
|
|
153
|
-
cookie-based refresh writeback) doesn't fit your app, register your own
|
|
154
|
-
middleware instead of (or in addition to) the module's default handler:
|
|
208
|
+
To override the default (e.g. force a particular workspace per request),
|
|
209
|
+
register your own middleware:
|
|
155
210
|
|
|
156
211
|
```ts
|
|
157
212
|
// server/middleware/qelos.ts
|
|
@@ -160,12 +215,9 @@ import { createQelosMiddleware } from '@qelos/integrator-nuxt';
|
|
|
160
215
|
export default createQelosMiddleware({
|
|
161
216
|
config: useRuntimeConfig().qelos,
|
|
162
217
|
resolveWorkspace: ({ user, workspaces }) =>
|
|
163
|
-
workspaces.find(w => w._id === user.metadata?.activeWorkspace)
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
setCookie(event, 'q_access_token', newTokens.accessToken, { httpOnly: true });
|
|
167
|
-
setCookie(event, 'q_refresh_token', newTokens.refreshToken, { httpOnly: true });
|
|
168
|
-
},
|
|
218
|
+
workspaces.find(w => w._id === user.metadata?.activeWorkspace)
|
|
219
|
+
|| user.workspace
|
|
220
|
+
|| null,
|
|
169
221
|
});
|
|
170
222
|
```
|
|
171
223
|
|
|
@@ -175,7 +227,8 @@ in `nuxt.config.ts`.
|
|
|
175
227
|
## API token mode
|
|
176
228
|
|
|
177
229
|
For service-to-service deployments where every request shares one Qelos API
|
|
178
|
-
token, set `apiToken` and the middleware will skip the cookie
|
|
230
|
+
token, set `apiToken` and the middleware will skip the cookie flow entirely
|
|
231
|
+
and build an SDK that authenticates with the static token:
|
|
179
232
|
|
|
180
233
|
```ts
|
|
181
234
|
qelos: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qelos/integrator-nuxt",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Nuxt integrator for Qelos: server middleware/module that identifies the user and workspace from the Qelos SDK before your handlers run.",
|
|
6
6
|
"main": "./dist/module.js",
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Run with: `tsx --test integrators/nuxt/src/cookies.test.ts`
|
|
2
|
+
import { describe, it } from 'node:test';
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
import { rewriteSetCookieDomain, rewriteSetCookieDomains } from './cookies';
|
|
5
|
+
|
|
6
|
+
describe('rewriteSetCookieDomain', () => {
|
|
7
|
+
it('replaces a leading-dot Domain value', () => {
|
|
8
|
+
const input = 'sid=abc; Path=/; Domain=.qelos.app; HttpOnly; Secure';
|
|
9
|
+
assert.equal(
|
|
10
|
+
rewriteSetCookieDomain(input, 'example.com'),
|
|
11
|
+
'sid=abc; Path=/; Domain=example.com; HttpOnly; Secure',
|
|
12
|
+
);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('replaces a wildcard Domain value', () => {
|
|
16
|
+
const input = 'sid=abc; Path=/; Domain=*.qelos.app; HttpOnly';
|
|
17
|
+
assert.equal(
|
|
18
|
+
rewriteSetCookieDomain(input, 'example.com'),
|
|
19
|
+
'sid=abc; Path=/; Domain=example.com; HttpOnly',
|
|
20
|
+
);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('returns the cookie unchanged when no Domain attribute is present', () => {
|
|
24
|
+
const input = 'sid=abc; Path=/; HttpOnly; Secure; SameSite=Lax';
|
|
25
|
+
assert.equal(rewriteSetCookieDomain(input, 'example.com'), input);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('strips the port from a host:port newDomain before substitution', () => {
|
|
29
|
+
const input = 'sid=abc; Domain=.qelos.app; Path=/';
|
|
30
|
+
assert.equal(
|
|
31
|
+
rewriteSetCookieDomain(input, 'localhost:3000'),
|
|
32
|
+
'sid=abc; Domain=localhost; Path=/',
|
|
33
|
+
);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('preserves attribute order and other attributes across replacement', () => {
|
|
37
|
+
const input =
|
|
38
|
+
'sid=abc; Path=/; Domain=.qelos.app; HttpOnly; Secure; SameSite=Lax; Max-Age=3600';
|
|
39
|
+
assert.equal(
|
|
40
|
+
rewriteSetCookieDomain(input, 'example.com'),
|
|
41
|
+
'sid=abc; Path=/; Domain=example.com; HttpOnly; Secure; SameSite=Lax; Max-Age=3600',
|
|
42
|
+
);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('preserves an Expires attribute (which contains commas) across replacement', () => {
|
|
46
|
+
const input =
|
|
47
|
+
'sid=abc; Domain=.qelos.app; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Path=/';
|
|
48
|
+
assert.equal(
|
|
49
|
+
rewriteSetCookieDomain(input, 'example.com'),
|
|
50
|
+
'sid=abc; Domain=example.com; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Path=/',
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('matches the Domain attribute name case-insensitively and preserves its casing', () => {
|
|
55
|
+
const input = 'sid=abc; domain=.qelos.app; Path=/';
|
|
56
|
+
assert.equal(
|
|
57
|
+
rewriteSetCookieDomain(input, 'example.com'),
|
|
58
|
+
'sid=abc; domain=example.com; Path=/',
|
|
59
|
+
);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('strips the entire Domain segment when newDomain is undefined', () => {
|
|
63
|
+
const input =
|
|
64
|
+
'sid=abc; Path=/; Domain=.qelos.app; HttpOnly; Secure; SameSite=Lax';
|
|
65
|
+
assert.equal(
|
|
66
|
+
rewriteSetCookieDomain(input, undefined),
|
|
67
|
+
'sid=abc; Path=/; HttpOnly; Secure; SameSite=Lax',
|
|
68
|
+
);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('strips the entire Domain segment when newDomain is an empty string', () => {
|
|
72
|
+
const input = 'sid=abc; Domain=.qelos.app; Path=/';
|
|
73
|
+
assert.equal(
|
|
74
|
+
rewriteSetCookieDomain(input, ''),
|
|
75
|
+
'sid=abc; Path=/',
|
|
76
|
+
);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('removes the Domain segment when it is the last attribute', () => {
|
|
80
|
+
const input = 'sid=abc; Path=/; Domain=.qelos.app';
|
|
81
|
+
assert.equal(
|
|
82
|
+
rewriteSetCookieDomain(input, undefined),
|
|
83
|
+
'sid=abc; Path=/',
|
|
84
|
+
);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe('rewriteSetCookieDomains', () => {
|
|
89
|
+
it('applies the rewrite to each entry of an array', () => {
|
|
90
|
+
const values = [
|
|
91
|
+
'a=1; Domain=.qelos.app; Path=/',
|
|
92
|
+
'b=2; Path=/; HttpOnly',
|
|
93
|
+
'c=3; Domain=*.qelos.app; Secure',
|
|
94
|
+
];
|
|
95
|
+
assert.deepEqual(rewriteSetCookieDomains(values, 'example.com'), [
|
|
96
|
+
'a=1; Domain=example.com; Path=/',
|
|
97
|
+
'b=2; Path=/; HttpOnly',
|
|
98
|
+
'c=3; Domain=example.com; Secure',
|
|
99
|
+
]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('strips the Domain segment from each entry when newDomain is undefined', () => {
|
|
103
|
+
const values = [
|
|
104
|
+
'a=1; Domain=.qelos.app; Path=/',
|
|
105
|
+
'b=2; Domain=*.qelos.app; HttpOnly',
|
|
106
|
+
];
|
|
107
|
+
assert.deepEqual(rewriteSetCookieDomains(values, undefined), [
|
|
108
|
+
'a=1; Path=/',
|
|
109
|
+
'b=2; HttpOnly',
|
|
110
|
+
]);
|
|
111
|
+
});
|
|
112
|
+
});
|
package/src/cookies.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrite the `Domain=` attribute of a single `Set-Cookie` header value.
|
|
3
|
+
*
|
|
4
|
+
* - If the cookie contains a `Domain=<value>` attribute (case-insensitive), its
|
|
5
|
+
* value is replaced with `newDomain`, with any trailing `:port` suffix
|
|
6
|
+
* stripped first (cookie `Domain` attributes do not include a port).
|
|
7
|
+
* - If `newDomain` is `undefined` (or empty), the entire `; Domain=<value>`
|
|
8
|
+
* segment is removed so the browser scopes the cookie to the current host.
|
|
9
|
+
* - If no `Domain=` attribute is present, the input is returned unchanged.
|
|
10
|
+
*
|
|
11
|
+
* All other attributes, their casing/order and the original cookie name/value
|
|
12
|
+
* bytes are preserved.
|
|
13
|
+
*/
|
|
14
|
+
export function rewriteSetCookieDomain(
|
|
15
|
+
setCookie: string,
|
|
16
|
+
newDomain: string | undefined,
|
|
17
|
+
): string {
|
|
18
|
+
const domainSegment = /;\s*Domain\s*=\s*[^;]+/i;
|
|
19
|
+
if (!domainSegment.test(setCookie)) return setCookie;
|
|
20
|
+
|
|
21
|
+
const stripped = newDomain ? stripPort(newDomain) : '';
|
|
22
|
+
if (!stripped) {
|
|
23
|
+
return setCookie.replace(domainSegment, '');
|
|
24
|
+
}
|
|
25
|
+
return setCookie.replace(
|
|
26
|
+
/(;\s*Domain\s*=\s*)[^;]+/i,
|
|
27
|
+
`$1${stripped}`,
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Apply {@link rewriteSetCookieDomain} to each entry of a `Set-Cookie` array
|
|
33
|
+
* (e.g. the result of `Headers.getSetCookie()`).
|
|
34
|
+
*/
|
|
35
|
+
export function rewriteSetCookieDomains(
|
|
36
|
+
values: string[],
|
|
37
|
+
newDomain: string | undefined,
|
|
38
|
+
): string[] {
|
|
39
|
+
return values.map((value) => rewriteSetCookieDomain(value, newDomain));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function stripPort(host: string): string {
|
|
43
|
+
if (host.startsWith('[')) {
|
|
44
|
+
const end = host.indexOf(']');
|
|
45
|
+
return end === -1 ? host : host.slice(1, end);
|
|
46
|
+
}
|
|
47
|
+
const colon = host.indexOf(':');
|
|
48
|
+
return colon === -1 ? host : host.slice(0, colon);
|
|
49
|
+
}
|
package/src/middleware.ts
CHANGED
|
@@ -1,34 +1,23 @@
|
|
|
1
1
|
import {
|
|
2
|
+
appendResponseHeader,
|
|
3
|
+
createError,
|
|
2
4
|
defineEventHandler,
|
|
3
|
-
getCookie,
|
|
4
5
|
getRequestHeader,
|
|
5
|
-
setCookie,
|
|
6
|
-
createError,
|
|
7
6
|
type H3Event,
|
|
8
7
|
} from 'h3';
|
|
9
8
|
import type { IUser } from '@qelos/sdk/dist/authentication';
|
|
10
9
|
import type { IWorkspace } from '@qelos/sdk/workspaces';
|
|
10
|
+
import { rewriteSetCookieDomain } from './cookies';
|
|
11
|
+
import { resolveQelosProxyTarget } from './proxy-target';
|
|
11
12
|
import { createRequestSdk } from './sdk-factory';
|
|
12
|
-
import type {
|
|
13
|
-
QelosNuxtRuntimeConfig,
|
|
14
|
-
QelosRequestContext,
|
|
15
|
-
QelosTokenPair,
|
|
16
|
-
TokenRefreshHook,
|
|
17
|
-
} from './types';
|
|
18
|
-
|
|
19
|
-
const DEFAULT_ACCESS_COOKIE = 'q_access_token';
|
|
20
|
-
const DEFAULT_REFRESH_COOKIE = 'q_refresh_token';
|
|
13
|
+
import type { QelosNuxtRuntimeConfig, QelosRequestContext } from './types';
|
|
21
14
|
|
|
22
15
|
export interface CreateMiddlewareOptions {
|
|
23
16
|
config: QelosNuxtRuntimeConfig;
|
|
24
17
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
|
|
28
|
-
onTokenRefresh?: TokenRefreshHook;
|
|
29
|
-
/**
|
|
30
|
-
* Resolve the active workspace for a request. Defaults to picking the first
|
|
31
|
-
* workspace returned from `sdk.workspaces.getList()`.
|
|
18
|
+
* Resolve the active workspace for a request. Defaults to whatever
|
|
19
|
+
* `/api/me` reports on `user.workspace` (the user's currently activated
|
|
20
|
+
* workspace, or `null` when none is active).
|
|
32
21
|
*/
|
|
33
22
|
resolveWorkspace?: (params: {
|
|
34
23
|
event: H3Event;
|
|
@@ -37,43 +26,6 @@ export interface CreateMiddlewareOptions {
|
|
|
37
26
|
}) => IWorkspace | null | Promise<IWorkspace | null>;
|
|
38
27
|
}
|
|
39
28
|
|
|
40
|
-
function readTokens(event: H3Event, config: QelosNuxtRuntimeConfig): QelosTokenPair {
|
|
41
|
-
const accessCookie = config.accessTokenCookie || DEFAULT_ACCESS_COOKIE;
|
|
42
|
-
const refreshCookie = config.refreshTokenCookie || DEFAULT_REFRESH_COOKIE;
|
|
43
|
-
|
|
44
|
-
const cookieAccess = getCookie(event, accessCookie);
|
|
45
|
-
const cookieRefresh = getCookie(event, refreshCookie);
|
|
46
|
-
|
|
47
|
-
const authHeader = getRequestHeader(event, 'authorization');
|
|
48
|
-
const headerAccess = authHeader && authHeader.toLowerCase().startsWith('bearer ')
|
|
49
|
-
? authHeader.slice(7).trim()
|
|
50
|
-
: undefined;
|
|
51
|
-
|
|
52
|
-
return {
|
|
53
|
-
accessToken: headerAccess || cookieAccess || undefined,
|
|
54
|
-
refreshToken: cookieRefresh || undefined,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function writeTokensToCookies(
|
|
59
|
-
event: H3Event,
|
|
60
|
-
config: QelosNuxtRuntimeConfig,
|
|
61
|
-
tokens: { accessToken: string; refreshToken?: string },
|
|
62
|
-
) {
|
|
63
|
-
const accessCookie = config.accessTokenCookie || DEFAULT_ACCESS_COOKIE;
|
|
64
|
-
const refreshCookie = config.refreshTokenCookie || DEFAULT_REFRESH_COOKIE;
|
|
65
|
-
const cookieOptions = {
|
|
66
|
-
httpOnly: true,
|
|
67
|
-
secure: true,
|
|
68
|
-
sameSite: 'lax' as const,
|
|
69
|
-
path: '/',
|
|
70
|
-
};
|
|
71
|
-
setCookie(event, accessCookie, tokens.accessToken, cookieOptions);
|
|
72
|
-
if (tokens.refreshToken) {
|
|
73
|
-
setCookie(event, refreshCookie, tokens.refreshToken, cookieOptions);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
29
|
function shouldSkip(event: H3Event, config: QelosNuxtRuntimeConfig): boolean {
|
|
78
30
|
if (!config.skipPaths?.length) {
|
|
79
31
|
return false;
|
|
@@ -82,41 +34,74 @@ function shouldSkip(event: H3Event, config: QelosNuxtRuntimeConfig): boolean {
|
|
|
82
34
|
return config.skipPaths.some((prefix) => path.startsWith(prefix));
|
|
83
35
|
}
|
|
84
36
|
|
|
37
|
+
function buildMeUrl(base: string): string {
|
|
38
|
+
return `${base.replace(/\/+$/, '')}/api/me`;
|
|
39
|
+
}
|
|
40
|
+
|
|
85
41
|
export function createQelosMiddleware(options: CreateMiddlewareOptions) {
|
|
86
42
|
const { config, resolveWorkspace } = options;
|
|
87
|
-
const onTokenRefresh: TokenRefreshHook = options.onTokenRefresh
|
|
88
|
-
|| (async ({ event, newTokens }) => {
|
|
89
|
-
writeTokensToCookies(event, config, newTokens);
|
|
90
|
-
});
|
|
91
43
|
|
|
92
44
|
return defineEventHandler(async (event) => {
|
|
93
45
|
if (shouldSkip(event, config)) {
|
|
94
46
|
return;
|
|
95
47
|
}
|
|
96
48
|
|
|
97
|
-
const
|
|
98
|
-
const sdk = createRequestSdk({ config, tokens, event, onTokenRefresh });
|
|
49
|
+
const sdk = createRequestSdk({ config, event });
|
|
99
50
|
|
|
100
51
|
const ctx: QelosRequestContext = {
|
|
101
52
|
user: null,
|
|
102
53
|
workspace: null,
|
|
103
54
|
workspaces: [],
|
|
104
55
|
sdk,
|
|
105
|
-
tokens,
|
|
106
56
|
};
|
|
107
57
|
event.context.qelos = ctx;
|
|
108
58
|
|
|
109
|
-
const
|
|
110
|
-
if (!
|
|
59
|
+
const base = resolveQelosProxyTarget(config);
|
|
60
|
+
if (!base && !config.apiToken) {
|
|
111
61
|
if (config.requireAuth) {
|
|
112
62
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
113
63
|
}
|
|
114
64
|
return;
|
|
115
65
|
}
|
|
116
66
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
67
|
+
if (base) {
|
|
68
|
+
const headers: Record<string, string> = {};
|
|
69
|
+
const cookieHeader = getRequestHeader(event, 'cookie');
|
|
70
|
+
if (cookieHeader) headers.cookie = cookieHeader;
|
|
71
|
+
const authHeader = getRequestHeader(event, 'authorization');
|
|
72
|
+
if (authHeader) headers.authorization = authHeader;
|
|
73
|
+
|
|
74
|
+
const originalHost = getRequestHeader(event, 'host');
|
|
75
|
+
|
|
76
|
+
let response: Response | undefined;
|
|
77
|
+
try {
|
|
78
|
+
response = await fetch(buildMeUrl(base), {
|
|
79
|
+
method: 'GET',
|
|
80
|
+
headers,
|
|
81
|
+
redirect: 'manual',
|
|
82
|
+
});
|
|
83
|
+
} catch {
|
|
84
|
+
if (config.requireAuth) {
|
|
85
|
+
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
86
|
+
}
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const setCookieValues = response.headers.getSetCookie?.() ?? [];
|
|
91
|
+
for (const value of setCookieValues) {
|
|
92
|
+
appendResponseHeader(event, 'set-cookie', rewriteSetCookieDomain(value, originalHost));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (response.ok) {
|
|
96
|
+
try {
|
|
97
|
+
ctx.user = (await response.json()) as IUser;
|
|
98
|
+
} catch {
|
|
99
|
+
ctx.user = null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (!ctx.user) {
|
|
120
105
|
if (config.requireAuth) {
|
|
121
106
|
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
|
|
122
107
|
}
|
|
@@ -129,16 +114,18 @@ export function createQelosMiddleware(options: CreateMiddlewareOptions) {
|
|
|
129
114
|
ctx.workspaces = [];
|
|
130
115
|
}
|
|
131
116
|
|
|
132
|
-
if (
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
|
|
117
|
+
if (resolveWorkspace) {
|
|
118
|
+
ctx.workspace = (await resolveWorkspace({
|
|
119
|
+
event,
|
|
120
|
+
user: ctx.user,
|
|
121
|
+
workspaces: ctx.workspaces,
|
|
122
|
+
})) || null;
|
|
123
|
+
} else {
|
|
124
|
+
// `/api/me` carries `user.workspace` (`{ _id, name, roles }`) only when
|
|
125
|
+
// the user has activated a workspace. Null means the frontend must
|
|
126
|
+
// prompt to activate/create one — don't silently pick workspaces[0].
|
|
127
|
+
ctx.workspace =
|
|
128
|
+
(ctx.user as unknown as { workspace?: IWorkspace | null }).workspace || null;
|
|
142
129
|
}
|
|
143
130
|
});
|
|
144
131
|
}
|
package/src/module.ts
CHANGED
|
@@ -13,6 +13,11 @@ export interface QelosNuxtModuleOptions extends QelosNuxtRuntimeConfig {
|
|
|
13
13
|
* want to call `createQelosMiddleware` yourself from your own server route.
|
|
14
14
|
*/
|
|
15
15
|
disableMiddleware?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Disable registration of the catch-all `/api/**` proxy server handler.
|
|
18
|
+
* Defaults to `false`.
|
|
19
|
+
*/
|
|
20
|
+
disableProxy?: boolean;
|
|
16
21
|
}
|
|
17
22
|
|
|
18
23
|
export default defineNuxtModule<QelosNuxtModuleOptions>({
|
|
@@ -33,7 +38,22 @@ export default defineNuxtModule<QelosNuxtModuleOptions>({
|
|
|
33
38
|
|
|
34
39
|
const { resolve } = createResolver(import.meta.url);
|
|
35
40
|
|
|
36
|
-
const { disableMiddleware, ...runtimeConfig } = options;
|
|
41
|
+
const { disableMiddleware, disableProxy, ...runtimeConfig } = options;
|
|
42
|
+
|
|
43
|
+
if (!disableProxy) {
|
|
44
|
+
// When the catch-all `/api/**` proxy is enabled, the user-resolution
|
|
45
|
+
// middleware MUST skip `/api/` requests. The middleware itself calls
|
|
46
|
+
// `${appUrl}/api/me` to identify the user, so without this skip
|
|
47
|
+
// every inbound `/api/me` would be both proxied AND used as the
|
|
48
|
+
// identification probe — a duplicate upstream hit and a potential
|
|
49
|
+
// cookie-rewrite loop. Users can extend `skipPaths` further but
|
|
50
|
+
// `/api/` must remain covered whenever `disableProxy` is false.
|
|
51
|
+
const existingSkipPaths = runtimeConfig.skipPaths ?? [];
|
|
52
|
+
const alreadyCovered = existingSkipPaths.some((prefix) => '/api/'.startsWith(prefix));
|
|
53
|
+
if (!alreadyCovered) {
|
|
54
|
+
runtimeConfig.skipPaths = ['/api/', ...existingSkipPaths];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
37
57
|
|
|
38
58
|
nuxt.options.runtimeConfig.qelos = {
|
|
39
59
|
...(nuxt.options.runtimeConfig.qelos as Record<string, unknown> | undefined),
|
|
@@ -47,6 +67,13 @@ export default defineNuxtModule<QelosNuxtModuleOptions>({
|
|
|
47
67
|
});
|
|
48
68
|
}
|
|
49
69
|
|
|
70
|
+
if (!disableProxy) {
|
|
71
|
+
addServerHandler({
|
|
72
|
+
route: '/api/**',
|
|
73
|
+
handler: resolve('./runtime/api-proxy'),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
50
77
|
addImportsDir(resolve('./runtime/composables'));
|
|
51
78
|
|
|
52
79
|
addTypeTemplate({
|
|
@@ -77,8 +104,4 @@ export type {
|
|
|
77
104
|
export type {
|
|
78
105
|
QelosNuxtRuntimeConfig,
|
|
79
106
|
QelosRequestContext,
|
|
80
|
-
QelosTokenPair,
|
|
81
|
-
ResolvedTokens,
|
|
82
|
-
TokenRefreshContext,
|
|
83
|
-
TokenRefreshHook,
|
|
84
107
|
} from './types';
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { describe, it, beforeEach, afterEach } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { resolveQelosProxyTarget } from './proxy-target';
|
|
4
|
+
import type { QelosNuxtRuntimeConfig } from './types';
|
|
5
|
+
|
|
6
|
+
const PROXY_ENV_KEYS = [
|
|
7
|
+
'NUXT_QELOS_PROXY_TARGET',
|
|
8
|
+
'QELOS_IP',
|
|
9
|
+
'QELOS_API_IP',
|
|
10
|
+
] as const;
|
|
11
|
+
|
|
12
|
+
function clearProxyEnv(): void {
|
|
13
|
+
for (const key of PROXY_ENV_KEYS) {
|
|
14
|
+
delete process.env[key];
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('resolveQelosProxyTarget', () => {
|
|
19
|
+
const savedEnv: Record<string, string | undefined> = {};
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
for (const key of PROXY_ENV_KEYS) {
|
|
23
|
+
savedEnv[key] = process.env[key];
|
|
24
|
+
}
|
|
25
|
+
clearProxyEnv();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
for (const key of PROXY_ENV_KEYS) {
|
|
30
|
+
if (savedEnv[key] === undefined) {
|
|
31
|
+
delete process.env[key];
|
|
32
|
+
} else {
|
|
33
|
+
process.env[key] = savedEnv[key];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('uses NUXT_QELOS_PROXY_TARGET when set, even if other env vars and appUrl exist', () => {
|
|
39
|
+
process.env.NUXT_QELOS_PROXY_TARGET = 'https://from-nuxt-env.example';
|
|
40
|
+
process.env.QELOS_IP = 'https://from-qelos-ip.example';
|
|
41
|
+
process.env.QELOS_API_IP = 'https://from-qelos-api-ip.example';
|
|
42
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
43
|
+
appUrl: 'https://from-app-url.example',
|
|
44
|
+
};
|
|
45
|
+
assert.equal(
|
|
46
|
+
resolveQelosProxyTarget(config),
|
|
47
|
+
'https://from-nuxt-env.example',
|
|
48
|
+
);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('falls back to QELOS_IP when NUXT_QELOS_PROXY_TARGET is unset', () => {
|
|
52
|
+
process.env.QELOS_IP = 'https://from-qelos-ip.example';
|
|
53
|
+
process.env.QELOS_API_IP = 'https://from-qelos-api-ip.example';
|
|
54
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
55
|
+
appUrl: 'https://from-app-url.example',
|
|
56
|
+
};
|
|
57
|
+
assert.equal(
|
|
58
|
+
resolveQelosProxyTarget(config),
|
|
59
|
+
'https://from-qelos-ip.example',
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('falls back to QELOS_API_IP when higher-priority env vars are unset', () => {
|
|
64
|
+
process.env.QELOS_API_IP = 'https://from-qelos-api-ip.example';
|
|
65
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
66
|
+
appUrl: 'https://from-app-url.example',
|
|
67
|
+
};
|
|
68
|
+
assert.equal(
|
|
69
|
+
resolveQelosProxyTarget(config),
|
|
70
|
+
'https://from-qelos-api-ip.example',
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('falls back to config.appUrl when no env var is set', () => {
|
|
75
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
76
|
+
appUrl: 'https://from-app-url.example',
|
|
77
|
+
};
|
|
78
|
+
assert.equal(
|
|
79
|
+
resolveQelosProxyTarget(config),
|
|
80
|
+
'https://from-app-url.example',
|
|
81
|
+
);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('returns undefined when nothing is configured', () => {
|
|
85
|
+
const config: QelosNuxtRuntimeConfig = { appUrl: '' };
|
|
86
|
+
assert.equal(resolveQelosProxyTarget(config), undefined);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('treats whitespace-only values as unset', () => {
|
|
90
|
+
process.env.NUXT_QELOS_PROXY_TARGET = ' ';
|
|
91
|
+
process.env.QELOS_IP = '\t';
|
|
92
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
93
|
+
appUrl: 'https://from-app-url.example',
|
|
94
|
+
};
|
|
95
|
+
assert.equal(
|
|
96
|
+
resolveQelosProxyTarget(config),
|
|
97
|
+
'https://from-app-url.example',
|
|
98
|
+
);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('trims surrounding whitespace from resolved values', () => {
|
|
102
|
+
const config: QelosNuxtRuntimeConfig = {
|
|
103
|
+
appUrl: ' https://trimmed.example ',
|
|
104
|
+
};
|
|
105
|
+
assert.equal(
|
|
106
|
+
resolveQelosProxyTarget(config),
|
|
107
|
+
'https://trimmed.example',
|
|
108
|
+
);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { QelosNuxtRuntimeConfig } from './types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolve the origin to which `/api/**` requests are proxied. The managed
|
|
5
|
+
* Qelos app URL (`config.appUrl`) is the proxy target — env vars are only
|
|
6
|
+
* dev-time overrides when the configured `appUrl` is not reachable from
|
|
7
|
+
* the local host.
|
|
8
|
+
*
|
|
9
|
+
* Priority (highest first):
|
|
10
|
+
* 1. `process.env.NUXT_QELOS_PROXY_TARGET`
|
|
11
|
+
* 2. `process.env.QELOS_IP`
|
|
12
|
+
* 3. `process.env.QELOS_API_IP`
|
|
13
|
+
* 4. `config.appUrl`
|
|
14
|
+
*
|
|
15
|
+
* Empty / whitespace-only values are skipped, and `undefined` is returned when
|
|
16
|
+
* nothing is configured so the caller can surface a clear error.
|
|
17
|
+
*/
|
|
18
|
+
export function resolveQelosProxyTarget(
|
|
19
|
+
config: QelosNuxtRuntimeConfig,
|
|
20
|
+
): string | undefined {
|
|
21
|
+
const env = process.env;
|
|
22
|
+
const fromEnv =
|
|
23
|
+
env.NUXT_QELOS_PROXY_TARGET?.trim() ||
|
|
24
|
+
env.QELOS_IP?.trim() ||
|
|
25
|
+
env.QELOS_API_IP?.trim();
|
|
26
|
+
if (fromEnv) return fromEnv;
|
|
27
|
+
|
|
28
|
+
const fromAppUrl = config.appUrl?.trim();
|
|
29
|
+
return fromAppUrl || undefined;
|
|
30
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// This file is registered as a Nuxt server handler by `module.ts`. It is
|
|
2
|
+
// bundled by Nitro, so `#imports` resolves at the consuming-app build time
|
|
3
|
+
// (not at this package's `tsc` build).
|
|
4
|
+
// @ts-ignore - resolved by Nitro
|
|
5
|
+
import { useRuntimeConfig } from '#imports';
|
|
6
|
+
import {
|
|
7
|
+
createError,
|
|
8
|
+
defineEventHandler,
|
|
9
|
+
getRequestHeader,
|
|
10
|
+
proxyRequest,
|
|
11
|
+
} from 'h3';
|
|
12
|
+
// @ts-ignore - resolved by Nitro (transitive dep of Nuxt)
|
|
13
|
+
import { joinURL } from 'ufo';
|
|
14
|
+
import { resolveQelosProxyTarget } from '../proxy-target';
|
|
15
|
+
import type { QelosNuxtRuntimeConfig } from '../types';
|
|
16
|
+
|
|
17
|
+
export default defineEventHandler((event) => {
|
|
18
|
+
const config = (useRuntimeConfig().qelos || {}) as QelosNuxtRuntimeConfig;
|
|
19
|
+
const base = resolveQelosProxyTarget(config);
|
|
20
|
+
if (!base) {
|
|
21
|
+
throw createError({
|
|
22
|
+
statusCode: 503,
|
|
23
|
+
statusMessage:
|
|
24
|
+
'[@qelos/integrator-nuxt] Qelos API proxy is not configured. Set qelos.appUrl (or NUXT_QELOS_PROXY_TARGET / QELOS_IP / QELOS_API_IP in development).',
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const originalHost = getRequestHeader(event, 'host');
|
|
29
|
+
const path = event.path.split('?')[0] ?? event.path;
|
|
30
|
+
const target = joinURL(base, path);
|
|
31
|
+
|
|
32
|
+
return proxyRequest(event, target, {
|
|
33
|
+
fetch: globalThis.fetch,
|
|
34
|
+
cookieDomainRewrite: { '*': originalHost ?? '' },
|
|
35
|
+
});
|
|
36
|
+
});
|
package/src/sdk-factory.ts
CHANGED
|
@@ -1,111 +1,39 @@
|
|
|
1
1
|
import QelosSDK from '@qelos/sdk';
|
|
2
2
|
import type { QelosSDKOptions, FetchLike } from '@qelos/sdk/types';
|
|
3
|
-
import type
|
|
4
|
-
|
|
5
|
-
QelosTokenPair,
|
|
6
|
-
ResolvedTokens,
|
|
7
|
-
TokenRefreshHook,
|
|
8
|
-
} from './types';
|
|
9
|
-
import type { H3Event } from 'h3';
|
|
3
|
+
import { getRequestHeader, type H3Event } from 'h3';
|
|
4
|
+
import type { QelosNuxtRuntimeConfig } from './types';
|
|
10
5
|
|
|
11
6
|
export interface CreateSdkParams {
|
|
12
7
|
config: QelosNuxtRuntimeConfig;
|
|
13
|
-
/**
|
|
14
|
-
* Tokens for the current request. The factory mutates this object in
|
|
15
|
-
* place when a token refresh occurs, so callers can read the latest pair
|
|
16
|
-
* after the SDK has been used.
|
|
17
|
-
*/
|
|
18
|
-
tokens: QelosTokenPair;
|
|
19
8
|
event: H3Event;
|
|
20
|
-
onTokenRefresh?: TokenRefreshHook;
|
|
21
9
|
}
|
|
22
10
|
|
|
23
|
-
|
|
24
|
-
'/api/token/refresh',
|
|
25
|
-
'/api/cookie/refresh',
|
|
26
|
-
'/api/signin',
|
|
27
|
-
'/api/signup',
|
|
28
|
-
]);
|
|
29
|
-
|
|
30
|
-
export function createRequestSdk({ config, tokens, event, onTokenRefresh }: CreateSdkParams): QelosSDK {
|
|
31
|
-
let sdk: QelosSDK;
|
|
32
|
-
let refreshInFlight: Promise<void> | null = null;
|
|
33
|
-
|
|
11
|
+
export function createRequestSdk({ config, event }: CreateSdkParams): QelosSDK {
|
|
34
12
|
const baseOptions: Partial<QelosSDKOptions> = config.sdkOptions || {};
|
|
35
13
|
|
|
36
|
-
async function performRefresh(): Promise<void> {
|
|
37
|
-
if (!tokens.refreshToken && !tokens.accessToken) {
|
|
38
|
-
throw new Error('no refresh token available');
|
|
39
|
-
}
|
|
40
|
-
const previous: QelosTokenPair = {
|
|
41
|
-
accessToken: tokens.accessToken,
|
|
42
|
-
refreshToken: tokens.refreshToken,
|
|
43
|
-
};
|
|
44
|
-
let refreshed: ResolvedTokens;
|
|
45
|
-
if (tokens.refreshToken) {
|
|
46
|
-
const result = await sdk.authentication.refreshToken(tokens.refreshToken);
|
|
47
|
-
refreshed = {
|
|
48
|
-
accessToken: result.payload.token,
|
|
49
|
-
refreshToken: result.payload.refreshToken,
|
|
50
|
-
};
|
|
51
|
-
} else {
|
|
52
|
-
const result = await sdk.authentication.refreshCookieToken(tokens.accessToken);
|
|
53
|
-
refreshed = {
|
|
54
|
-
accessToken: result.payload.cookieToken,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
tokens.accessToken = refreshed.accessToken;
|
|
58
|
-
tokens.refreshToken = refreshed.refreshToken;
|
|
59
|
-
if (onTokenRefresh) {
|
|
60
|
-
await onTokenRefresh({ event, oldTokens: previous, newTokens: refreshed, sdk });
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function ensureRefresh(): Promise<void> {
|
|
65
|
-
if (!refreshInFlight) {
|
|
66
|
-
refreshInFlight = performRefresh().finally(() => {
|
|
67
|
-
refreshInFlight = null;
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
return refreshInFlight;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
14
|
const options: QelosSDKOptions = {
|
|
74
15
|
appUrl: config.appUrl,
|
|
75
16
|
fetch: (globalThis.fetch as unknown as FetchLike),
|
|
76
|
-
forceRefresh: !config.apiToken,
|
|
77
17
|
...baseOptions,
|
|
78
18
|
};
|
|
79
19
|
|
|
80
20
|
if (config.apiToken) {
|
|
81
21
|
options.apiToken = config.apiToken;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
22
|
+
return new QelosSDK(options);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
options.extraHeaders = async () => {
|
|
26
|
+
const headers: Record<string, string> = {};
|
|
27
|
+
const cookieHeader = getRequestHeader(event, 'cookie');
|
|
28
|
+
if (cookieHeader) {
|
|
29
|
+
headers.cookie = cookieHeader;
|
|
85
30
|
}
|
|
86
|
-
|
|
87
|
-
|
|
31
|
+
const authHeader = getRequestHeader(event, 'authorization');
|
|
32
|
+
if (authHeader) {
|
|
33
|
+
headers.authorization = authHeader;
|
|
88
34
|
}
|
|
35
|
+
return headers;
|
|
36
|
+
};
|
|
89
37
|
|
|
90
|
-
|
|
91
|
-
if (NO_AUTH_URLS.has(relativeUrl)) {
|
|
92
|
-
return {};
|
|
93
|
-
}
|
|
94
|
-
if (forceRefresh && tokens.refreshToken) {
|
|
95
|
-
await ensureRefresh();
|
|
96
|
-
}
|
|
97
|
-
const token = sdk?.authentication?.accessToken || tokens.accessToken;
|
|
98
|
-
if (token) {
|
|
99
|
-
return { authorization: 'Bearer ' + token };
|
|
100
|
-
}
|
|
101
|
-
return {};
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
options.onFailedRefreshToken = async () => {
|
|
105
|
-
await ensureRefresh();
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
sdk = new QelosSDK(options);
|
|
110
|
-
return sdk;
|
|
38
|
+
return new QelosSDK(options);
|
|
111
39
|
}
|
package/src/types.ts
CHANGED
|
@@ -3,11 +3,6 @@ import type { IUser } from '@qelos/sdk/dist/authentication';
|
|
|
3
3
|
import type { IWorkspace } from '@qelos/sdk/workspaces';
|
|
4
4
|
import type { QelosSDKOptions } from '@qelos/sdk/types';
|
|
5
5
|
|
|
6
|
-
export interface QelosTokenPair {
|
|
7
|
-
accessToken?: string;
|
|
8
|
-
refreshToken?: string;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
6
|
export interface QelosNuxtRuntimeConfig {
|
|
12
7
|
/**
|
|
13
8
|
* Base URL of the Qelos backend (e.g. https://yourdomain.com).
|
|
@@ -15,17 +10,9 @@ export interface QelosNuxtRuntimeConfig {
|
|
|
15
10
|
appUrl: string;
|
|
16
11
|
/**
|
|
17
12
|
* Static API token used for service-to-service calls. When provided, no
|
|
18
|
-
* cookie
|
|
13
|
+
* cookie-based authentication is performed.
|
|
19
14
|
*/
|
|
20
15
|
apiToken?: string;
|
|
21
|
-
/**
|
|
22
|
-
* Cookie name carrying the Qelos access token. Defaults to `q_access_token`.
|
|
23
|
-
*/
|
|
24
|
-
accessTokenCookie?: string;
|
|
25
|
-
/**
|
|
26
|
-
* Cookie name carrying the Qelos refresh token. Defaults to `q_refresh_token`.
|
|
27
|
-
*/
|
|
28
|
-
refreshTokenCookie?: string;
|
|
29
16
|
/**
|
|
30
17
|
* Path to mount the server middleware on. Defaults to `''` (every request).
|
|
31
18
|
*/
|
|
@@ -44,22 +31,13 @@ export interface QelosNuxtRuntimeConfig {
|
|
|
44
31
|
* Optional extra options merged into the per-request SDK instance.
|
|
45
32
|
*/
|
|
46
33
|
sdkOptions?: Partial<QelosSDKOptions>;
|
|
34
|
+
/**
|
|
35
|
+
* If true, the catch-all `/api/**` proxy handler is not registered.
|
|
36
|
+
* Defaults to `false`.
|
|
37
|
+
*/
|
|
38
|
+
disableProxy?: boolean;
|
|
47
39
|
}
|
|
48
40
|
|
|
49
|
-
export interface ResolvedTokens {
|
|
50
|
-
accessToken: string;
|
|
51
|
-
refreshToken?: string;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface TokenRefreshContext {
|
|
55
|
-
event: import('h3').H3Event;
|
|
56
|
-
oldTokens: QelosTokenPair;
|
|
57
|
-
newTokens: ResolvedTokens;
|
|
58
|
-
sdk: QelosSDK;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export type TokenRefreshHook = (ctx: TokenRefreshContext) => void | Promise<void>;
|
|
62
|
-
|
|
63
41
|
export interface QelosRequestContext {
|
|
64
42
|
/**
|
|
65
43
|
* The authenticated user, or `null` when anonymous.
|
|
@@ -75,13 +53,11 @@ export interface QelosRequestContext {
|
|
|
75
53
|
*/
|
|
76
54
|
workspaces: IWorkspace[];
|
|
77
55
|
/**
|
|
78
|
-
* SDK instance bound to the current request's
|
|
56
|
+
* SDK instance bound to the current request's cookies. `extraHeaders`
|
|
57
|
+
* re-reads cookies live on each call, so cookie rotations applied by the
|
|
58
|
+
* middleware are picked up automatically.
|
|
79
59
|
*/
|
|
80
60
|
sdk: QelosSDK;
|
|
81
|
-
/**
|
|
82
|
-
* Tokens read from the request. Mutated when a refresh occurs.
|
|
83
|
-
*/
|
|
84
|
-
tokens: QelosTokenPair;
|
|
85
61
|
}
|
|
86
62
|
|
|
87
63
|
declare module 'h3' {
|