@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/LICENSE +18 -0
- package/package.json +40 -4
- package/src/api.ts +335 -0
- package/src/contract/ciam.ts +65 -0
- package/src/contract/iam.ts +36 -0
- package/src/contract/index.ts +11 -0
- package/src/contract/operations.ts +206 -0
- package/src/contract/otel.ts +21 -0
- package/src/contract/scim.ts +51 -0
- package/src/contract/sso.ts +323 -0
- package/src/contract/workload.ts +144 -0
- package/src/credentials.ts +114 -0
- package/src/define.ts +235 -0
- package/src/index.ts +27 -0
- package/src/onboard-page.ts +135 -0
- package/src/serve.ts +292 -0
- package/src/stores.ts +79 -0
- package/src/testing.ts +95 -0
- package/README.md +0 -3
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
const text = z.string().min(1);
|
|
4
|
+
|
|
5
|
+
export const registerWorkloadPayloadSchema = z.object({
|
|
6
|
+
name: text,
|
|
7
|
+
baseUrl: z.string(),
|
|
8
|
+
scopes: z.array(z.string()).optional(),
|
|
9
|
+
});
|
|
10
|
+
export type RegisterWorkloadPayload = z.infer<typeof registerWorkloadPayloadSchema>;
|
|
11
|
+
|
|
12
|
+
export const registerWorkloadResultSchema = z.object({
|
|
13
|
+
registered: z.literal(true),
|
|
14
|
+
clientId: text,
|
|
15
|
+
clientSecret: text,
|
|
16
|
+
downstreamId: z.string().optional(),
|
|
17
|
+
downstreamUrl: z.string().optional(),
|
|
18
|
+
tokenUrl: text,
|
|
19
|
+
issuer: text,
|
|
20
|
+
jwksUri: text,
|
|
21
|
+
scope: z.string().optional(),
|
|
22
|
+
/**
|
|
23
|
+
* ISO-8601 timestamp at which the minted `clientSecret` (or equivalent credential) expires, when
|
|
24
|
+
* the provider mints a finite-lifetime secret. Persisted to `standard_config.secretExpiresAt` so
|
|
25
|
+
* the integration can be proactively renewed. Omit for non-expiring secrets.
|
|
26
|
+
*/
|
|
27
|
+
secretExpiresAt: z.string().optional(),
|
|
28
|
+
});
|
|
29
|
+
export type RegisterWorkloadResult = z.infer<typeof registerWorkloadResultSchema>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The wire form. ionite's in-process payload also carries the caller app's vault contents; those are
|
|
33
|
+
* never sent to an adapter, so a provider that needs them (AWS STS) cannot be remote on this contract.
|
|
34
|
+
*/
|
|
35
|
+
export const registerOutgoingPayloadSchema = z.object({
|
|
36
|
+
callerName: text,
|
|
37
|
+
callerBaseUrl: z.string(),
|
|
38
|
+
keyName: text,
|
|
39
|
+
targetApp: z.object({ id: z.string(), name: z.string(), slug: z.string() }),
|
|
40
|
+
});
|
|
41
|
+
export type RegisterOutgoingPayload = z.infer<typeof registerOutgoingPayloadSchema>;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Describes which token claim a federated consumer should pin its trust to, and the value that claim
|
|
45
|
+
* carries for the minted client. The `claim` name is the AWS OIDC *condition-key* name (`aud` or
|
|
46
|
+
* `sub`), NOT necessarily the raw JWT claim — AWS maps a fixed, small set of keys for web-identity
|
|
47
|
+
* federation:
|
|
48
|
+
* - `aud` <- `azp` if the token sets `azp`, else the raw `aud` claim
|
|
49
|
+
* - `sub` <- `sub`
|
|
50
|
+
* (See AWS "Available keys for AWS OIDC federation".)
|
|
51
|
+
*
|
|
52
|
+
* Each IdP's token shape differs, so the federating workload adapter is the only thing that knows the
|
|
53
|
+
* right claim/value pair; it declares it here rather than having the AWS STS role builder hardcode an
|
|
54
|
+
* IdP-specific guess.
|
|
55
|
+
* - Okta default-AS client_credentials token: clientId lands in `sub` (`aud` = `api://default`), so
|
|
56
|
+
* `{ claim: "sub", value: clientId }`.
|
|
57
|
+
* - Keycloak (with our `aud` mapper): `{ claim: "aud", value: clientId }`.
|
|
58
|
+
* - Entra v2.0 client_credentials token: `azp` = caller clientId and AWS maps `:aud` <- `azp`, so
|
|
59
|
+
* `{ claim: "aud", value: clientId }` (the raw `aud` is the resource API, e.g. Graph — unusable as
|
|
60
|
+
* an identity discriminator).
|
|
61
|
+
*/
|
|
62
|
+
export const trustClaimSchema = z.object({ claim: z.enum(['aud', 'sub']), value: z.string() });
|
|
63
|
+
export type TrustClaim = z.infer<typeof trustClaimSchema>;
|
|
64
|
+
|
|
65
|
+
export const registerOutgoingResultSchema = z.object({
|
|
66
|
+
registered: z.literal(true),
|
|
67
|
+
/** Echo of the request's key name. ionite ignores it: the adapter does not choose where the entry lands. */
|
|
68
|
+
keyName: z.string().optional(),
|
|
69
|
+
clientId: text,
|
|
70
|
+
clientSecret: text,
|
|
71
|
+
idpTokenUrl: text,
|
|
72
|
+
issuer: text,
|
|
73
|
+
jwksUri: text,
|
|
74
|
+
/** Omitted: ionite records an empty scope. */
|
|
75
|
+
scope: z.string().optional(),
|
|
76
|
+
downstreamId: text,
|
|
77
|
+
/**
|
|
78
|
+
* Optional federated-trust pin. Consumed by federated targets (AWS STS) to build their IAM role
|
|
79
|
+
* trust condition. Absent => the consumer falls back to the legacy `:aud == clientId` behavior.
|
|
80
|
+
*/
|
|
81
|
+
trustClaim: trustClaimSchema.optional(),
|
|
82
|
+
/**
|
|
83
|
+
* Optional effective `:aud` value to register in a federated consumer's OIDC provider
|
|
84
|
+
* `ClientIDList` (AWS `AddClientIDToOpenIDConnectProvider`). This is the audience AWS will actually
|
|
85
|
+
* check (`azp` if the token emits it, else the raw `aud` claim) — IdP-specific and NOT always the
|
|
86
|
+
* clientId:
|
|
87
|
+
* - Keycloak: token `aud` = clientId, so this equals `clientId` (or absent).
|
|
88
|
+
* - Okta default-AS: token `aud` is the static `api://default`, not the clientId, so the value to
|
|
89
|
+
* register is `api://default`.
|
|
90
|
+
* - Entra v2.0: AWS maps `:aud` <- `azp` = caller appId, so this is the appId.
|
|
91
|
+
* Absent => the consumer falls back to `clientId` (Keycloak back-compat).
|
|
92
|
+
*/
|
|
93
|
+
oidcAudience: z.string().optional(),
|
|
94
|
+
/**
|
|
95
|
+
* ISO-8601 timestamp at which the minted `clientSecret` expires, when the provider mints a
|
|
96
|
+
* finite-lifetime secret. Persisted to `standard_config.secretExpiresAt`. Omit for non-expiring secrets.
|
|
97
|
+
*/
|
|
98
|
+
secretExpiresAt: z.string().optional(),
|
|
99
|
+
});
|
|
100
|
+
export type RegisterOutgoingResult = z.infer<typeof registerOutgoingResultSchema>;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A client_credentials credential an upstream provider minted for the consuming vendor. The adapter
|
|
104
|
+
* stores it in the vendor (an n8n credential, a CI secret) so the vendor's own jobs can call out with
|
|
105
|
+
* it. It carries a secret: the adapter writes it to the vendor and keeps no copy.
|
|
106
|
+
*/
|
|
107
|
+
export const consumeWorkloadRegisterPayloadSchema = z.object({
|
|
108
|
+
credential: z.object({
|
|
109
|
+
clientId: text,
|
|
110
|
+
clientSecret: text,
|
|
111
|
+
tokenUrl: text,
|
|
112
|
+
issuer: text,
|
|
113
|
+
scope: z.string().optional(),
|
|
114
|
+
}),
|
|
115
|
+
});
|
|
116
|
+
export type ConsumeWorkloadRegisterPayload = z.infer<typeof consumeWorkloadRegisterPayloadSchema>;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A federated target (AWS STS) trusts tokens another provider mints, and mints nothing itself. ionite
|
|
120
|
+
* mints the caller's client on the IdP the target's `wellKnownUrl` names, then asks the target to
|
|
121
|
+
* trust exactly that client: the issuer, the claim to pin and the audience. No secret is sent.
|
|
122
|
+
*/
|
|
123
|
+
export const federateWorkloadPayloadSchema = z.object({
|
|
124
|
+
callerName: text,
|
|
125
|
+
targetName: text,
|
|
126
|
+
federated: z.object({
|
|
127
|
+
issuer: text,
|
|
128
|
+
trustClaim: trustClaimSchema,
|
|
129
|
+
/** The `:aud` AWS will check, registered on its OIDC provider. */
|
|
130
|
+
oidcAudience: text,
|
|
131
|
+
}),
|
|
132
|
+
});
|
|
133
|
+
export type FederateWorkloadPayload = z.infer<typeof federateWorkloadPayloadSchema>;
|
|
134
|
+
|
|
135
|
+
export const federateWorkloadResultSchema = z.object({
|
|
136
|
+
/** Handle for `workload/deregister`. */
|
|
137
|
+
downstreamId: text,
|
|
138
|
+
/**
|
|
139
|
+
* What the caller needs besides the token, e.g. `{ arn }` of the role to assume. ionite publishes it
|
|
140
|
+
* as a secret under its own key name: the adapter does not choose where it lands.
|
|
141
|
+
*/
|
|
142
|
+
secret: z.record(z.string(), z.string().max(2048)).refine((value) => Object.keys(value).length <= 10),
|
|
143
|
+
});
|
|
144
|
+
export type FederateWorkloadResult = z.infer<typeof federateWorkloadResultSchema>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where vendor admin credentials live. TWO RULES, both load-bearing:
|
|
5
|
+
*
|
|
6
|
+
* 1. ionite holds no client on this store. The adapter's SDK vault (`ion.secret`) does not qualify:
|
|
7
|
+
* the ionite instance that hosts the adapter holds a write client for the whole mount it sits in.
|
|
8
|
+
* 2. Access to this store comes from the deployment (an injected token file), never from the
|
|
9
|
+
* adapter's ionite-delivered config, which the same ionite instance can read.
|
|
10
|
+
*
|
|
11
|
+
* Nothing here returns a credential to a browser or to ionite: the only reader is the code that
|
|
12
|
+
* calls the vendor.
|
|
13
|
+
*/
|
|
14
|
+
export interface CredentialStore<Connection> {
|
|
15
|
+
readonly kind: string;
|
|
16
|
+
put(tenantId: string, connection: Connection): Promise<void>;
|
|
17
|
+
get(tenantId: string): Promise<Connection | undefined>;
|
|
18
|
+
/** Removes every stored version. Called when ionite deletes the tenant; ionite cannot do this itself. */
|
|
19
|
+
purge(tenantId: string): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Local development and tests only: a restart loses every connection. */
|
|
23
|
+
export class MemoryCredentialStore<Connection> implements CredentialStore<Connection> {
|
|
24
|
+
readonly kind = 'memory';
|
|
25
|
+
private readonly entries = new Map<string, Connection>();
|
|
26
|
+
|
|
27
|
+
async put(tenantId: string, connection: Connection): Promise<void> {
|
|
28
|
+
this.entries.set(tenantId, connection);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async get(tenantId: string): Promise<Connection | undefined> {
|
|
32
|
+
return this.entries.get(tenantId);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async purge(tenantId: string): Promise<void> {
|
|
36
|
+
this.entries.delete(tenantId);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** KV version 2 on OpenBao or Vault. */
|
|
41
|
+
class KvCredentialStore<Connection> implements CredentialStore<Connection> {
|
|
42
|
+
readonly kind = 'kv-v2';
|
|
43
|
+
|
|
44
|
+
constructor(
|
|
45
|
+
private readonly address: string,
|
|
46
|
+
private readonly mount: string,
|
|
47
|
+
private readonly prefix: string,
|
|
48
|
+
private readonly token: () => string,
|
|
49
|
+
private readonly parse: (stored: unknown) => Connection | undefined,
|
|
50
|
+
) {}
|
|
51
|
+
|
|
52
|
+
private url(kind: 'data' | 'metadata', tenantId: string): string {
|
|
53
|
+
return `${this.address}/v1/${this.mount}/${kind}/${this.prefix}/${encodeURIComponent(tenantId)}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private headers(): Record<string, string> {
|
|
57
|
+
return { 'X-Vault-Token': this.token(), 'Content-Type': 'application/json' };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async put(tenantId: string, connection: Connection): Promise<void> {
|
|
61
|
+
const resp = await fetch(this.url('data', tenantId), {
|
|
62
|
+
method: 'POST',
|
|
63
|
+
headers: this.headers(),
|
|
64
|
+
body: JSON.stringify({ data: connection }),
|
|
65
|
+
});
|
|
66
|
+
if (!resp.ok) throw new Error(`Credential store write failed: ${resp.status}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async get(tenantId: string): Promise<Connection | undefined> {
|
|
70
|
+
const resp = await fetch(this.url('data', tenantId), { headers: this.headers() });
|
|
71
|
+
if (resp.status === 404) return undefined;
|
|
72
|
+
if (!resp.ok) throw new Error(`Credential store read failed: ${resp.status}`);
|
|
73
|
+
const body = (await resp.json()) as { data?: { data?: unknown } };
|
|
74
|
+
return this.parse(body.data?.data);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async purge(tenantId: string): Promise<void> {
|
|
78
|
+
// The metadata path deletes all versions; a delete on the data path only soft-deletes the latest.
|
|
79
|
+
const resp = await fetch(this.url('metadata', tenantId), { method: 'DELETE', headers: this.headers() });
|
|
80
|
+
if (!resp.ok && resp.status !== 404) throw new Error(`Credential store purge failed: ${resp.status}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The store the deployment configured. `parse` re-checks what a KV read returns and answers
|
|
86
|
+
* `undefined` for an entry that no longer has the connection's shape.
|
|
87
|
+
*/
|
|
88
|
+
export function credentialStoreFromEnv<Connection>(
|
|
89
|
+
options: { slug: string; parse: (stored: unknown) => Connection | undefined },
|
|
90
|
+
env: Record<string, string | undefined> = process.env,
|
|
91
|
+
): CredentialStore<Connection> {
|
|
92
|
+
const address = env.ADAPTER_VAULT_ADDR?.trim().replace(/\/+$/, '');
|
|
93
|
+
if (!address) {
|
|
94
|
+
if (env.ADAPTER_DEV_MEMORY_VAULT === '1') return new MemoryCredentialStore<Connection>();
|
|
95
|
+
throw new Error(
|
|
96
|
+
'No credential store configured. Set ADAPTER_VAULT_ADDR with ADAPTER_VAULT_TOKEN_FILE, ' +
|
|
97
|
+
'or ADAPTER_DEV_MEMORY_VAULT=1 for local development.',
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
const tokenFile = env.ADAPTER_VAULT_TOKEN_FILE?.trim();
|
|
101
|
+
const staticToken = env.ADAPTER_VAULT_TOKEN?.trim();
|
|
102
|
+
if (!tokenFile && !staticToken) {
|
|
103
|
+
throw new Error('ADAPTER_VAULT_ADDR is set but neither ADAPTER_VAULT_TOKEN_FILE nor ADAPTER_VAULT_TOKEN is.');
|
|
104
|
+
}
|
|
105
|
+
// Read per call: an injector rewrites the file when it renews the token.
|
|
106
|
+
const token = tokenFile ? () => readFileSync(tokenFile, 'utf8').trim() : () => staticToken ?? '';
|
|
107
|
+
return new KvCredentialStore<Connection>(
|
|
108
|
+
address,
|
|
109
|
+
env.ADAPTER_VAULT_MOUNT?.trim() || 'secret',
|
|
110
|
+
env.ADAPTER_VAULT_PREFIX?.trim().replace(/^\/+|\/+$/g, '') || `${options.slug}-adapter/tenants`,
|
|
111
|
+
token,
|
|
112
|
+
options.parse,
|
|
113
|
+
);
|
|
114
|
+
}
|
package/src/define.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import type {
|
|
3
|
+
ConsumeIamRegisterPayload,
|
|
4
|
+
ConsumeIamRegisterResult,
|
|
5
|
+
ConsumeSsoPrepareRequest,
|
|
6
|
+
ConsumeSsoPrepareResult,
|
|
7
|
+
ConsumeSsoRegisterPayload,
|
|
8
|
+
ConsumeSsoRegisterSamlPayload,
|
|
9
|
+
ConsumeWorkloadRegisterPayload,
|
|
10
|
+
DiscoveredSSOApp,
|
|
11
|
+
FederateWorkloadPayload,
|
|
12
|
+
FederateWorkloadResult,
|
|
13
|
+
ManualSetup,
|
|
14
|
+
RegisterCiamAppPayload,
|
|
15
|
+
RegisterCiamAppResult,
|
|
16
|
+
RegisterOtelPayload,
|
|
17
|
+
RegisterOtelResult,
|
|
18
|
+
RegisterOutgoingPayload,
|
|
19
|
+
RegisterOutgoingResult,
|
|
20
|
+
RegisterScimTargetPayload,
|
|
21
|
+
RegisterScimTargetResult,
|
|
22
|
+
RegisterSSOAppPayload,
|
|
23
|
+
RegisterSSOAppResult,
|
|
24
|
+
RegisterWorkloadPayload,
|
|
25
|
+
RegisterWorkloadResult,
|
|
26
|
+
RetireDiscoveredResult,
|
|
27
|
+
SSODiscoveryResult,
|
|
28
|
+
SSOProtocol,
|
|
29
|
+
UpdateCiamAppPayload,
|
|
30
|
+
UpdateSSOAppPayload,
|
|
31
|
+
} from './contract';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A request the vendor code refuses because of what was sent, not because the vendor failed. The
|
|
35
|
+
* message goes back to ionite (or onto the connection form) verbatim, so it must not quote a secret.
|
|
36
|
+
* Any other thrown error is logged and answered with a bare 500.
|
|
37
|
+
*/
|
|
38
|
+
export class AdapterInputError extends Error {
|
|
39
|
+
constructor(message: string) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = 'AdapterInputError';
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* By name, not `instanceof`: an adapter can hold its own copy of this package (a `bun install` after
|
|
47
|
+
* the package changed copied it into every adapter), while code shared between adapters
|
|
48
|
+
* (`~/code/adapters/shared`) throws the root copy's class. Measured 2026-11-17: that was a bare 500.
|
|
49
|
+
*/
|
|
50
|
+
export function isAdapterInputError(error: unknown): error is AdapterInputError {
|
|
51
|
+
return error instanceof Error && error.name === 'AdapterInputError';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What every vendor call is made for. `tenantId` is the adapter tenant: one per ionite app record. */
|
|
55
|
+
export interface AdapterCallContext {
|
|
56
|
+
tenantId: string;
|
|
57
|
+
state: TenantState;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What the vendor code must remember about its own objects for this tenant, when the vendor gives
|
|
62
|
+
* them no field to mark them with (Supabase SSO providers have no name or label). Kept on the
|
|
63
|
+
* adapter's tenant record, so NEVER a secret: credentials belong in the credential store. Values must
|
|
64
|
+
* survive `JSON.stringify`.
|
|
65
|
+
*/
|
|
66
|
+
export interface TenantState {
|
|
67
|
+
get<T = unknown>(key: string): T | undefined;
|
|
68
|
+
/** `undefined` removes the key. Saved before it resolves. */
|
|
69
|
+
set(key: string, value: unknown): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface SsoProvider {
|
|
73
|
+
register(payload: RegisterSSOAppPayload): Promise<RegisterSSOAppResult>;
|
|
74
|
+
update(downstreamId: string, payload: UpdateSSOAppPayload): Promise<void>;
|
|
75
|
+
deregister(downstreamId: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Registers the App at an IAM tool that provisions users into it (Entra). `register` leaves
|
|
80
|
+
* provisioning stopped: the tool's connection test calls back into the App, which only trusts the
|
|
81
|
+
* tool's client once ionite has written the App's config. ionite calls `activate` after that.
|
|
82
|
+
*/
|
|
83
|
+
export interface ScimProvider {
|
|
84
|
+
register(payload: RegisterScimTargetPayload): Promise<RegisterScimTargetResult>;
|
|
85
|
+
activate?(downstreamId: string): Promise<void>;
|
|
86
|
+
deregister(downstreamId: string): Promise<void>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A customer sign-in client for the App. */
|
|
90
|
+
export interface CiamProvider {
|
|
91
|
+
register(payload: RegisterCiamAppPayload): Promise<RegisterCiamAppResult>;
|
|
92
|
+
update(downstreamId: string, payload: UpdateCiamAppPayload): Promise<void>;
|
|
93
|
+
deregister(downstreamId: string): Promise<void>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface SsoDiscoveryProvider {
|
|
97
|
+
/**
|
|
98
|
+
* MUST NOT write to the vendor, and MUST report a per-namespace failure as that namespace's `error`
|
|
99
|
+
* rather than throwing: one forbidden realm must not discard the realms that did read.
|
|
100
|
+
*/
|
|
101
|
+
discover(): Promise<SSODiscoveryResult>;
|
|
102
|
+
/** `undefined` means the vendor does not hold it. A transport or authorization failure throws. */
|
|
103
|
+
discoverOne(externalId: string, namespace?: string): Promise<DiscoveredSSOApp | undefined>;
|
|
104
|
+
retireDiscovered(
|
|
105
|
+
target: { externalId: string; namespace: string },
|
|
106
|
+
action: 'disable' | 'enable',
|
|
107
|
+
): Promise<RetireDiscoveredResult>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface WorkloadProvider {
|
|
111
|
+
register(payload: RegisterWorkloadPayload): Promise<RegisterWorkloadResult>;
|
|
112
|
+
registerOutgoing(payload: RegisterOutgoingPayload): Promise<RegisterOutgoingResult>;
|
|
113
|
+
deregister(downstreamId: string): Promise<void>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A target that trusts another provider's tokens (AWS STS). ionite never asks it to mint: it calls
|
|
118
|
+
* `federate` with the client it minted elsewhere, and `deregister` with the handle `federate` returned.
|
|
119
|
+
* Its `wellKnownUrl` fact is the trusted IdP's document.
|
|
120
|
+
*/
|
|
121
|
+
export interface FederatedWorkloadTarget {
|
|
122
|
+
federate(payload: FederateWorkloadPayload): Promise<FederateWorkloadResult>;
|
|
123
|
+
deregister(downstreamId: string): Promise<void>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface OtelProvider {
|
|
127
|
+
register(payload: RegisterOtelPayload): Promise<RegisterOtelResult>;
|
|
128
|
+
/** An already-deleted credential is success: ionite retries deregister after a partial failure. */
|
|
129
|
+
deregister(downstreamId: string): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface SsoConsumer {
|
|
133
|
+
/** What the upstream IdP must register for this vendor. Called before the upstream registration. */
|
|
134
|
+
prepare(request: ConsumeSsoPrepareRequest): Promise<ConsumeSsoPrepareResult>;
|
|
135
|
+
/**
|
|
136
|
+
* An OIDC upstream. Omit for a vendor that only takes SAML; ionite then gets a 400 if it sends OIDC.
|
|
137
|
+
* Return `manualSetup` when the vendor's API cannot take the upstream and a person must finish.
|
|
138
|
+
*/
|
|
139
|
+
// biome-ignore lint/suspicious/noConfusingVoidType: a consumer with nothing to hand back just returns
|
|
140
|
+
register?(payload: ConsumeSsoRegisterPayload): Promise<void | { manualSetup?: ManualSetup }>;
|
|
141
|
+
/** A SAML upstream, sent when `prepare` returned `protocol: "saml"`. */
|
|
142
|
+
// biome-ignore lint/suspicious/noConfusingVoidType: as for `register`
|
|
143
|
+
registerSaml?(payload: ConsumeSsoRegisterSamlPayload): Promise<void | { manualSetup?: ManualSetup }>;
|
|
144
|
+
/**
|
|
145
|
+
* Removes everything `register` created for this tenant. ionite sends no alias, so the vendor code
|
|
146
|
+
* must be able to find its own objects again (mark them with `tenantId`). Returns how many it removed.
|
|
147
|
+
*/
|
|
148
|
+
deregister(): Promise<number>;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface IamConsumer {
|
|
152
|
+
register(payload: ConsumeIamRegisterPayload): Promise<ConsumeIamRegisterResult>;
|
|
153
|
+
deregister(downstreamId: string): Promise<void>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A vendor that calls out with a credential an upstream provider minted for it. `register` stores
|
|
158
|
+
* it in the vendor, replacing what this tenant stored before; `deregister` removes it and returns how
|
|
159
|
+
* many objects it removed. ionite sends no handle, so mark what you create (tenant state, a name).
|
|
160
|
+
*/
|
|
161
|
+
export interface WorkloadConsumer {
|
|
162
|
+
register(payload: ConsumeWorkloadRegisterPayload): Promise<void>;
|
|
163
|
+
deregister(): Promise<number>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** What `connection.facts` returns. May be async: an account id can need a vendor call. */
|
|
167
|
+
export interface ConnectionFactsOf {
|
|
168
|
+
url: string;
|
|
169
|
+
wellKnownUrl?: string;
|
|
170
|
+
workloadWellKnownUrl?: string;
|
|
171
|
+
ssoOrigins?: string[];
|
|
172
|
+
account?: { id: string; region?: string };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
type Factory<Connection, Service> = (connection: Connection, context: AdapterCallContext) => Service;
|
|
176
|
+
|
|
177
|
+
export interface ConnectionField {
|
|
178
|
+
/** Key in the object handed to `connection.schema`. */
|
|
179
|
+
name: string;
|
|
180
|
+
label: string;
|
|
181
|
+
/** `password` values are never trimmed and never rendered back, including after a failed attempt. */
|
|
182
|
+
type: 'text' | 'url' | 'password';
|
|
183
|
+
placeholder?: string;
|
|
184
|
+
/** Left empty, the schema receives "" for it. */
|
|
185
|
+
optional?: boolean;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface AdapterDefinition<Connection> {
|
|
189
|
+
/** The catalog slug of the product, e.g. "keycloak". Also names the credential store's default path. */
|
|
190
|
+
slug: string;
|
|
191
|
+
/** Shown to the customer, e.g. "Keycloak". */
|
|
192
|
+
name: string;
|
|
193
|
+
connection: {
|
|
194
|
+
/** The onboarding form. A field is required unless marked `optional`. */
|
|
195
|
+
fields: readonly ConnectionField[];
|
|
196
|
+
/**
|
|
197
|
+
* Turns the submitted fields into what gets stored, and re-checks what the store returns. The
|
|
198
|
+
* first issue's message is shown on the form, so write messages for the customer.
|
|
199
|
+
*/
|
|
200
|
+
// zod 4's third parameter is its internals type; passing it would stop `Connection` inferring.
|
|
201
|
+
// biome-ignore lint/suspicious/noExplicitAny: the schema's input type is the raw form record
|
|
202
|
+
schema: z.ZodType<Connection, any>;
|
|
203
|
+
/** Proves the details work against the vendor. Throw to reject them; nothing is stored until this passes. */
|
|
204
|
+
verify(connection: Connection): Promise<void>;
|
|
205
|
+
/**
|
|
206
|
+
* Public facts ionite records for the connection. Never a credential. `url` is the vendor instance:
|
|
207
|
+
* a URL a consumer asks an upstream IdP to register must be on its origin. `wellKnownUrl` is
|
|
208
|
+
* required when the adapter provides SSO or Workload, whose results ionite checks against it; for a
|
|
209
|
+
* federated workload target it is the document of the IdP whose tokens the vendor trusts.
|
|
210
|
+
* `workloadWellKnownUrl` replaces it for Workload when workload tokens come from another server.
|
|
211
|
+
* `ssoOrigins` widens the consumer check for a vendor whose SSO endpoints are hosted elsewhere.
|
|
212
|
+
* `account` names the cloud account for a vendor whose resource names carry it (AWS).
|
|
213
|
+
*/
|
|
214
|
+
facts(connection: Connection): ConnectionFactsOf | Promise<ConnectionFactsOf>;
|
|
215
|
+
};
|
|
216
|
+
provides?: {
|
|
217
|
+
sso?: { capabilities: SSOProtocol[]; defaultScope: string; connect: Factory<Connection, SsoProvider> };
|
|
218
|
+
ssoDiscovery?: Factory<Connection, SsoDiscoveryProvider>;
|
|
219
|
+
workload?: Factory<Connection, WorkloadProvider>;
|
|
220
|
+
federatedWorkload?: Factory<Connection, FederatedWorkloadTarget>;
|
|
221
|
+
otel?: Factory<Connection, OtelProvider>;
|
|
222
|
+
scim?: Factory<Connection, ScimProvider>;
|
|
223
|
+
ciam?: { defaultScope: string; connect: Factory<Connection, CiamProvider> };
|
|
224
|
+
};
|
|
225
|
+
consumes?: {
|
|
226
|
+
sso?: Factory<Connection, SsoConsumer>;
|
|
227
|
+
iam?: Factory<Connection, IamConsumer>;
|
|
228
|
+
workload?: Factory<Connection, WorkloadConsumer>;
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Identity function that fixes `Connection` from the schema, so the factories are typed against it. */
|
|
233
|
+
export function defineAdapter<Connection>(definition: AdapterDefinition<Connection>): AdapterDefinition<Connection> {
|
|
234
|
+
return definition;
|
|
235
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** The adapter runtime (`docs/adapter-sdk.md`). The wire contract alone is `@ionite/adapters/contract`. */
|
|
2
|
+
|
|
3
|
+
/** The SDK's own zod, so a connection schema is built with the instance that parses it. */
|
|
4
|
+
export { z } from 'zod';
|
|
5
|
+
export { type AdapterApiOptions, type AdapterLog, type AdapterTenant, adapterManifest, createAdapterApi } from './api';
|
|
6
|
+
export * from './contract';
|
|
7
|
+
export { type CredentialStore, credentialStoreFromEnv, MemoryCredentialStore } from './credentials';
|
|
8
|
+
export {
|
|
9
|
+
type AdapterCallContext,
|
|
10
|
+
type AdapterDefinition,
|
|
11
|
+
AdapterInputError,
|
|
12
|
+
type CiamProvider,
|
|
13
|
+
type ConnectionField,
|
|
14
|
+
defineAdapter,
|
|
15
|
+
type FederatedWorkloadTarget,
|
|
16
|
+
type IamConsumer,
|
|
17
|
+
isAdapterInputError,
|
|
18
|
+
type OtelProvider,
|
|
19
|
+
type ScimProvider,
|
|
20
|
+
type SsoConsumer,
|
|
21
|
+
type SsoDiscoveryProvider,
|
|
22
|
+
type SsoProvider,
|
|
23
|
+
type TenantState,
|
|
24
|
+
type WorkloadConsumer,
|
|
25
|
+
type WorkloadProvider,
|
|
26
|
+
} from './define';
|
|
27
|
+
export { type ServeAdapterOptions, serveAdapter } from './serve';
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { AdapterDefinition } from './define';
|
|
2
|
+
import { isAdapterInputError } from './define';
|
|
3
|
+
|
|
4
|
+
/* The onboarding page: plain server-rendered HTML, one form, no script. */
|
|
5
|
+
|
|
6
|
+
function escapeHtml(value: string): string {
|
|
7
|
+
return value
|
|
8
|
+
.replace(/&/g, '&')
|
|
9
|
+
.replace(/</g, '<')
|
|
10
|
+
.replace(/>/g, '>')
|
|
11
|
+
.replace(/"/g, '"')
|
|
12
|
+
.replace(/'/g, ''');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* `formRedirectOrigin`: browsers apply `form-action` to the redirect that follows a form post, so a
|
|
17
|
+
* page whose form ends by sending the customer back to ionite must name that origin.
|
|
18
|
+
*/
|
|
19
|
+
function page(title: string, body: string, status = 200, formRedirectOrigin?: string): Response {
|
|
20
|
+
const html = `<!doctype html>
|
|
21
|
+
<html lang="en">
|
|
22
|
+
<head>
|
|
23
|
+
<meta charset="utf-8">
|
|
24
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
25
|
+
<title>${escapeHtml(title)}</title>
|
|
26
|
+
<style>
|
|
27
|
+
body { font: 16px/1.5 system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; color: #1a1a1a; }
|
|
28
|
+
h1 { font-size: 1.4rem; }
|
|
29
|
+
label { display: block; margin-top: 1rem; font-weight: 600; }
|
|
30
|
+
input { width: 100%; padding: 0.5rem; margin-top: 0.25rem; box-sizing: border-box; font: inherit; }
|
|
31
|
+
button, a.button { display: inline-block; margin-top: 1.5rem; padding: 0.6rem 1.2rem; font: inherit;
|
|
32
|
+
background: #1a1a1a; color: #fff; border: 0; border-radius: 4px; text-decoration: none; cursor: pointer; }
|
|
33
|
+
.error { margin-top: 1rem; padding: 0.75rem; background: #fdecea; color: #8a1c13; border-radius: 4px; }
|
|
34
|
+
.muted { color: #666; }
|
|
35
|
+
</style>
|
|
36
|
+
</head>
|
|
37
|
+
<body>
|
|
38
|
+
${body}
|
|
39
|
+
</body>
|
|
40
|
+
</html>`;
|
|
41
|
+
return new Response(html, {
|
|
42
|
+
status,
|
|
43
|
+
headers: {
|
|
44
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
45
|
+
'Cache-Control': 'no-store',
|
|
46
|
+
'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; form-action 'self'${
|
|
47
|
+
formRedirectOrigin ? ` ${formRedirectOrigin}` : ''
|
|
48
|
+
}`,
|
|
49
|
+
'Referrer-Policy': 'no-referrer',
|
|
50
|
+
'X-Frame-Options': 'DENY',
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function messagePage(title: string, message: string, status = 200): Response {
|
|
56
|
+
return page(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`, status);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function connectForm<Connection>(
|
|
60
|
+
definition: AdapterDefinition<Connection>,
|
|
61
|
+
input: {
|
|
62
|
+
requestToken: string;
|
|
63
|
+
/** Where the form posts: `/onboard` under the adapter's path prefix. */
|
|
64
|
+
action: string;
|
|
65
|
+
companyName: string;
|
|
66
|
+
signedInAs: string;
|
|
67
|
+
/** What the customer typed, re-rendered after a failed attempt. Password fields are skipped. */
|
|
68
|
+
values?: Record<string, string>;
|
|
69
|
+
error?: string;
|
|
70
|
+
/** Origin of the tenant's `returnUrl`, from `new URL().origin`. */
|
|
71
|
+
returnOrigin?: string;
|
|
72
|
+
},
|
|
73
|
+
): Response {
|
|
74
|
+
const fields = definition.connection.fields
|
|
75
|
+
.map((field) => {
|
|
76
|
+
const name = escapeHtml(field.name);
|
|
77
|
+
const placeholder = field.placeholder ? ` placeholder="${escapeHtml(field.placeholder)}"` : '';
|
|
78
|
+
// A password is never echoed back, including after a failed attempt.
|
|
79
|
+
const value = field.type === 'password' ? '' : ` value="${escapeHtml(input.values?.[field.name] ?? '')}"`;
|
|
80
|
+
return ` <label for="${name}">${escapeHtml(field.label)}</label>
|
|
81
|
+
<input id="${name}" name="${name}" type="${field.type}"${field.optional ? '' : ' required'}${placeholder}${value}>`;
|
|
82
|
+
})
|
|
83
|
+
.join('\n');
|
|
84
|
+
return page(
|
|
85
|
+
`Connect ${definition.name}`,
|
|
86
|
+
`<h1>Connect ${escapeHtml(definition.name)} for ${escapeHtml(input.companyName)}</h1>
|
|
87
|
+
<p class="muted">Signed in as ${escapeHtml(input.signedInAs)}. These credentials are stored by this adapter
|
|
88
|
+
and are not shared with ionite. They cannot be viewed afterwards, only replaced.</p>
|
|
89
|
+
${input.error ? `<p class="error">${escapeHtml(input.error)}</p>` : ''}
|
|
90
|
+
<form method="post" action="${escapeHtml(input.action)}" autocomplete="off">
|
|
91
|
+
<input type="hidden" name="rt" value="${escapeHtml(input.requestToken)}">
|
|
92
|
+
${fields}
|
|
93
|
+
<button type="submit">Connect</button>
|
|
94
|
+
</form>`,
|
|
95
|
+
input.error ? 400 : 200,
|
|
96
|
+
input.returnOrigin,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function donePage(productName: string, companyName: string): Response {
|
|
101
|
+
return page(
|
|
102
|
+
`${productName} connected`,
|
|
103
|
+
`<h1>${escapeHtml(productName)} connected</h1><p>${escapeHtml(companyName)} is connected. You can close this page.</p>`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The submitted form as the connection the definition's schema accepts, or the message to show.
|
|
109
|
+
* `values` is what may be rendered back: everything except password fields.
|
|
110
|
+
*/
|
|
111
|
+
export function readConnectionForm<Connection>(
|
|
112
|
+
definition: AdapterDefinition<Connection>,
|
|
113
|
+
form: FormData,
|
|
114
|
+
): { values: Record<string, string> } & ({ connection: Connection } | { error: string }) {
|
|
115
|
+
const submitted: Record<string, string> = {};
|
|
116
|
+
const values: Record<string, string> = {};
|
|
117
|
+
for (const field of definition.connection.fields) {
|
|
118
|
+
const raw = form.get(field.name);
|
|
119
|
+
const value = typeof raw === 'string' ? raw : '';
|
|
120
|
+
// Not trimmed: a password may begin or end with a space.
|
|
121
|
+
submitted[field.name] = field.type === 'password' ? value : value.trim();
|
|
122
|
+
if (field.type !== 'password') values[field.name] = submitted[field.name];
|
|
123
|
+
}
|
|
124
|
+
const missing = definition.connection.fields.find((field) => !field.optional && !submitted[field.name]);
|
|
125
|
+
if (missing) return { values, error: `Enter the ${missing.label.toLowerCase()}.` };
|
|
126
|
+
const parsed = definition.connection.schema.safeParse(submitted);
|
|
127
|
+
if (!parsed.success) return { values, error: parsed.error.issues[0]?.message ?? 'Check the details and try again.' };
|
|
128
|
+
return { values, connection: parsed.data };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The message for a connection the vendor refused. The vendor's own error goes to the log, not the page. */
|
|
132
|
+
export function verifyFailureMessage(productName: string, error: unknown): string {
|
|
133
|
+
if (isAdapterInputError(error)) return error.message;
|
|
134
|
+
return `${productName} rejected these details. Check them and try again.`;
|
|
135
|
+
}
|