@jini-ai/capability-providers 0.1.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +174 -0
  3. package/dist/adapters/blob-storage/index.d.ts +67 -0
  4. package/dist/adapters/blob-storage/index.js +62 -0
  5. package/dist/adapters/jwt-auth/index.d.ts +53 -0
  6. package/dist/adapters/jwt-auth/index.js +182 -0
  7. package/dist/adapters/sqlite/index.d.ts +56 -0
  8. package/dist/adapters/sqlite/index.js +83 -0
  9. package/dist/adapters/stripe/index.d.ts +94 -0
  10. package/dist/adapters/stripe/index.js +167 -0
  11. package/dist/adapters/ws/index.d.ts +95 -0
  12. package/dist/adapters/ws/index.js +161 -0
  13. package/dist/auth.d.ts +22 -47
  14. package/dist/auth.js +10 -173
  15. package/dist/db.d.ts +11 -48
  16. package/dist/db.js +15 -79
  17. package/dist/index.d.ts +54 -1
  18. package/dist/index.js +54 -1
  19. package/dist/payments.d.ts +21 -74
  20. package/dist/payments.js +13 -175
  21. package/dist/realtime.d.ts +24 -73
  22. package/dist/realtime.js +14 -140
  23. package/dist/storage.d.ts +23 -49
  24. package/dist/storage.js +13 -57
  25. package/dist/tokens.js +6 -6
  26. package/dist/unsafe-reference/auth.d.ts +1 -1
  27. package/dist/unsafe-reference/auth.js +3 -3
  28. package/dist/unsafe-reference/db.d.ts +2 -2
  29. package/dist/unsafe-reference/index.d.ts +1 -1
  30. package/dist/unsafe-reference/index.js +1 -1
  31. package/dist/unsafe-reference/payments.d.ts +3 -1
  32. package/dist/unsafe-reference/payments.js +6 -5
  33. package/dist/unsafe-reference/realtime.d.ts +1 -1
  34. package/dist/unsafe-reference/realtime.js +4 -4
  35. package/dist/unsafe-reference/storage.d.ts +3 -1
  36. package/dist/unsafe-reference/storage.js +7 -6
  37. package/dist/visitor-auth/definitions.d.ts +32 -0
  38. package/dist/visitor-auth/definitions.js +57 -0
  39. package/dist/visitor-auth/index.d.ts +17 -0
  40. package/dist/visitor-auth/index.js +17 -0
  41. package/dist/visitor-auth/lifecycle.d.ts +101 -0
  42. package/dist/visitor-auth/lifecycle.js +326 -0
  43. package/dist/visitor-auth/ports.d.ts +134 -0
  44. package/dist/visitor-auth/ports.js +2 -0
  45. package/dist/visitor-auth/registry.d.ts +38 -0
  46. package/dist/visitor-auth/registry.js +78 -0
  47. package/dist/visitor-auth/tokens.d.ts +10 -0
  48. package/dist/visitor-auth/tokens.js +9 -0
  49. package/package.json +66 -9
  50. package/dist/auth.d.ts.map +0 -1
  51. package/dist/auth.js.map +0 -1
  52. package/dist/db.d.ts.map +0 -1
  53. package/dist/db.js.map +0 -1
  54. package/dist/index.d.ts.map +0 -1
  55. package/dist/index.js.map +0 -1
  56. package/dist/payments.d.ts.map +0 -1
  57. package/dist/payments.js.map +0 -1
  58. package/dist/realtime.d.ts.map +0 -1
  59. package/dist/realtime.js.map +0 -1
  60. package/dist/storage.d.ts.map +0 -1
  61. package/dist/storage.js.map +0 -1
  62. package/dist/tokens.d.ts.map +0 -1
  63. package/dist/tokens.js.map +0 -1
  64. package/dist/unsafe-reference/auth.d.ts.map +0 -1
  65. package/dist/unsafe-reference/auth.js.map +0 -1
  66. package/dist/unsafe-reference/db.d.ts.map +0 -1
  67. package/dist/unsafe-reference/db.js.map +0 -1
  68. package/dist/unsafe-reference/index.d.ts.map +0 -1
  69. package/dist/unsafe-reference/index.js.map +0 -1
  70. package/dist/unsafe-reference/payments.d.ts.map +0 -1
  71. package/dist/unsafe-reference/payments.js.map +0 -1
  72. package/dist/unsafe-reference/realtime.d.ts.map +0 -1
  73. package/dist/unsafe-reference/realtime.js.map +0 -1
  74. package/dist/unsafe-reference/storage.d.ts.map +0 -1
  75. package/dist/unsafe-reference/storage.js.map +0 -1
