@ionite/adapters 0.0.0-stage → 0.1.0-beta.20261118.2

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/src/serve.ts ADDED
@@ -0,0 +1,292 @@
1
+ import {
2
+ captureRedirect,
3
+ defaultRedirectPolicies,
4
+ envConfig,
5
+ getWorkload,
6
+ hasPermission,
7
+ ionite,
8
+ prettyLogger,
9
+ resolveCapturedRedirect,
10
+ } from '@ionite/server';
11
+ import { createValidators } from '@ionite/zod';
12
+ import { createAdapterApi } from './api';
13
+ import type { SignInRequest, SignInResponse } from './contract';
14
+ import { type CredentialStore, credentialStoreFromEnv } from './credentials';
15
+ import type { AdapterDefinition } from './define';
16
+ import { connectForm, donePage, messagePage, readConnectionForm, verifyFailureMessage } from './onboard-page';
17
+ import { storesFromEnv } from './stores';
18
+
19
+ /** The permission ionite's callers hold on an adapter, the same one Tenant Management requires. */
20
+ const TENANT_MANAGE = 'ion:tenant:manage';
21
+ const SIGN_IN_TTL_MS = 5 * 60_000;
22
+
23
+ /** `returnUrl` arrives on the tenant create request and is redirected to, so only http(s) passes. */
24
+ function safeReturnUrl(value: string | undefined): string | undefined {
25
+ if (!value || !URL.canParse(value)) return undefined;
26
+ const { protocol } = new URL(value);
27
+ return protocol === 'https:' || protocol === 'http:' ? value : undefined;
28
+ }
29
+
30
+ export interface ServeAdapterOptions<Connection> {
31
+ /** Default: `PORT`, else 4195. Not 4190: it is on the fetch standard's blocked-port list. */
32
+ port?: number;
33
+ /**
34
+ * Where browsers and ionite reach this adapter. Default: `ADAPTER_BASE_URL`, else localhost. A path
35
+ * (`https://adapters.example/keycloak`) serves every route under it, for hosts that route by path.
36
+ */
37
+ publicBaseUrl?: string;
38
+ /** Default: the store `ADAPTER_VAULT_*` describes (see `credentialStoreFromEnv`). */
39
+ credentialStore?: CredentialStore<Connection>;
40
+ /** Default: `envConfig()`, the `ION_*` variables. */
41
+ configSource?: Parameters<typeof ionite>[0];
42
+ }
43
+
44
+ /**
45
+ * Runs an adapter as an SDK app. ionite creates a tenant here through Tenant Management, one per app
46
+ * record; the create answers `action_required`, the customer lands on `/onboard` already signed in
47
+ * and enters the vendor credentials, which go to the adapter's own credential store. ionite never
48
+ * receives them. Afterwards ionite calls `/api/adapter/{tenant}/...` with a workload token.
49
+ */
50
+ export async function serveAdapter<Connection>(
51
+ definition: AdapterDefinition<Connection>,
52
+ options: ServeAdapterOptions<Connection> = {},
53
+ ) {
54
+ const port = options.port ?? Number(process.env.PORT ?? 4195);
55
+ const base = new URL(options.publicBaseUrl ?? (process.env.ADAPTER_BASE_URL?.trim() || `http://localhost:${port}`));
56
+ if (base.search || base.hash) throw new Error('ADAPTER_BASE_URL takes no query or fragment');
57
+ // Path routing does not strip the prefix, so every route, cookie and minted URL carries it.
58
+ const prefix = base.pathname.replace(/\/+$/, '');
59
+ const baseUrl = `${base.origin}${prefix}`;
60
+ const onboardPath = `${prefix}/onboard`;
61
+ const credentials =
62
+ options.credentialStore ??
63
+ credentialStoreFromEnv<Connection>({
64
+ slug: definition.slug,
65
+ parse: (stored) => {
66
+ const parsed = definition.connection.schema.safeParse(stored);
67
+ return parsed.success ? parsed.data : undefined;
68
+ },
69
+ });
70
+ const validators = createValidators();
71
+ const stores = await storesFromEnv(definition.slug);
72
+ const tenantStore = stores.tenants;
73
+ // Sign-in links are minted here on ionite's workload-authenticated request (see `issueSignIn`).
74
+ const magicLinkStore = stores.magicLinks;
75
+
76
+ const onboardRedirectPolicy = { ...defaultRedirectPolicies, fallback: onboardPath };
77
+
78
+ const ion = ionite(options.configSource ?? envConfig(), {
79
+ validators,
80
+ log: prettyLogger,
81
+ basePath: `${prefix}/api/ionite`,
82
+ stores: stores.framework,
83
+ ciam: {
84
+ enableJitUserProvisioning: true,
85
+ // Adapters sharing a host must not see each other's sessions.
86
+ cookiesPath: prefix || '/',
87
+ beforeLogin: ({ request }) => captureRedirect(request, onboardRedirectPolicy),
88
+ afterLogin: (ctx) => {
89
+ if (!ctx.ok) return `${onboardPath}?error=login_failed`;
90
+ // Magic link: the redirect rides the login URL. OIDC: it rides the beforeLogin state cookie.
91
+ return (
92
+ captureRedirect(ctx.request, onboardRedirectPolicy)?.redirect ??
93
+ resolveCapturedRedirect(ctx, onboardRedirectPolicy)
94
+ );
95
+ },
96
+ },
97
+ tm: {
98
+ basePath: `${prefix}/api/tenants`,
99
+ store: tenantStore,
100
+ validators,
101
+ planCreate: () => ({ status: 'action_required', path: onboardPath, origin: base.origin }),
102
+ onTenantDeleted: async ({ tenantId }) => {
103
+ await credentials.purge(tenantId);
104
+ ion.log.info(`${definition.name} credentials purged`, { 'ion.operation': 'credentials.purge', tenantId });
105
+ },
106
+ },
107
+ });
108
+ if (!ion.tm) throw new Error('Tenant Management wiring failed');
109
+ const tm = ion.tm;
110
+
111
+ /** The signed-in root CIAM customer. The request token names the request; it never authorises it. */
112
+ async function signedInCustomer(
113
+ request: Request,
114
+ ): Promise<{ id: string; label: string } | 'unavailable' | undefined> {
115
+ if (!ion.ciam) return 'unavailable';
116
+ const resolution = await ion.ciam.resolveCustomer(request);
117
+ if (resolution.status === 'degraded') return 'unavailable';
118
+ if (resolution.status !== 'authenticated' || !resolution.value.id) return undefined;
119
+ return { id: resolution.value.id, label: resolution.value.email || resolution.value.id };
120
+ }
121
+
122
+ /**
123
+ * ionite vouches for a user it has already signed in and authorised, and gets back a single-use
124
+ * link that signs that user in here. The adapter trusts ionite for WHO the user is; it already
125
+ * trusts the same caller to drive the vendor.
126
+ */
127
+ async function issueSignIn(request: SignInRequest): Promise<SignInResponse> {
128
+ const email = request.email.trim();
129
+ const name = request.name?.trim() || email.split('@')[0] || email;
130
+ const token = `${crypto.randomUUID()}${crypto.randomUUID()}`.replace(/-/g, '');
131
+ const expiresAt = new Date(Date.now() + SIGN_IN_TTL_MS);
132
+ await magicLinkStore.create(token, { userName: email, name, email }, expiresAt);
133
+ const login = new URL(`${baseUrl}/api/ionite/magic-link/login`);
134
+ login.searchParams.set('token', token);
135
+ login.searchParams.set('redirect', request.redirect);
136
+ return { url: login.toString(), expiresAt: expiresAt.toISOString() };
137
+ }
138
+
139
+ async function onboard(request: Request): Promise<Response> {
140
+ const url = new URL(request.url);
141
+ const form = request.method === 'POST' ? await request.formData() : undefined;
142
+ const posted = form?.get('rt');
143
+ const requestToken = form ? (typeof posted === 'string' ? posted.trim() : '') : (url.searchParams.get('rt') ?? '');
144
+ if (!requestToken) return messagePage('Nothing to connect', 'Start the connection from ionite.', 400);
145
+
146
+ const customer = await signedInCustomer(request);
147
+ if (customer === 'unavailable') {
148
+ return messagePage('Sign-in unavailable', 'Customer sign-in is not available right now. Try again shortly.', 503);
149
+ }
150
+ if (!customer) return messagePage('Sign in from ionite', 'Open this page from ionite to sign in.', 401);
151
+
152
+ const pending = await tm.getActionRequest(requestToken);
153
+ if (!pending)
154
+ return messagePage('Link expired', 'This link is invalid or has expired. Start again from ionite.', 400);
155
+ const returnUrl = safeReturnUrl(pending.returnUrl);
156
+ const shown = {
157
+ requestToken,
158
+ action: onboardPath,
159
+ companyName: pending.companyName,
160
+ signedInAs: customer.label,
161
+ returnOrigin: returnUrl ? new URL(returnUrl).origin : undefined,
162
+ };
163
+ if (!form) return connectForm(definition, shown);
164
+
165
+ const read = readConnectionForm(definition, form);
166
+ if ('error' in read) return connectForm(definition, { ...shown, values: read.values, error: read.error });
167
+ try {
168
+ await definition.connection.verify(read.connection);
169
+ } catch (error) {
170
+ ion.log.warn(
171
+ `${definition.name} credential check failed`,
172
+ { 'ion.outcome': 'failure', tenantId: pending.id },
173
+ error,
174
+ );
175
+ return connectForm(definition, {
176
+ ...shown,
177
+ values: read.values,
178
+ error: verifyFailureMessage(definition.name, error),
179
+ });
180
+ }
181
+
182
+ // Stored before completion: a completed tenant with no credentials would fail every later call,
183
+ // while credentials for a tenant that loses the completion race are overwritten by the winner's
184
+ // retry or purged with the tenant.
185
+ await credentials.put(pending.id, read.connection);
186
+ const { tenant } = await tm.completeActionRequest({
187
+ requestToken,
188
+ tenant: {
189
+ ...pending,
190
+ status: 'completed',
191
+ tenantUrl: pending.tenantUrl ?? `${baseUrl}/t/${pending.id}`,
192
+ updatedAt: new Date(),
193
+ },
194
+ });
195
+ ion.log.info(`${definition.name} credentials stored`, {
196
+ 'ion.operation': 'credentials.store',
197
+ tenantId: tenant.id,
198
+ actor: customer.id,
199
+ store: credentials.kind,
200
+ });
201
+ // Straight back to ionite, which confirms the connection with this adapter before recording it.
202
+ return returnUrl ? Response.redirect(returnUrl, 303) : donePage(definition.name, tenant.companyName);
203
+ }
204
+
205
+ const noStore = { 'Cache-Control': 'no-store' };
206
+
207
+ /**
208
+ * A `workload.incoming` token that also holds `ion:tenant:manage`. The permission, not
209
+ * authentication alone, keeps other workloads this app trusts from driving a tenant's vendor.
210
+ */
211
+ async function authenticate(request: Request): Promise<string | Response> {
212
+ if (!ion.workload) {
213
+ return Response.json({ error: 'This app has no ionite trust configured yet' }, { status: 503, headers: noStore });
214
+ }
215
+ const caller = await getWorkload(request, ion);
216
+ if (!caller) {
217
+ return new Response(null, { status: 401, headers: { 'WWW-Authenticate': 'Bearer error="invalid_token"' } });
218
+ }
219
+ const access = await hasPermission(request, ion, TENANT_MANAGE, undefined, 'workload');
220
+ if (!access.allow) {
221
+ return Response.json({ error: `The caller is not granted ${TENANT_MANAGE}` }, { status: 403, headers: noStore });
222
+ }
223
+ return String(caller.clientId ?? caller.workloadId ?? caller.claims.sub ?? 'unknown');
224
+ }
225
+
226
+ const adapterApi = createAdapterApi({
227
+ definition,
228
+ authenticate,
229
+ tenants: {
230
+ get: (id) => tenantStore.get(id),
231
+ async saveVendorState(id, vendorState) {
232
+ const tenant = await tenantStore.get(id);
233
+ if (!tenant) throw new Error(`Tenant ${id} disappeared before its state was saved`);
234
+ await tenantStore.upsert({ ...tenant, vendorState, updatedAt: new Date() } as typeof tenant);
235
+ },
236
+ },
237
+ credentials,
238
+ issueSignIn,
239
+ log: ion.log,
240
+ basePath: prefix,
241
+ });
242
+
243
+ const route = async (request: Request): Promise<Response> => {
244
+ const { pathname } = new URL(request.url);
245
+ // Unprefixed too: kubelet probes reach the pod directly, not through the path-routing host.
246
+ if (pathname === '/healthz' || pathname === `${prefix}/healthz`) {
247
+ return Response.json({ ok: true, credentialStore: credentials.kind });
248
+ }
249
+ if (pathname === `${prefix}/api/tenants` || pathname.startsWith(`${prefix}/api/tenants/`))
250
+ return tm.handler(request);
251
+ if (pathname.startsWith(`${prefix}/api/ionite/`)) return ion.handler(request);
252
+ if (pathname === onboardPath && (request.method === 'GET' || request.method === 'POST')) return onboard(request);
253
+ return (await adapterApi(request)) ?? new Response('Not found', { status: 404 });
254
+ };
255
+
256
+ const server = Bun.serve({
257
+ port,
258
+ async fetch(request) {
259
+ try {
260
+ return await route(request);
261
+ } catch (error) {
262
+ // The message can quote the vendor's response; it goes to the log, not to the caller.
263
+ ion.log.error(
264
+ 'Request failed',
265
+ { 'ion.outcome': 'failure', 'http.method': request.method, 'url.path': new URL(request.url).pathname },
266
+ error,
267
+ );
268
+ return Response.json({ error: 'Request failed' }, { status: 500, headers: noStore });
269
+ }
270
+ },
271
+ });
272
+ // Listening comes BEFORE ready: over LFV the vault delivers this app's config by calling
273
+ // `/api/ionite/lfv/delivery` here, so waiting for config before serving never finishes.
274
+ await ion.ready();
275
+ ion.log.info(`${definition.name} adapter listening`, {
276
+ url: baseUrl,
277
+ 'tm.url': `${baseUrl}/api/tenants`,
278
+ credentialStore: credentials.kind,
279
+ });
280
+
281
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
282
+ process.on(signal, () => {
283
+ setTimeout(() => process.exit(1), 10_000).unref();
284
+ void server
285
+ .stop()
286
+ .then(() => ion.close())
287
+ .then(() => stores.close())
288
+ .then(() => process.exit(0));
289
+ });
290
+ }
291
+ return { ion, server };
292
+ }
package/src/stores.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { TenantStore } from '@ionite/core';
2
+ import {
3
+ createClient,
4
+ createRedisAdapter,
5
+ RedisCustomerStore,
6
+ RedisMagicLinkStore,
7
+ RedisSessionStore,
8
+ RedisTenantStore,
9
+ RedisUserStore,
10
+ RedisWorkloadTokenStore,
11
+ } from '@ionite/redis';
12
+ import type { FrameworkStores } from '@ionite/server';
13
+
14
+ type MagicLinkStore = NonNullable<FrameworkStores['magicLinkStore']>;
15
+
16
+ const REDIS_CONNECT_TIMEOUT_MS = 15_000;
17
+
18
+ export interface AdapterStores {
19
+ tenants: TenantStore;
20
+ /** The SDK's sessions, users, customers and workload tokens, with `magicLinkStore` below. */
21
+ framework: FrameworkStores;
22
+ /** `serveAdapter` mints sign-in links into it, so it is named on its own. */
23
+ magicLinks: MagicLinkStore;
24
+ close(): Promise<void>;
25
+ }
26
+
27
+ /**
28
+ * Every store lives in the Redis at `ADAPTER_REDIS_URL`, under `adapter:<slug>:`, in development as
29
+ * in a deployment: replicas share tenants, sessions and sign-in links, and a restart loses none of
30
+ * them. Adapters may share one Redis; the slug keeps their keys apart.
31
+ */
32
+ export async function storesFromEnv(
33
+ slug: string,
34
+ env: Record<string, string | undefined> = process.env,
35
+ ): Promise<AdapterStores> {
36
+ const redisUrl = env.ADAPTER_REDIS_URL?.trim();
37
+ if (!redisUrl) {
38
+ throw new Error('ADAPTER_REDIS_URL is not set. Locally, point it at any Redis, e.g. redis://localhost:6379.');
39
+ }
40
+ const client = createClient({ url: redisUrl });
41
+ // node-redis reconnects on its own; without a listener an 'error' event would crash the process.
42
+ client.on('error', (error: unknown) => console.error(`[${slug}] redis client error`, error));
43
+ // The first connect also retries forever, which would leave a pod hung before it serves `/healthz`;
44
+ // failing here makes an unreachable Redis a visible crash loop instead.
45
+ let timer: ReturnType<typeof setTimeout> | undefined;
46
+ try {
47
+ await Promise.race([
48
+ client.connect(),
49
+ new Promise<never>((_, reject) => {
50
+ timer = setTimeout(
51
+ () => reject(new Error(`Redis at ADAPTER_REDIS_URL did not connect within ${REDIS_CONNECT_TIMEOUT_MS}ms`)),
52
+ REDIS_CONNECT_TIMEOUT_MS,
53
+ );
54
+ }),
55
+ ]);
56
+ } catch (error) {
57
+ await client.disconnect().catch(() => {});
58
+ throw error;
59
+ } finally {
60
+ clearTimeout(timer);
61
+ }
62
+ const redis = createRedisAdapter(client);
63
+ const prefix = `adapter:${slug}:`;
64
+ const magicLinks = new RedisMagicLinkStore({ redis, keyPrefix: `${prefix}magic-links:` });
65
+ return {
66
+ tenants: new RedisTenantStore({ redis, keyPrefix: `${prefix}tenants:` }),
67
+ framework: {
68
+ sessionStore: new RedisSessionStore({ redis, keyPrefix: `${prefix}sessions:` }),
69
+ userStore: new RedisUserStore({ redis, keyPrefix: `${prefix}users:` }),
70
+ customerStore: new RedisCustomerStore({ redis, keyPrefix: `${prefix}customers:` }),
71
+ workloadTokenStore: new RedisWorkloadTokenStore({ redis, keyPrefix: `${prefix}workload-tokens:` }),
72
+ magicLinkStore: magicLinks,
73
+ },
74
+ magicLinks,
75
+ close: async () => {
76
+ await client.quit();
77
+ },
78
+ };
79
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { createAdapterApi } from './api';
2
+ import type { OperationInput, OperationName } from './contract';
3
+ import { MemoryCredentialStore } from './credentials';
4
+ import type { AdapterDefinition } from './define';
5
+
6
+ /**
7
+ * The connection as `serveAdapter` holds it: parsed once by the connect form, stored, then parsed
8
+ * again on every load. A schema whose output it rejects (a transform to a non-string, a `"" →
9
+ * undefined` on a required field) connects fine and then fails every call, so a test fails here.
10
+ */
11
+ function storedConnection<Connection>(definition: AdapterDefinition<Connection>, connection: Connection): Connection {
12
+ const connected = definition.connection.schema.safeParse(connection);
13
+ if (!connected.success) {
14
+ throw new Error(`The test connection does not pass ${definition.slug}'s connection schema`);
15
+ }
16
+ const reloaded = definition.connection.schema.safeParse(connected.data);
17
+ if (!reloaded.success) {
18
+ throw new Error(
19
+ `${definition.slug}'s connection schema rejects its own output, which the SDK re-parses on every load`,
20
+ );
21
+ }
22
+ return reloaded.data;
23
+ }
24
+
25
+ /**
26
+ * Drives an adapter definition over the same HTTP shapes ionite uses, with no ionite, no SDK config
27
+ * and no vault: the caller is always authorised and the tenant is already connected with
28
+ * `connection`. Stub `fetch` for the vendor, or point `connection` at a real instance.
29
+ */
30
+ export function createTestAdapter<Connection>(
31
+ definition: AdapterDefinition<Connection>,
32
+ options: {
33
+ connection: Connection;
34
+ tenantId?: string;
35
+ vendorState?: Record<string, unknown>;
36
+ /** The adapter's path prefix, as `serveAdapter` derives it from a base URL with a path. */
37
+ basePath?: string;
38
+ },
39
+ ) {
40
+ const tenantId = options.tenantId ?? 'test-tenant';
41
+ // One tenant's `TenantState`, kept across calls as the real tenant record would keep it.
42
+ let vendorState: Record<string, unknown> = { ...(options.vendorState ?? {}) };
43
+ const credentials = new MemoryCredentialStore<Connection>();
44
+ const ready = credentials.put(tenantId, storedConnection(definition, options.connection));
45
+ const logged: Array<{ level: string; message: string; attributes?: Record<string, unknown> }> = [];
46
+ const record = (level: string) => (message: string, attributes?: Record<string, unknown>) => {
47
+ logged.push({ level, message, attributes });
48
+ };
49
+ const api = createAdapterApi({
50
+ definition,
51
+ authenticate: async () => 'test-caller',
52
+ tenants: {
53
+ get: async (id) =>
54
+ id === tenantId
55
+ ? { id, status: 'completed', ioniteId: 'APP-TEST', companyId: 'TENANT-TEST', vendorState: { ...vendorState } }
56
+ : undefined,
57
+ async saveVendorState(_id, state) {
58
+ vendorState = state;
59
+ },
60
+ },
61
+ credentials,
62
+ issueSignIn: async (request) => ({
63
+ url: `http://adapter.test/sign-in?redirect=${encodeURIComponent(request.redirect)}`,
64
+ expiresAt: new Date(0).toISOString(),
65
+ }),
66
+ log: { info: record('info'), warn: record('warn'), error: record('error') },
67
+ basePath: options.basePath,
68
+ });
69
+
70
+ async function send(method: string, path: string, body?: unknown): Promise<{ status: number; body: unknown }> {
71
+ await ready;
72
+ const response = await api(
73
+ new Request(`http://adapter.test${options.basePath ?? ''}/api/adapter/${path}`, {
74
+ method,
75
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
76
+ body: body === undefined ? undefined : JSON.stringify(body),
77
+ }),
78
+ );
79
+ if (!response) throw new Error(`/api/adapter/${path} is not an adapter route`);
80
+ return { status: response.status, body: await response.json().catch(() => undefined) };
81
+ }
82
+
83
+ return {
84
+ /** Every log line the adapter wrote. Assert on it to prove a secret never reaches the log. */
85
+ logged,
86
+ /** What the adapter saved with `context.state`. */
87
+ vendorState: () => vendorState,
88
+ manifest: () => send('GET', 'manifest'),
89
+ connection: () => send('GET', `${tenantId}/connection`),
90
+ /** Typed to the contract. Use `send` to post a body the contract would not let you build. */
91
+ call: <Op extends OperationName>(operation: Op, input: OperationInput<Op>) =>
92
+ send('POST', `${tenantId}/${operation}`, input),
93
+ send,
94
+ };
95
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.