@@ -0,0 +1,326 @@
1
+ const DEFAULT_TRANSACTION_TTL_MS = 10 * 60 * 1000;
2
+ const MAX_TRANSACTION_TTL_MS = 15 * 60 * 1000;
3
+ const PKCE_VALUE = /^[A-Za-z0-9._~-]{43,128}$/;
4
+ const OPAQUE_SECURITY_VALUE = /^[A-Za-z0-9._~-]{32,512}$/;
5
+ const SAFE_PROVIDER_ERROR = /^[A-Za-z0-9._-]{1,64}$/;
6
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
7
+ const RESERVED_AUTHORIZATION_PARAMETERS = new Set([
8
+ 'client_id',
9
+ 'code_challenge',
10
+ 'code_challenge_method',
11
+ 'nonce',
12
+ 'redirect_uri',
13
+ 'response_type',
14
+ 'scope',
15
+ 'state',
16
+ ]);
17
+ export class VisitorAuthConfigurationError extends Error {
18
+ code;
19
+ constructor({ code, message }) {
20
+ super(message);
21
+ this.name = 'VisitorAuthConfigurationError';
22
+ this.code = code;
23
+ }
24
+ }
25
+ function parsedSecureUrl(value, label, allowLoopbackHttp) {
26
+ let url;
27
+ try {
28
+ url = new URL(value);
29
+ }
30
+ catch {
31
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: `${label} must be an absolute URL` });
32
+ }
33
+ const secure = isSecureProtocol(url, allowLoopbackHttp);
34
+ if (!secure || url.username || url.password || url.hash) {
35
+ throw new VisitorAuthConfigurationError({ code: 'insecure-url', message: `${label} must use HTTPS without credentials or a fragment` });
36
+ }
37
+ return url;
38
+ }
39
+ function isSecureProtocol(url, allowLoopbackHttp) {
40
+ if (url.protocol === 'https:')
41
+ return true;
42
+ return allowLoopbackHttp && url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);
43
+ }
44
+ function assertNonEmpty(value, label) {
45
+ if (!value.trim()) {
46
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: `${label} must not be empty` });
47
+ }
48
+ }
49
+ function assertProviderAlignment(required) {
50
+ if (required.provider.id !== required.server.providerId ||
51
+ required.provider.id !== required.registration.providerId) {
52
+ throw new VisitorAuthConfigurationError({ code: 'provider-mismatch', message: 'provider definition, authorization server, and client registration must match' });
53
+ }
54
+ }
55
+ function validatedTransactionTtl(ttlMs) {
56
+ const resolved = ttlMs ?? DEFAULT_TRANSACTION_TTL_MS;
57
+ if (!Number.isInteger(resolved) || resolved <= 0 || resolved > MAX_TRANSACTION_TTL_MS) {
58
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: `ttlMs must be an integer between 1 and ${MAX_TRANSACTION_TTL_MS}` });
59
+ }
60
+ return resolved;
61
+ }
62
+ function assertPlanContext(required) {
63
+ assertNonEmpty(required.registration.tenantId, 'tenantId');
64
+ assertNonEmpty(required.registration.clientId, 'clientId');
65
+ assertNonEmpty(required.flowBinding, 'flowBinding');
66
+ if (required.registration.clientSecretRef) {
67
+ assertNonEmpty(required.registration.clientSecretRef.id, 'clientSecretRef.id');
68
+ }
69
+ if (!Number.isFinite(required.nowMs)) {
70
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'nowMs must be finite' });
71
+ }
72
+ }
73
+ function validatedOidcNonce(protocol, security) {
74
+ if (!OPAQUE_SECURITY_VALUE.test(security.state)) {
75
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'state is malformed or too short' });
76
+ }
77
+ if (!PKCE_VALUE.test(security.codeVerifier) || !PKCE_VALUE.test(security.codeChallenge)) {
78
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'PKCE verifier and S256 challenge must be 43-128 URL-safe characters' });
79
+ }
80
+ if (protocol !== 'oidc')
81
+ return undefined;
82
+ const nonce = security.nonce;
83
+ if (!nonce || !OPAQUE_SECURITY_VALUE.test(nonce)) {
84
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'OIDC authorization requires a strong nonce' });
85
+ }
86
+ return nonce;
87
+ }
88
+ function assertAuthorizationServerSecurity(required) {
89
+ if (!required.server.supportsPkceS256) {
90
+ throw new VisitorAuthConfigurationError({ code: 'pkce-s256-required', message: 'visitor-auth requires authorization servers that support PKCE S256' });
91
+ }
92
+ if (required.provider.protocol === 'oidc' && !required.server.issuer) {
93
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'OIDC authorization server metadata must declare an issuer' });
94
+ }
95
+ if (required.server.requiresAuthorizationResponseIssuer && !required.server.issuer) {
96
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'authorization response issuer validation requires a configured issuer' });
97
+ }
98
+ }
99
+ function configuredAuthorizationUrl(required) {
100
+ const authorizationUrl = parsedSecureUrl(required.authorizationEndpoint, 'authorizationEndpoint', false);
101
+ for (const key of authorizationUrl.searchParams.keys()) {
102
+ if (RESERVED_AUTHORIZATION_PARAMETERS.has(key)) {
103
+ throw new VisitorAuthConfigurationError({ code: 'reserved-parameter', message: `authorizationEndpoint must not preconfigure reserved parameter "${key}"` });
104
+ }
105
+ }
106
+ for (const [key, value] of Object.entries(required.extraParameters ?? {})) {
107
+ if (RESERVED_AUTHORIZATION_PARAMETERS.has(key)) {
108
+ throw new VisitorAuthConfigurationError({ code: 'reserved-parameter', message: `extraParameters must not override reserved parameter "${key}"` });
109
+ }
110
+ authorizationUrl.searchParams.set(key, value);
111
+ }
112
+ authorizationUrl.searchParams.set('response_type', 'code');
113
+ authorizationUrl.searchParams.set('client_id', required.clientId);
114
+ authorizationUrl.searchParams.set('redirect_uri', required.redirectUri);
115
+ authorizationUrl.searchParams.set('scope', required.scopes.join(' '));
116
+ authorizationUrl.searchParams.set('state', required.security.state);
117
+ authorizationUrl.searchParams.set('code_challenge', required.security.codeChallenge);
118
+ authorizationUrl.searchParams.set('code_challenge_method', 'S256');
119
+ if (required.oidcNonce)
120
+ authorizationUrl.searchParams.set('nonce', required.oidcNonce);
121
+ return authorizationUrl.toString();
122
+ }
123
+ /**
124
+ * Produces a side-effect-free authorization plan. The host persists the
125
+ * returned transaction before redirecting and must later consume it through
126
+ * `VisitorAuthTransactionStorePort` exactly once.
127
+ *
128
+ * @param required - Trusted provider/server/registration metadata, browser binding, and fresh security artifacts.
129
+ * @param optional - Bounded transaction lifetime and non-reserved provider parameters.
130
+ * @returns A redirect URL and the sensitive transaction the host must seal before redirecting.
131
+ * @throws {VisitorAuthConfigurationError} When configuration or security material fails closed.
132
+ * @complexity Time and space: O(s + p), where s is scope count and p is extra parameters.
133
+ */
134
+ export function planVisitorAuthAuthorization(required, optional = {}) {
135
+ assertProviderAlignment(required);
136
+ assertPlanContext(required);
137
+ assertAuthorizationServerSecurity(required);
138
+ const ttlMs = validatedTransactionTtl(optional.ttlMs);
139
+ const oidcNonce = validatedOidcNonce(required.provider.protocol, required.security);
140
+ const tokenEndpoint = parsedSecureUrl(required.server.tokenEndpoint, 'tokenEndpoint', false);
141
+ const redirectUri = parsedSecureUrl(required.redirectUri, 'redirectUri', true).toString();
142
+ const authorizationUrl = configuredAuthorizationUrl({
143
+ authorizationEndpoint: required.server.authorizationEndpoint,
144
+ clientId: required.registration.clientId,
145
+ redirectUri,
146
+ scopes: required.provider.defaultScopes,
147
+ security: required.security,
148
+ ...(oidcNonce ? { oidcNonce } : {}),
149
+ ...(optional.extraParameters ? { extraParameters: optional.extraParameters } : {}),
150
+ });
151
+ return {
152
+ authorizationUrl,
153
+ transaction: Object.freeze({
154
+ tenantId: required.registration.tenantId,
155
+ providerId: required.provider.id,
156
+ flowBinding: required.flowBinding,
157
+ protocol: required.provider.protocol,
158
+ state: required.security.state,
159
+ ...(oidcNonce ? { nonce: oidcNonce } : {}),
160
+ codeVerifier: required.security.codeVerifier,
161
+ redirectUri,
162
+ clientId: required.registration.clientId,
163
+ ...(required.registration.clientSecretRef
164
+ ? { clientSecretRef: required.registration.clientSecretRef }
165
+ : {}),
166
+ tokenEndpoint: tokenEndpoint.toString(),
167
+ ...(required.server.issuer ? { expectedIssuer: required.server.issuer } : {}),
168
+ requiresAuthorizationResponseIssuer: required.server.requiresAuthorizationResponseIssuer ?? false,
169
+ createdAtMs: required.nowMs,
170
+ expiresAtMs: required.nowMs + ttlMs,
171
+ }),
172
+ };
173
+ }
174
+ function callbackContextRejection(required) {
175
+ if (required.transaction.tenantId !== required.tenantId)
176
+ return 'tenant-mismatch';
177
+ if (required.transaction.flowBinding !== required.flowBinding)
178
+ return 'flow-binding-mismatch';
179
+ if (!Number.isFinite(required.nowMs))
180
+ return 'expired';
181
+ if (required.nowMs >= required.transaction.expiresAtMs)
182
+ return 'expired';
183
+ return undefined;
184
+ }
185
+ function callbackProtocolRejection(required) {
186
+ if (!required.callback.state || required.callback.state !== required.transaction.state) {
187
+ return 'state-mismatch';
188
+ }
189
+ if (required.transaction.requiresAuthorizationResponseIssuer && !required.callback.issuer) {
190
+ return 'issuer-mismatch';
191
+ }
192
+ if (required.callback.issuer &&
193
+ required.callback.issuer !== required.transaction.expectedIssuer) {
194
+ return 'issuer-mismatch';
195
+ }
196
+ return undefined;
197
+ }
198
+ function safeProviderError(value) {
199
+ return SAFE_PROVIDER_ERROR.test(value) ? value : undefined;
200
+ }
201
+ /**
202
+ * Evaluates an already atomically consumed transaction. It produces a token
203
+ * exchange request only after every browser, tenant, expiry, state, and issuer
204
+ * binding succeeds; it performs no HTTP and creates no identity/session.
205
+ *
206
+ * @param required - Consumed transaction, parsed callback fields, current tenant/browser binding, and injected time.
207
+ * @returns A discriminated exchange or rejection decision; expected callback failures never throw.
208
+ * @complexity Time and space: O(1).
209
+ */
210
+ export function evaluateVisitorAuthCallback(required) {
211
+ const { transaction, callback } = required;
212
+ const rejection = callbackContextRejection(required) ?? callbackProtocolRejection({ transaction, callback });
213
+ if (rejection)
214
+ return { decision: 'reject', reason: rejection };
215
+ if (callback.error) {
216
+ const providerError = safeProviderError(callback.error);
217
+ return {
218
+ decision: 'reject',
219
+ reason: 'provider-error',
220
+ ...(providerError ? { providerError } : {}),
221
+ };
222
+ }
223
+ if (!callback.code) {
224
+ return { decision: 'reject', reason: 'missing-code' };
225
+ }
226
+ return {
227
+ decision: 'exchange',
228
+ request: {
229
+ tenantId: transaction.tenantId,
230
+ providerId: transaction.providerId,
231
+ clientId: transaction.clientId,
232
+ ...(transaction.clientSecretRef
233
+ ? { clientSecretRef: transaction.clientSecretRef }
234
+ : {}),
235
+ tokenEndpoint: transaction.tokenEndpoint,
236
+ authorizationCode: callback.code,
237
+ codeVerifier: transaction.codeVerifier,
238
+ redirectUri: transaction.redirectUri,
239
+ },
240
+ };
241
+ }
242
+ function validatedClockSkew(clockSkewSeconds) {
243
+ const skew = clockSkewSeconds ?? 60;
244
+ if (!Number.isFinite(skew) || skew < 0 || skew > 300) {
245
+ throw new VisitorAuthConfigurationError({ code: 'invalid-input', message: 'clockSkewSeconds must be between 0 and 300' });
246
+ }
247
+ return skew;
248
+ }
249
+ function validateClaimAudience(required) {
250
+ const audiences = typeof required.audience === 'string' ? [required.audience] : required.audience;
251
+ if (audiences.length === 0)
252
+ return 'malformed-claims';
253
+ if (audiences.some((audience) => !audience.trim()))
254
+ return 'malformed-claims';
255
+ if (!audiences.includes(required.clientId))
256
+ return 'audience-mismatch';
257
+ if (audiences.length > 1 && required.authorizedParty !== required.clientId) {
258
+ return 'authorized-party-mismatch';
259
+ }
260
+ return undefined;
261
+ }
262
+ function validateClaimTiming(required) {
263
+ if (!Number.isFinite(required.nowSeconds))
264
+ return 'malformed-claims';
265
+ if (!Number.isFinite(required.expiresAtSeconds))
266
+ return 'malformed-claims';
267
+ if (required.expiresAtSeconds <= required.nowSeconds - required.skewSeconds)
268
+ return 'expired';
269
+ return undefined;
270
+ }
271
+ function validateClaimIdentityBinding(required) {
272
+ if (!required.claims.subject.trim())
273
+ return 'subject-missing';
274
+ if (!required.transaction.expectedIssuer)
275
+ return 'issuer-mismatch';
276
+ if (required.claims.issuer !== required.transaction.expectedIssuer)
277
+ return 'issuer-mismatch';
278
+ if (!required.transaction.nonce)
279
+ return 'nonce-mismatch';
280
+ if (required.claims.nonce !== required.transaction.nonce)
281
+ return 'nonce-mismatch';
282
+ return undefined;
283
+ }
284
+ function acceptedIdentityDecision(required) {
285
+ return {
286
+ decision: 'accept',
287
+ identity: {
288
+ providerId: required.providerId,
289
+ subject: required.claims.subject,
290
+ ...(required.claims.email ? { email: required.claims.email } : {}),
291
+ ...(required.claims.emailVerified === undefined
292
+ ? {}
293
+ : { emailVerified: required.claims.emailVerified }),
294
+ },
295
+ };
296
+ }
297
+ /**
298
+ * Applies OIDC semantic checks to claims returned by
299
+ * `VisitorAuthIdTokenVerifierPort` after cryptographic verification.
300
+ *
301
+ * @param required - The consumed OIDC transaction, verified claims, and injected epoch time.
302
+ * @param optional - A bounded clock-skew allowance (default 60 seconds, maximum 300).
303
+ * @returns A provider-subject identity only after issuer, audience, expiry, and nonce checks pass.
304
+ * @throws {VisitorAuthConfigurationError} When the caller supplies an invalid skew policy.
305
+ * @complexity Time: O(a); space: O(a), where a is the number of audiences.
306
+ */
307
+ export function validateVisitorAuthIdentityClaims(required, optional = {}) {
308
+ const { transaction, claims } = required;
309
+ const skew = validatedClockSkew(optional.clockSkewSeconds);
310
+ const timingRejection = validateClaimTiming({
311
+ expiresAtSeconds: claims.expiresAtSeconds,
312
+ nowSeconds: required.nowSeconds,
313
+ skewSeconds: skew,
314
+ });
315
+ const identityRejection = validateClaimIdentityBinding({ transaction, claims });
316
+ const audienceRejection = validateClaimAudience({
317
+ audience: claims.audience,
318
+ authorizedParty: claims.authorizedParty,
319
+ clientId: transaction.clientId,
320
+ });
321
+ const rejection = timingRejection ?? identityRejection ?? audienceRejection;
322
+ if (rejection)
323
+ return { decision: 'reject', reason: rejection };
324
+ return acceptedIdentityDecision({ providerId: transaction.providerId, claims });
325
+ }
326
+ //# sourceMappingURL=lifecycle.js.map
@@ -0,0 +1,134 @@
1
+ import type { VisitorAuthProtocol, VisitorAuthProviderDefinition } from './definitions.js';
2
+ export interface VisitorAuthClientSecretRef {
3
+ /** Opaque host-owned handle. Never a plaintext secret. */
4
+ readonly id: string;
5
+ }
6
+ export interface VisitorAuthClientRegistration {
7
+ readonly tenantId: string;
8
+ readonly providerId: string;
9
+ readonly clientId: string;
10
+ readonly clientSecretRef?: VisitorAuthClientSecretRef;
11
+ }
12
+ /** Resolves public client metadata plus an opaque reference to sealed secret material. */
13
+ export interface VisitorAuthClientRegistrationPort {
14
+ resolve(required: {
15
+ readonly tenantId: string;
16
+ readonly providerId: string;
17
+ }): Promise<VisitorAuthClientRegistration | undefined>;
18
+ }
19
+ export interface VisitorAuthAuthorizationServer {
20
+ readonly providerId: string;
21
+ readonly authorizationEndpoint: string;
22
+ readonly tokenEndpoint: string;
23
+ readonly issuer?: string;
24
+ readonly supportsPkceS256: boolean;
25
+ /** RFC 9207 response issuer is required when the adapter advertises it. */
26
+ readonly requiresAuthorizationResponseIssuer?: boolean;
27
+ }
28
+ /** Resolves trusted, host-pinned server metadata; it is not user-supplied callback data. */
29
+ export interface VisitorAuthAuthorizationServerPort {
30
+ resolve(required: {
31
+ readonly provider: VisitorAuthProviderDefinition;
32
+ }): Promise<VisitorAuthAuthorizationServer>;
33
+ }
34
+ export interface VisitorAuthSecurityArtifacts {
35
+ readonly state: string;
36
+ readonly nonce?: string;
37
+ readonly codeVerifier: string;
38
+ readonly codeChallenge: string;
39
+ }
40
+ /** CSPRNG and SHA-256 seam. Implementations must generate fresh artifacts per attempt. */
41
+ export interface VisitorAuthSecurityPort {
42
+ createAuthorizationArtifacts(required: {
43
+ readonly protocol: VisitorAuthProtocol;
44
+ }): Promise<VisitorAuthSecurityArtifacts>;
45
+ }
46
+ export interface VisitorAuthTransaction {
47
+ readonly tenantId: string;
48
+ readonly providerId: string;
49
+ /** Host-minted binding to the initiating browser/session; carries no authority itself. */
50
+ readonly flowBinding: string;
51
+ readonly protocol: VisitorAuthProtocol;
52
+ readonly state: string;
53
+ readonly nonce?: string;
54
+ /** Sensitive PKCE material: stores must seal this value and never log it. */
55
+ readonly codeVerifier: string;
56
+ readonly redirectUri: string;
57
+ readonly clientId: string;
58
+ readonly clientSecretRef?: VisitorAuthClientSecretRef;
59
+ readonly tokenEndpoint: string;
60
+ readonly expectedIssuer?: string;
61
+ readonly requiresAuthorizationResponseIssuer: boolean;
62
+ readonly createdAtMs: number;
63
+ readonly expiresAtMs: number;
64
+ }
65
+ /**
66
+ * One-time transaction persistence. `consume` must atomically remove or mark
67
+ * the tenant-scoped state as consumed before returning it, including on a
68
+ * later callback rejection, so concurrent/replayed callbacks cannot reuse it.
69
+ */
70
+ export interface VisitorAuthTransactionStorePort {
71
+ save(required: {
72
+ readonly transaction: VisitorAuthTransaction;
73
+ }): Promise<void>;
74
+ consume(required: {
75
+ readonly tenantId: string;
76
+ readonly state: string;
77
+ }): Promise<VisitorAuthTransaction | undefined>;
78
+ }
79
+ export interface VisitorAuthTokenExchangeRequest {
80
+ readonly tenantId: string;
81
+ readonly providerId: string;
82
+ readonly clientId: string;
83
+ readonly clientSecretRef?: VisitorAuthClientSecretRef;
84
+ readonly tokenEndpoint: string;
85
+ readonly authorizationCode: string;
86
+ readonly codeVerifier: string;
87
+ readonly redirectUri: string;
88
+ }
89
+ export interface VisitorAuthTokenSet {
90
+ readonly accessToken: string;
91
+ readonly tokenType: string;
92
+ readonly expiresInSeconds?: number;
93
+ readonly refreshToken?: string;
94
+ readonly idToken?: string;
95
+ readonly grantedScopes?: readonly string[];
96
+ }
97
+ /** Provider adapter seam; core lifecycle logic never dereferences secret handles or performs HTTP. */
98
+ export interface VisitorAuthTokenExchangePort {
99
+ exchange(required: VisitorAuthTokenExchangeRequest): Promise<VisitorAuthTokenSet>;
100
+ refresh(required: {
101
+ readonly tenantId: string;
102
+ readonly providerId: string;
103
+ readonly clientId: string;
104
+ readonly clientSecretRef?: VisitorAuthClientSecretRef;
105
+ readonly refreshToken: string;
106
+ }): Promise<VisitorAuthTokenSet>;
107
+ revoke(required: {
108
+ readonly tenantId: string;
109
+ readonly providerId: string;
110
+ readonly token: string;
111
+ }): Promise<void>;
112
+ }
113
+ export interface VisitorAuthVerifiedIdTokenClaims {
114
+ readonly issuer: string;
115
+ readonly subject: string;
116
+ readonly audience: string | readonly string[];
117
+ readonly authorizedParty?: string;
118
+ readonly expiresAtSeconds: number;
119
+ readonly nonce?: string;
120
+ readonly email?: string;
121
+ readonly emailVerified?: boolean;
122
+ }
123
+ /**
124
+ * Cryptographic verification seam. It must verify signature, algorithm,
125
+ * trusted key provenance, and token shape before returning these claims.
126
+ */
127
+ export interface VisitorAuthIdTokenVerifierPort {
128
+ verify(required: {
129
+ readonly providerId: string;
130
+ readonly idToken: string;
131
+ readonly expectedIssuer: string;
132
+ }): Promise<VisitorAuthVerifiedIdTokenClaims>;
133
+ }
134
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,38 @@
1
+ import type { VisitorAuthProviderDefinition } from './definitions.js';
2
+ export type VisitorAuthRegistryErrorCode = 'invalid-provider' | 'duplicate-provider';
3
+ export declare class VisitorAuthRegistryError extends Error {
4
+ readonly code: VisitorAuthRegistryErrorCode;
5
+ constructor({ code, message }: {
6
+ code: VisitorAuthRegistryErrorCode;
7
+ message: string;
8
+ });
9
+ }
10
+ export interface VisitorAuthProviderRegistry {
11
+ register(required: {
12
+ definition: VisitorAuthProviderDefinition;
13
+ }): void;
14
+ get(required: {
15
+ providerId: string;
16
+ }): VisitorAuthProviderDefinition | undefined;
17
+ has(required: {
18
+ providerId: string;
19
+ }): boolean;
20
+ list(): readonly VisitorAuthProviderDefinition[];
21
+ }
22
+ /**
23
+ * Creates an independent, append-only provider-definition registry.
24
+ *
25
+ * The registry stores defensive immutable copies. It intentionally carries no
26
+ * OAuth handlers or credentials: a host cannot obtain executable authority by
27
+ * enumerating provider metadata.
28
+ *
29
+ * @param required - Optional provider definitions to validate and register in order.
30
+ * @returns A fresh registry with no shared mutable state.
31
+ * @throws {VisitorAuthRegistryError} When a definition is malformed or duplicates an id.
32
+ * @complexity Time: O(p * (f + s)); space: O(p * (f + s)), where p is providers,
33
+ * f is credential fields, and s is scopes.
34
+ */
35
+ export declare function createVisitorAuthProviderRegistry(_required: Record<string, never>, optional?: {
36
+ readonly seed?: readonly VisitorAuthProviderDefinition[];
37
+ }): VisitorAuthProviderRegistry;
38
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1,78 @@
1
+ export class VisitorAuthRegistryError extends Error {
2
+ code;
3
+ constructor({ code, message }) {
4
+ super(message);
5
+ this.name = 'VisitorAuthRegistryError';
6
+ this.code = code;
7
+ }
8
+ }
9
+ function validatedCopy(definition) {
10
+ const id = definition.id.trim();
11
+ const label = definition.label.trim();
12
+ if (!id || !label || !/^[a-z0-9][a-z0-9._-]*$/.test(id)) {
13
+ throw new VisitorAuthRegistryError({ code: 'invalid-provider', message: 'visitor-auth provider id and label must be non-empty, and id must be URL-safe' });
14
+ }
15
+ if (definition.credentialSchema.length === 0) {
16
+ throw new VisitorAuthRegistryError({ code: 'invalid-provider', message: `visitor-auth provider "${id}" must declare at least one credential field` });
17
+ }
18
+ const credentialKeys = new Set();
19
+ const credentialSchema = definition.credentialSchema.map((field) => {
20
+ const key = field.key.trim();
21
+ const fieldLabel = field.label.trim();
22
+ if (!key || !fieldLabel || credentialKeys.has(key)) {
23
+ throw new VisitorAuthRegistryError({ code: 'invalid-provider', message: `visitor-auth provider "${id}" has an invalid or duplicate credential field` });
24
+ }
25
+ credentialKeys.add(key);
26
+ return Object.freeze({ ...field, key, label: fieldLabel });
27
+ });
28
+ const scopes = definition.defaultScopes.map((scope) => scope.trim());
29
+ if (scopes.some((scope) => !scope) || new Set(scopes).size !== scopes.length) {
30
+ throw new VisitorAuthRegistryError({ code: 'invalid-provider', message: `visitor-auth provider "${id}" has an invalid or duplicate default scope` });
31
+ }
32
+ return Object.freeze({
33
+ ...definition,
34
+ id,
35
+ label,
36
+ credentialSchema: Object.freeze(credentialSchema),
37
+ defaultScopes: Object.freeze(scopes),
38
+ });
39
+ }
40
+ /**
41
+ * Creates an independent, append-only provider-definition registry.
42
+ *
43
+ * The registry stores defensive immutable copies. It intentionally carries no
44
+ * OAuth handlers or credentials: a host cannot obtain executable authority by
45
+ * enumerating provider metadata.
46
+ *
47
+ * @param required - Optional provider definitions to validate and register in order.
48
+ * @returns A fresh registry with no shared mutable state.
49
+ * @throws {VisitorAuthRegistryError} When a definition is malformed or duplicates an id.
50
+ * @complexity Time: O(p * (f + s)); space: O(p * (f + s)), where p is providers,
51
+ * f is credential fields, and s is scopes.
52
+ */
53
+ export function createVisitorAuthProviderRegistry(_required, optional = {}) {
54
+ const providers = new Map();
55
+ const registry = {
56
+ register({ definition }) {
57
+ const copy = validatedCopy(definition);
58
+ if (providers.has(copy.id)) {
59
+ throw new VisitorAuthRegistryError({ code: 'duplicate-provider', message: `visitor-auth provider "${copy.id}" is already registered` });
60
+ }
61
+ providers.set(copy.id, copy);
62
+ },
63
+ get({ providerId }) {
64
+ return providers.get(providerId);
65
+ },
66
+ has({ providerId }) {
67
+ return providers.has(providerId);
68
+ },
69
+ list() {
70
+ return Object.freeze(Array.from(providers.values()));
71
+ },
72
+ };
73
+ for (const definition of optional.seed ?? []) {
74
+ registry.register({ definition });
75
+ }
76
+ return registry;
77
+ }
78
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1,10 @@
1
+ import type { VisitorAuthAuthorizationServerPort, VisitorAuthClientRegistrationPort, VisitorAuthIdTokenVerifierPort, VisitorAuthSecurityPort, VisitorAuthTokenExchangePort, VisitorAuthTransactionStorePort } from './ports.js';
2
+ import type { VisitorAuthProviderRegistry } from './registry.js';
3
+ export declare const VisitorAuthProviderRegistryToken: import("@jini-ai/core").Token<VisitorAuthProviderRegistry, string>;
4
+ export declare const VisitorAuthClientRegistrationToken: import("@jini-ai/core").Token<VisitorAuthClientRegistrationPort, string>;
5
+ export declare const VisitorAuthAuthorizationServerToken: import("@jini-ai/core").Token<VisitorAuthAuthorizationServerPort, string>;
6
+ export declare const VisitorAuthSecurityToken: import("@jini-ai/core").Token<VisitorAuthSecurityPort, string>;
7
+ export declare const VisitorAuthTransactionStoreToken: import("@jini-ai/core").Token<VisitorAuthTransactionStorePort, string>;
8
+ export declare const VisitorAuthTokenExchangeToken: import("@jini-ai/core").Token<VisitorAuthTokenExchangePort, string>;
9
+ export declare const VisitorAuthIdTokenVerifierToken: import("@jini-ai/core").Token<VisitorAuthIdTokenVerifierPort, string>;
10
+ //# sourceMappingURL=tokens.d.ts.map
@@ -0,0 +1,9 @@
1
+ import { token } from '@jini-ai/core';
2
+ export const VisitorAuthProviderRegistryToken = token({ id: 'jini.capabilityProviders.visitorAuth.providerRegistry' });
3
+ export const VisitorAuthClientRegistrationToken = token({ id: 'jini.capabilityProviders.visitorAuth.clientRegistration' });
4
+ export const VisitorAuthAuthorizationServerToken = token({ id: 'jini.capabilityProviders.visitorAuth.authorizationServer' });
5
+ export const VisitorAuthSecurityToken = token({ id: 'jini.capabilityProviders.visitorAuth.security' });
6
+ export const VisitorAuthTransactionStoreToken = token({ id: 'jini.capabilityProviders.visitorAuth.transactionStore' });
7
+ export const VisitorAuthTokenExchangeToken = token({ id: 'jini.capabilityProviders.visitorAuth.tokenExchange' });
8
+ export const VisitorAuthIdTokenVerifierToken = token({ id: 'jini.capabilityProviders.visitorAuth.idTokenVerifier' });
9
+ //# sourceMappingURL=tokens.js.map