@astrasyncai/verification-gateway 2.4.2 → 2.4.4
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 +25 -0
- package/dist/adapter-interface/interface.d.mts +2 -2
- package/dist/adapter-interface/interface.d.ts +2 -2
- package/dist/adapters/express.d.mts +2 -2
- package/dist/adapters/express.d.ts +2 -2
- package/dist/adapters/express.js +31 -7
- package/dist/adapters/express.js.map +1 -1
- package/dist/adapters/express.mjs +31 -7
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/mcp.d.mts +25 -2
- package/dist/adapters/mcp.d.ts +25 -2
- package/dist/adapters/mcp.js +31 -7
- package/dist/adapters/mcp.js.map +1 -1
- package/dist/adapters/mcp.mjs +31 -7
- package/dist/adapters/mcp.mjs.map +1 -1
- package/dist/adapters/nextjs.d.mts +2 -2
- package/dist/adapters/nextjs.d.ts +2 -2
- package/dist/adapters/nextjs.js +1 -0
- package/dist/adapters/nextjs.js.map +1 -1
- package/dist/adapters/nextjs.mjs +1 -0
- package/dist/adapters/nextjs.mjs.map +1 -1
- package/dist/adapters/sdk.d.mts +2 -2
- package/dist/adapters/sdk.d.ts +2 -2
- package/dist/adapters/sdk.js +1 -0
- package/dist/adapters/sdk.js.map +1 -1
- package/dist/adapters/sdk.mjs +1 -0
- package/dist/adapters/sdk.mjs.map +1 -1
- package/dist/agent/index.d.mts +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/bin/astrasync.js +10 -2
- package/dist/browser/background.js +1 -0
- package/dist/browser/background.js.map +1 -1
- package/dist/browser/background.mjs +1 -0
- package/dist/browser/background.mjs.map +1 -1
- package/dist/browser/browser-adapter.d.mts +2 -2
- package/dist/browser/browser-adapter.d.ts +2 -2
- package/dist/cli/index.d.mts +2 -2
- package/dist/cli/index.d.ts +2 -2
- package/dist/cursor/cursor-adapter.d.mts +2 -2
- package/dist/cursor/cursor-adapter.d.ts +2 -2
- package/dist/cursor/extension.d.mts +2 -2
- package/dist/cursor/extension.d.ts +2 -2
- package/dist/cursor/extension.js +1 -0
- package/dist/cursor/extension.js.map +1 -1
- package/dist/cursor/extension.mjs +1 -0
- package/dist/cursor/extension.mjs.map +1 -1
- package/dist/{express-DneHiMhu.d.mts → express-Ck2RHZLT.d.mts} +1 -1
- package/dist/{express-DsiaQRFt.d.ts → express-DZmEzCgo.d.ts} +1 -1
- package/dist/gateway/gateway.d.mts +2 -2
- package/dist/gateway/gateway.d.ts +2 -2
- package/dist/gateway/gateway.js +1 -0
- package/dist/gateway/gateway.js.map +1 -1
- package/dist/gateway/gateway.mjs +1 -0
- package/dist/gateway/gateway.mjs.map +1 -1
- package/dist/git-trigger/git-hooks.d.mts +2 -2
- package/dist/git-trigger/git-hooks.d.ts +2 -2
- package/dist/{index-NZiKvrtE.d.ts → index-6Jus6yWU.d.ts} +1 -1
- package/dist/{index-DAGm-Sgf.d.mts → index-BZZTOfrI.d.mts} +1 -1
- package/dist/{index-Dd4alF0l.d.ts → index-BgKghi19.d.ts} +1 -1
- package/dist/{index-C9yWlQ2Y.d.mts → index-D698fDOk.d.mts} +1 -1
- package/dist/index.d.mts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +31 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +31 -7
- package/dist/index.mjs.map +1 -1
- package/dist/local-evaluator/evaluator.d.mts +2 -2
- package/dist/local-evaluator/evaluator.d.ts +2 -2
- package/dist/{nextjs-vUuVCaBP.d.mts → nextjs-93PHcE-i.d.mts} +1 -1
- package/dist/{nextjs-B4WmoiVm.d.ts → nextjs-t_ix2zQZ.d.ts} +1 -1
- package/dist/registration/index.d.mts +37 -0
- package/dist/registration/index.d.ts +37 -0
- package/dist/registration/index.js +10 -2
- package/dist/registration/index.js.map +1 -1
- package/dist/registration/index.mjs +10 -2
- package/dist/registration/index.mjs.map +1 -1
- package/dist/{sdk-Cixo6pTV.d.mts → sdk-BFwzjYjl.d.mts} +1 -1
- package/dist/{sdk-BvWp4q2q.d.ts → sdk-Chq02d82.d.ts} +1 -1
- package/dist/transport/index.d.mts +2 -2
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-IUzu-A4u.d.ts → types-CLP_TDu5.d.ts} +1 -1
- package/dist/{types-DLai3jly.d.mts → types-CVT-sorC.d.mts} +23 -0
- package/dist/{types-DLai3jly.d.ts → types-CVT-sorC.d.ts} +23 -0
- package/dist/{types-C_e1IZdU.d.mts → types-y13mmzbA.d.mts} +1 -1
- package/dist/ui/index.d.mts +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LocalPolicy, P as PDLSSContext, V as VerificationDecision, a as LocalPurposeRule } from '../types-
|
|
2
|
-
import '../types-
|
|
1
|
+
import { L as LocalPolicy, P as PDLSSContext, V as VerificationDecision, a as LocalPurposeRule } from '../types-y13mmzbA.mjs';
|
|
2
|
+
import '../types-CVT-sorC.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Local PDLSS Evaluator
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LocalPolicy, P as PDLSSContext, V as VerificationDecision, a as LocalPurposeRule } from '../types-
|
|
2
|
-
import '../types-
|
|
1
|
+
import { L as LocalPolicy, P as PDLSSContext, V as VerificationDecision, a as LocalPurposeRule } from '../types-CLP_TDu5.js';
|
|
2
|
+
import '../types-CVT-sorC.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Local PDLSS Evaluator
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as next_server from 'next/server';
|
|
2
2
|
import { NextRequest } from 'next/server';
|
|
3
|
-
import { N as NextJsMiddlewareOptions } from './types-
|
|
3
|
+
import { N as NextJsMiddlewareOptions } from './types-CVT-sorC.mjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Create Next.js middleware for agent verification.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as next_server from 'next/server';
|
|
2
2
|
import { NextRequest } from 'next/server';
|
|
3
|
-
import { N as NextJsMiddlewareOptions } from './types-
|
|
3
|
+
import { N as NextJsMiddlewareOptions } from './types-CVT-sorC.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Create Next.js middleware for agent verification.
|
|
@@ -156,19 +156,41 @@ interface WaitForApprovalOptions {
|
|
|
156
156
|
type RegisterResult = {
|
|
157
157
|
status: 'active';
|
|
158
158
|
agent: AgentRecord;
|
|
159
|
+
/** Round-12 (F16): backend advisories surfaced verbatim. */
|
|
160
|
+
warnings?: Array<{
|
|
161
|
+
code: string;
|
|
162
|
+
message: string;
|
|
163
|
+
}>;
|
|
159
164
|
} | {
|
|
160
165
|
status: 'pending_approval';
|
|
161
166
|
requestId: string;
|
|
162
167
|
expiresAt: string;
|
|
163
168
|
pollUrl: string;
|
|
164
169
|
message?: string;
|
|
170
|
+
/** Round-12 (F16): backend advisories surfaced verbatim. */
|
|
171
|
+
warnings?: Array<{
|
|
172
|
+
code: string;
|
|
173
|
+
message: string;
|
|
174
|
+
}>;
|
|
165
175
|
};
|
|
166
176
|
/**
|
|
167
177
|
* Response shape from `pollRegistration(requestId)` and the internal poll
|
|
168
178
|
* loop. State `pending` means still awaiting owner; the others are terminal.
|
|
179
|
+
*
|
|
180
|
+
* Round-11 (F3): on `state: 'approved'`, the response also carries the
|
|
181
|
+
* canonical `astraId` — the partner-facing public agent identity that all
|
|
182
|
+
* verify-access / verify/{id} surfaces accept. The `agent` (UUID) field
|
|
183
|
+
* stays owner-private and is kept for backward compat.
|
|
169
184
|
*/
|
|
170
185
|
interface PollRegistrationResult {
|
|
171
186
|
state: 'pending' | 'approved' | 'denied' | 'expired';
|
|
187
|
+
/**
|
|
188
|
+
* Canonical `ASTRA-…` id. Populated when `state === 'approved'`; `null`
|
|
189
|
+
* (or absent) otherwise. This is the identifier to pass to public
|
|
190
|
+
* verification surfaces — UUIDs from the register response are owner-
|
|
191
|
+
* private request handles and are rejected by verify-access in v2.4.3+.
|
|
192
|
+
*/
|
|
193
|
+
astraId?: string | null;
|
|
172
194
|
agent?: AgentRecord;
|
|
173
195
|
reason?: string;
|
|
174
196
|
}
|
|
@@ -182,6 +204,16 @@ interface RegistrationResponse {
|
|
|
182
204
|
data: {
|
|
183
205
|
agent: AgentRecord;
|
|
184
206
|
};
|
|
207
|
+
/**
|
|
208
|
+
* Round-12 (F16): backend-emitted advisories (e.g. `no_callback_endpoint`
|
|
209
|
+
* when apiEndpoint is omitted). Pre-fix the SDK whitelisted five fields
|
|
210
|
+
* on the way out and dropped this. Surface verbatim on both 201 and 202
|
|
211
|
+
* register paths.
|
|
212
|
+
*/
|
|
213
|
+
warnings?: Array<{
|
|
214
|
+
code: string;
|
|
215
|
+
message: string;
|
|
216
|
+
}>;
|
|
185
217
|
}
|
|
186
218
|
/** Raw 202 body — internal type, exposed via {@link RegisterResult}. */
|
|
187
219
|
interface PendingRegistrationResponse {
|
|
@@ -191,6 +223,11 @@ interface PendingRegistrationResponse {
|
|
|
191
223
|
expiresAt: string;
|
|
192
224
|
pollUrl: string;
|
|
193
225
|
message?: string;
|
|
226
|
+
/** Round-12 (F16): same advisories as 201 path. */
|
|
227
|
+
warnings?: Array<{
|
|
228
|
+
code: string;
|
|
229
|
+
message: string;
|
|
230
|
+
}>;
|
|
194
231
|
}
|
|
195
232
|
/** Agent record from the API. */
|
|
196
233
|
interface AgentRecord {
|
|
@@ -156,19 +156,41 @@ interface WaitForApprovalOptions {
|
|
|
156
156
|
type RegisterResult = {
|
|
157
157
|
status: 'active';
|
|
158
158
|
agent: AgentRecord;
|
|
159
|
+
/** Round-12 (F16): backend advisories surfaced verbatim. */
|
|
160
|
+
warnings?: Array<{
|
|
161
|
+
code: string;
|
|
162
|
+
message: string;
|
|
163
|
+
}>;
|
|
159
164
|
} | {
|
|
160
165
|
status: 'pending_approval';
|
|
161
166
|
requestId: string;
|
|
162
167
|
expiresAt: string;
|
|
163
168
|
pollUrl: string;
|
|
164
169
|
message?: string;
|
|
170
|
+
/** Round-12 (F16): backend advisories surfaced verbatim. */
|
|
171
|
+
warnings?: Array<{
|
|
172
|
+
code: string;
|
|
173
|
+
message: string;
|
|
174
|
+
}>;
|
|
165
175
|
};
|
|
166
176
|
/**
|
|
167
177
|
* Response shape from `pollRegistration(requestId)` and the internal poll
|
|
168
178
|
* loop. State `pending` means still awaiting owner; the others are terminal.
|
|
179
|
+
*
|
|
180
|
+
* Round-11 (F3): on `state: 'approved'`, the response also carries the
|
|
181
|
+
* canonical `astraId` — the partner-facing public agent identity that all
|
|
182
|
+
* verify-access / verify/{id} surfaces accept. The `agent` (UUID) field
|
|
183
|
+
* stays owner-private and is kept for backward compat.
|
|
169
184
|
*/
|
|
170
185
|
interface PollRegistrationResult {
|
|
171
186
|
state: 'pending' | 'approved' | 'denied' | 'expired';
|
|
187
|
+
/**
|
|
188
|
+
* Canonical `ASTRA-…` id. Populated when `state === 'approved'`; `null`
|
|
189
|
+
* (or absent) otherwise. This is the identifier to pass to public
|
|
190
|
+
* verification surfaces — UUIDs from the register response are owner-
|
|
191
|
+
* private request handles and are rejected by verify-access in v2.4.3+.
|
|
192
|
+
*/
|
|
193
|
+
astraId?: string | null;
|
|
172
194
|
agent?: AgentRecord;
|
|
173
195
|
reason?: string;
|
|
174
196
|
}
|
|
@@ -182,6 +204,16 @@ interface RegistrationResponse {
|
|
|
182
204
|
data: {
|
|
183
205
|
agent: AgentRecord;
|
|
184
206
|
};
|
|
207
|
+
/**
|
|
208
|
+
* Round-12 (F16): backend-emitted advisories (e.g. `no_callback_endpoint`
|
|
209
|
+
* when apiEndpoint is omitted). Pre-fix the SDK whitelisted five fields
|
|
210
|
+
* on the way out and dropped this. Surface verbatim on both 201 and 202
|
|
211
|
+
* register paths.
|
|
212
|
+
*/
|
|
213
|
+
warnings?: Array<{
|
|
214
|
+
code: string;
|
|
215
|
+
message: string;
|
|
216
|
+
}>;
|
|
185
217
|
}
|
|
186
218
|
/** Raw 202 body — internal type, exposed via {@link RegisterResult}. */
|
|
187
219
|
interface PendingRegistrationResponse {
|
|
@@ -191,6 +223,11 @@ interface PendingRegistrationResponse {
|
|
|
191
223
|
expiresAt: string;
|
|
192
224
|
pollUrl: string;
|
|
193
225
|
message?: string;
|
|
226
|
+
/** Round-12 (F16): same advisories as 201 path. */
|
|
227
|
+
warnings?: Array<{
|
|
228
|
+
code: string;
|
|
229
|
+
message: string;
|
|
230
|
+
}>;
|
|
194
231
|
}
|
|
195
232
|
/** Agent record from the API. */
|
|
196
233
|
interface AgentRecord {
|
|
@@ -182,9 +182,15 @@ var AstraSync = class {
|
|
|
182
182
|
};
|
|
183
183
|
const { status, body: raw } = await this.requestWithStatus("POST", "/api/agents/register", body);
|
|
184
184
|
if (status === 201) {
|
|
185
|
+
const activeBody = raw;
|
|
185
186
|
const active = {
|
|
186
187
|
status: "active",
|
|
187
|
-
agent:
|
|
188
|
+
agent: activeBody.data.agent,
|
|
189
|
+
// Round-12 (F16): pass backend advisories through verbatim.
|
|
190
|
+
// Pre-fix the SDK whitelisted five fields and silently dropped
|
|
191
|
+
// `warnings`, which left partners with no signal that
|
|
192
|
+
// `no_callback_endpoint` (or future advisories) had fired.
|
|
193
|
+
...activeBody.warnings && { warnings: activeBody.warnings }
|
|
188
194
|
};
|
|
189
195
|
return active;
|
|
190
196
|
}
|
|
@@ -194,7 +200,9 @@ var AstraSync = class {
|
|
|
194
200
|
requestId: pendingBody.requestId,
|
|
195
201
|
expiresAt: pendingBody.expiresAt,
|
|
196
202
|
pollUrl: pendingBody.pollUrl,
|
|
197
|
-
message: pendingBody.message
|
|
203
|
+
message: pendingBody.message,
|
|
204
|
+
// Round-12 (F16): same pass-through on the pending path.
|
|
205
|
+
...pendingBody.warnings && { warnings: pendingBody.warnings }
|
|
198
206
|
};
|
|
199
207
|
if (!options.waitForApproval) return pending;
|
|
200
208
|
return this.waitForApproval(pendingBody.requestId, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/registration/index.ts","../../src/registration/errors.ts","../../src/registration/api.ts"],"sourcesContent":["export { AstraSync } from './api';\nexport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\nexport type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n AgentRecord,\n VerifyResponse,\n HealthResponse,\n PDLSSConfig,\n PDLSSPurpose,\n PDLSSDuration,\n PDLSSLimits,\n PDLSSScope,\n PDLSSSelfInstantiation,\n ModelConfig,\n FrameworkConfig,\n AgentProtocol,\n} from './types';\n","import type { ApiErrorResponse } from './types';\n\n/** Base error class for AstraSync SDK errors. */\nexport class AstraSyncError extends Error {\n public readonly code?: string;\n public readonly statusCode: number;\n\n constructor(message: string, statusCode: number, code?: string) {\n super(message);\n this.name = 'AstraSyncError';\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/** Thrown when KYD verification is required before agent registration. */\nexport class KYDRequiredError extends AstraSyncError {\n public readonly kydUrl: string;\n public readonly ownerNotified: boolean;\n\n constructor(response: ApiErrorResponse) {\n const kydUrl = response.kydUrl || 'https://astrasync.ai/developer-profile';\n super(\n `KYD verification required before registering agents.\\nComplete your KYD profile at: ${kydUrl}`,\n 403,\n 'KYD_REQUIRED'\n );\n this.name = 'KYDRequiredError';\n this.kydUrl = kydUrl;\n this.ownerNotified = response.ownerNotified || false;\n }\n}\n\n/** Thrown when authentication fails. */\nexport class AuthenticationError extends AstraSyncError {\n constructor(message: string) {\n super(message, 401, 'AUTH_FAILED');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the owner denies the\n * pending registration request. The `reason` field, when present, mirrors the\n * deny note the owner left in the dashboard.\n */\nexport class RegistrationDeniedError extends AstraSyncError {\n public readonly requestId: string;\n public readonly reason?: string;\n\n constructor(requestId: string, reason?: string) {\n super(\n `Registration request ${requestId} was denied by the account owner.${reason ? ` Reason: ${reason}` : ''}`,\n 403,\n 'REGISTRATION_DENIED'\n );\n this.name = 'RegistrationDeniedError';\n this.requestId = requestId;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the pending request\n * passes its 14-day TTL with no owner decision. The agent must re-submit.\n */\nexport class RegistrationExpiredError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Registration request ${requestId} expired before the owner approved it. Submit a new registration request.`,\n 410,\n 'REGISTRATION_EXPIRED'\n );\n this.name = 'RegistrationExpiredError';\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the caller's local\n * `timeoutMs` elapses before the owner makes a decision. The request is still\n * live server-side — poll `pollRegistration(requestId)` to resume waiting, or\n * call `waitForApproval` again with a longer timeout.\n */\nexport class RegistrationTimeoutError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Timed out waiting for owner approval of registration request ${requestId}. The request is still active server-side; poll the request to resume waiting.`,\n 408,\n 'REGISTRATION_TIMEOUT'\n );\n this.name = 'RegistrationTimeoutError';\n this.requestId = requestId;\n }\n}\n","import type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n VerifyResponse,\n HealthResponse,\n ApiErrorResponse,\n AgentRecord,\n} from './types';\nimport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\n\nconst DEFAULT_BASE_URL = 'https://astrasync.ai';\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * AstraSync SDK client for registering and managing AI agents.\n *\n * @example\n * ```typescript\n * const client = new AstraSync({ apiKey: 'kya_your_api_key' });\n * const result = await client.register({\n * name: 'My Agent',\n * model: { modelName: 'gpt-4o', modelProvider: 'openai', modelType: 'llm' },\n * });\n * ```\n *\n * For staging, pass `baseUrl: 'https://staging.astrasync.ai'`.\n */\nexport class AstraSync {\n private readonly baseUrl: string;\n private readonly apiKey?: string;\n private readonly email?: string;\n private readonly password?: string;\n private readonly privateKey?: string;\n private cachedJwt?: string;\n private jwtExpiresAt?: number;\n\n constructor(config: AstraSyncConfig = {}) {\n let raw = (config.baseUrl || process.env.ASTRASYNC_API_URL || DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n // Round-10 (O2): tolerate the verify-side convention. `GatewayConfig.apiBaseUrl`\n // is documented as `https://astrasync.ai/api` (with /api), but\n // `AstraSyncConfig.baseUrl` is documented as the bare origin. Partners\n // passing the verify-style URL to the registration client hit a 404\n // because we'd then append `/api/agents/register` → double /api. Strip\n // a trailing `/api` and warn once so the partner can fix the source.\n if (raw.toLowerCase().endsWith('/api')) {\n raw = raw.slice(0, -'/api'.length);\n if (config.baseUrl && !config.silent) {\n // eslint-disable-next-line no-console\n console.warn(\n `[AstraSync] baseUrl '${config.baseUrl}' had a trailing /api — stripped to '${raw}'. ` +\n `Pass the bare origin (e.g. 'https://astrasync.ai' or 'https://staging.astrasync.ai') ` +\n `to AstraSync(). The /api suffix is the verify-gateway (GatewayConfig.apiBaseUrl) convention.`\n );\n }\n }\n this.baseUrl = raw;\n\n this.apiKey = config.apiKey || process.env.ASTRASYNC_API_KEY;\n this.email = config.email;\n this.password = config.password;\n this.privateKey = config.privateKey;\n\n if (!this.apiKey && !this.email) {\n throw new AuthenticationError(\n 'Authentication required. Provide apiKey, or email+password. ' +\n 'Set ASTRASYNC_API_KEY env var or pass config to constructor.'\n );\n }\n\n if (this.email && !this.password) {\n throw new AuthenticationError('Password is required when using email authentication.');\n }\n }\n\n /**\n * Register a new AI agent on the AstraSync KYA Platform.\n *\n * The backend response depends on auth context:\n * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,\n * returns `{ status: 'active', agent }`.\n * - **API-key only** (no signature): 202 pending, returns\n * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The\n * owner is notified by email and a dashboard alert is emitted; the agent\n * becomes active only after the owner approves.\n *\n * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the\n * request until it resolves, then return the live agent record. The promise\n * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or\n * `RegistrationTimeoutError` on the corresponding terminal states.\n *\n * @example Non-blocking (default — best for serverless / scheduled agents):\n * ```typescript\n * const result = await sdk.register({ name, pdlss });\n * if (result.status === 'pending_approval') {\n * storeRequestId(result.requestId);\n * return; // function exits; resume later via pollRegistration()\n * }\n * ```\n *\n * @example Blocking (best for long-running services + CLI):\n * ```typescript\n * const agent = await sdk.register({\n * name, pdlss, waitForApproval: true, timeoutMs: 600_000,\n * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),\n * });\n * ```\n */\n async register(\n options: RegisterOptions & WaitForApprovalOptions\n ): Promise<RegisterResult | AgentRecord> {\n const body: Record<string, unknown> = {\n name: options.name,\n ...(options.description && { description: options.description }),\n ...(options.agentType && { agentType: options.agentType }),\n ...(options.apiEndpoint && { apiEndpoint: options.apiEndpoint }),\n ...(options.model && { model: options.model }),\n ...(options.framework && { framework: options.framework }),\n ...(options.protocols && { protocols: options.protocols }),\n ...(options.metadata && { metadata: options.metadata }),\n ...(options.pdlss && { pdlss: options.pdlss }),\n };\n\n const { status, body: raw } = await this.requestWithStatus<\n RegistrationResponse | PendingRegistrationResponse\n >('POST', '/api/agents/register', body);\n\n if (status === 201) {\n const active: RegisterResult = {\n status: 'active',\n agent: (raw as RegistrationResponse).data.agent,\n };\n return active;\n }\n\n // 202 Accepted — owner approval required.\n const pendingBody = raw as PendingRegistrationResponse;\n const pending: RegisterResult = {\n status: 'pending_approval',\n requestId: pendingBody.requestId,\n expiresAt: pendingBody.expiresAt,\n pollUrl: pendingBody.pollUrl,\n message: pendingBody.message,\n };\n\n if (!options.waitForApproval) return pending;\n\n return this.waitForApproval(pendingBody.requestId, options);\n }\n\n /**\n * Poll the current state of a pending-approval registration request.\n *\n * Useful for caller-driven polling when `waitForApproval: false` (the\n * default). The endpoint is unauthenticated — pass the `requestId` that\n * was returned from the 202 response.\n *\n * @returns `state: 'pending'` while awaiting; `'approved'` carries the\n * minted agent in `agent`; `'denied'` may carry the owner's\n * `reason`; `'expired'` is terminal after 14 days.\n */\n async pollRegistration(requestId: string): Promise<PollRegistrationResult> {\n const url = `${this.baseUrl}/api/agents/request-registration/${requestId}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) {\n const errBody = (await res.json().catch(() => ({}))) as ApiErrorResponse;\n throw new AstraSyncError(\n errBody.error || `pollRegistration failed: ${res.status}`,\n res.status,\n errBody.code\n );\n }\n return (await res.json()) as PollRegistrationResult;\n }\n\n /**\n * Block until a pending registration request resolves to a terminal state.\n * Resolves to the live `AgentRecord` on approval; rejects with the matching\n * Registration*Error on deny/expire/timeout. Usually called via\n * `register({ waitForApproval: true })`, but exposed for callers that want\n * to fire-and-forget the initial register call and resume waiting later\n * (e.g. after restoring a stored `requestId` on cold start).\n */\n async waitForApproval(\n requestId: string,\n options: WaitForApprovalOptions = {}\n ): Promise<AgentRecord> {\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 5_000;\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n while (Date.now() < deadline) {\n const result = await this.pollRegistration(requestId);\n const ageMs = Date.now() - start;\n options.onPending?.({ requestId, ageMs });\n\n if (result.state === 'approved') {\n if (!result.agent) {\n throw new AstraSyncError(\n `Registration ${requestId} reported approved but no agent payload returned.`,\n 500\n );\n }\n return result.agent;\n }\n if (result.state === 'denied') {\n throw new RegistrationDeniedError(requestId, result.reason);\n }\n if (result.state === 'expired') {\n throw new RegistrationExpiredError(requestId);\n }\n await sleep(pollIntervalMs);\n }\n throw new RegistrationTimeoutError(requestId);\n }\n\n /**\n * Look up an agent's public profile by ASTRA ID or UUID.\n */\n async verify(agentId: string): Promise<VerifyResponse> {\n return this.request<VerifyResponse>('GET', `/api/agents/verify/${agentId}`);\n }\n\n /**\n * Check API health.\n */\n async health(): Promise<HealthResponse> {\n const res = await fetch(`${this.baseUrl}/api/health/`);\n if (!res.ok) {\n throw new AstraSyncError(`Health check failed: ${res.status}`, res.status);\n }\n return res.json() as Promise<HealthResponse>;\n }\n\n // ── Private helpers ──────────────────────────────────────────────\n\n private async request<T>(method: string, endpoint: string, body?: unknown): Promise<T> {\n const { body: parsed } = await this.requestWithStatus<T>(method, endpoint, body);\n return parsed;\n }\n\n /**\n * Variant of {@link request} that also returns the HTTP status code, so\n * callers can branch on 201 vs 202 (or other success codes) without losing\n * type information about the response body.\n */\n private async requestWithStatus<T>(\n method: string,\n endpoint: string,\n body?: unknown\n ): Promise<{ status: number; body: T }> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Set auth header\n const token = await this.getAuthToken();\n headers['Authorization'] = `Bearer ${token}`;\n\n // Sign request if private key is configured\n if (this.privateKey) {\n const signature = await this.signRequest(method, endpoint, body || {});\n headers['X-AstraSync-Signature'] = signature;\n }\n\n const res = await fetch(url, {\n method,\n headers,\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n\n if (!res.ok) {\n const errorBody = (await res\n .json()\n .catch(() => ({ error: res.statusText }))) as ApiErrorResponse;\n\n // Handle KYD_REQUIRED specifically\n if (res.status === 403 && errorBody.code === 'KYD_REQUIRED') {\n throw new KYDRequiredError(errorBody);\n }\n\n throw new AstraSyncError(\n errorBody.error || `Request failed: ${res.status}`,\n res.status,\n errorBody.code\n );\n }\n\n return { status: res.status, body: (await res.json()) as T };\n }\n\n private async getAuthToken(): Promise<string> {\n // API key auth — use directly\n if (this.apiKey) {\n return this.apiKey;\n }\n\n // Email+password — login and cache JWT\n if (this.cachedJwt && this.jwtExpiresAt && Date.now() < this.jwtExpiresAt) {\n return this.cachedJwt;\n }\n\n const res = await fetch(`${this.baseUrl}/api/auth/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: this.email, password: this.password }),\n });\n\n if (!res.ok) {\n const errorBody = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n throw new AuthenticationError(\n (errorBody.message as string) || (errorBody.error as string) || 'Login failed'\n );\n }\n\n const data = (await res.json()) as { data: { token: string } };\n this.cachedJwt = data.data.token;\n // Cache for 6 days (tokens expire in 7)\n this.jwtExpiresAt = Date.now() + 6 * 24 * 60 * 60 * 1000;\n\n return this.cachedJwt;\n }\n\n /**\n * Sign a request using secp256k1 (ethers.js).\n * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY\n * Must match apps/backend/src/services/signature-verify.service.ts exactly.\n */\n private async signRequest(method: string, endpoint: string, body: unknown): Promise<string> {\n const { Wallet } = await import('ethers');\n const sorted = this.sortObjectKeys(body);\n const canonical = `${method}:${endpoint}:${JSON.stringify(sorted)}`;\n const wallet = new Wallet(this.privateKey!);\n return wallet.signMessage(canonical);\n }\n\n /** Recursively sort object keys for canonical JSON representation. */\n private sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortObjectKeys(item));\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,YAAoB,MAAe;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AAAA,EACd;AACF;AAG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QAAI,CAAC,IAAI,IAAI;AACX,YAAM,YAAa,MAAM,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACpD,YAAM,IAAI;AAAA,QACP,UAAU,WAAuB,UAAU,SAAoB;AAAA,MAClE;AAAA,IACF;AAEA,UAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,SAAK,YAAY,KAAK,KAAK;AAE3B,SAAK,eAAe,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK;AAEpD,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,YAAY,QAAgB,UAAkB,MAAgC;AAC1F,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,QAAQ;AACxC,UAAM,SAAS,KAAK,eAAe,IAAI;AACvC,UAAM,YAAY,GAAG,MAAM,IAAI,QAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;AACjE,UAAM,SAAS,IAAI,OAAO,KAAK,UAAW;AAC1C,WAAO,OAAO,YAAY,SAAS;AAAA,EACrC;AAAA;AAAA,EAGQ,eAAe,KAAuB;AAC5C,QAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,aAAO;AAAA,IACT;AACA,QAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,aAAO,IAAI,IAAI,CAAC,SAAS,KAAK,eAAe,IAAI,CAAC;AAAA,IACpD;AACA,UAAM,SAAkC,CAAC;AACzC,eAAW,OAAO,OAAO,KAAK,GAAG,EAAE,KAAK,GAAG;AACzC,aAAO,GAAG,IAAI,KAAK,eAAgB,IAAgC,GAAG,CAAC;AAAA,IACzE;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/registration/index.ts","../../src/registration/errors.ts","../../src/registration/api.ts"],"sourcesContent":["export { AstraSync } from './api';\nexport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\nexport type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n AgentRecord,\n VerifyResponse,\n HealthResponse,\n PDLSSConfig,\n PDLSSPurpose,\n PDLSSDuration,\n PDLSSLimits,\n PDLSSScope,\n PDLSSSelfInstantiation,\n ModelConfig,\n FrameworkConfig,\n AgentProtocol,\n} from './types';\n","import type { ApiErrorResponse } from './types';\n\n/** Base error class for AstraSync SDK errors. */\nexport class AstraSyncError extends Error {\n public readonly code?: string;\n public readonly statusCode: number;\n\n constructor(message: string, statusCode: number, code?: string) {\n super(message);\n this.name = 'AstraSyncError';\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/** Thrown when KYD verification is required before agent registration. */\nexport class KYDRequiredError extends AstraSyncError {\n public readonly kydUrl: string;\n public readonly ownerNotified: boolean;\n\n constructor(response: ApiErrorResponse) {\n const kydUrl = response.kydUrl || 'https://astrasync.ai/developer-profile';\n super(\n `KYD verification required before registering agents.\\nComplete your KYD profile at: ${kydUrl}`,\n 403,\n 'KYD_REQUIRED'\n );\n this.name = 'KYDRequiredError';\n this.kydUrl = kydUrl;\n this.ownerNotified = response.ownerNotified || false;\n }\n}\n\n/** Thrown when authentication fails. */\nexport class AuthenticationError extends AstraSyncError {\n constructor(message: string) {\n super(message, 401, 'AUTH_FAILED');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the owner denies the\n * pending registration request. The `reason` field, when present, mirrors the\n * deny note the owner left in the dashboard.\n */\nexport class RegistrationDeniedError extends AstraSyncError {\n public readonly requestId: string;\n public readonly reason?: string;\n\n constructor(requestId: string, reason?: string) {\n super(\n `Registration request ${requestId} was denied by the account owner.${reason ? ` Reason: ${reason}` : ''}`,\n 403,\n 'REGISTRATION_DENIED'\n );\n this.name = 'RegistrationDeniedError';\n this.requestId = requestId;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the pending request\n * passes its 14-day TTL with no owner decision. The agent must re-submit.\n */\nexport class RegistrationExpiredError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Registration request ${requestId} expired before the owner approved it. Submit a new registration request.`,\n 410,\n 'REGISTRATION_EXPIRED'\n );\n this.name = 'RegistrationExpiredError';\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the caller's local\n * `timeoutMs` elapses before the owner makes a decision. The request is still\n * live server-side — poll `pollRegistration(requestId)` to resume waiting, or\n * call `waitForApproval` again with a longer timeout.\n */\nexport class RegistrationTimeoutError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Timed out waiting for owner approval of registration request ${requestId}. The request is still active server-side; poll the request to resume waiting.`,\n 408,\n 'REGISTRATION_TIMEOUT'\n );\n this.name = 'RegistrationTimeoutError';\n this.requestId = requestId;\n }\n}\n","import type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n VerifyResponse,\n HealthResponse,\n ApiErrorResponse,\n AgentRecord,\n} from './types';\nimport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\n\nconst DEFAULT_BASE_URL = 'https://astrasync.ai';\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * AstraSync SDK client for registering and managing AI agents.\n *\n * @example\n * ```typescript\n * const client = new AstraSync({ apiKey: 'kya_your_api_key' });\n * const result = await client.register({\n * name: 'My Agent',\n * model: { modelName: 'gpt-4o', modelProvider: 'openai', modelType: 'llm' },\n * });\n * ```\n *\n * For staging, pass `baseUrl: 'https://staging.astrasync.ai'`.\n */\nexport class AstraSync {\n private readonly baseUrl: string;\n private readonly apiKey?: string;\n private readonly email?: string;\n private readonly password?: string;\n private readonly privateKey?: string;\n private cachedJwt?: string;\n private jwtExpiresAt?: number;\n\n constructor(config: AstraSyncConfig = {}) {\n let raw = (config.baseUrl || process.env.ASTRASYNC_API_URL || DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n // Round-10 (O2): tolerate the verify-side convention. `GatewayConfig.apiBaseUrl`\n // is documented as `https://astrasync.ai/api` (with /api), but\n // `AstraSyncConfig.baseUrl` is documented as the bare origin. Partners\n // passing the verify-style URL to the registration client hit a 404\n // because we'd then append `/api/agents/register` → double /api. Strip\n // a trailing `/api` and warn once so the partner can fix the source.\n if (raw.toLowerCase().endsWith('/api')) {\n raw = raw.slice(0, -'/api'.length);\n if (config.baseUrl && !config.silent) {\n // eslint-disable-next-line no-console\n console.warn(\n `[AstraSync] baseUrl '${config.baseUrl}' had a trailing /api — stripped to '${raw}'. ` +\n `Pass the bare origin (e.g. 'https://astrasync.ai' or 'https://staging.astrasync.ai') ` +\n `to AstraSync(). The /api suffix is the verify-gateway (GatewayConfig.apiBaseUrl) convention.`\n );\n }\n }\n this.baseUrl = raw;\n\n this.apiKey = config.apiKey || process.env.ASTRASYNC_API_KEY;\n this.email = config.email;\n this.password = config.password;\n this.privateKey = config.privateKey;\n\n if (!this.apiKey && !this.email) {\n throw new AuthenticationError(\n 'Authentication required. Provide apiKey, or email+password. ' +\n 'Set ASTRASYNC_API_KEY env var or pass config to constructor.'\n );\n }\n\n if (this.email && !this.password) {\n throw new AuthenticationError('Password is required when using email authentication.');\n }\n }\n\n /**\n * Register a new AI agent on the AstraSync KYA Platform.\n *\n * The backend response depends on auth context:\n * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,\n * returns `{ status: 'active', agent }`.\n * - **API-key only** (no signature): 202 pending, returns\n * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The\n * owner is notified by email and a dashboard alert is emitted; the agent\n * becomes active only after the owner approves.\n *\n * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the\n * request until it resolves, then return the live agent record. The promise\n * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or\n * `RegistrationTimeoutError` on the corresponding terminal states.\n *\n * @example Non-blocking (default — best for serverless / scheduled agents):\n * ```typescript\n * const result = await sdk.register({ name, pdlss });\n * if (result.status === 'pending_approval') {\n * storeRequestId(result.requestId);\n * return; // function exits; resume later via pollRegistration()\n * }\n * ```\n *\n * @example Blocking (best for long-running services + CLI):\n * ```typescript\n * const agent = await sdk.register({\n * name, pdlss, waitForApproval: true, timeoutMs: 600_000,\n * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),\n * });\n * ```\n */\n async register(\n options: RegisterOptions & WaitForApprovalOptions\n ): Promise<RegisterResult | AgentRecord> {\n const body: Record<string, unknown> = {\n name: options.name,\n ...(options.description && { description: options.description }),\n ...(options.agentType && { agentType: options.agentType }),\n ...(options.apiEndpoint && { apiEndpoint: options.apiEndpoint }),\n ...(options.model && { model: options.model }),\n ...(options.framework && { framework: options.framework }),\n ...(options.protocols && { protocols: options.protocols }),\n ...(options.metadata && { metadata: options.metadata }),\n ...(options.pdlss && { pdlss: options.pdlss }),\n };\n\n const { status, body: raw } = await this.requestWithStatus<\n RegistrationResponse | PendingRegistrationResponse\n >('POST', '/api/agents/register', body);\n\n if (status === 201) {\n const activeBody = raw as RegistrationResponse;\n const active: RegisterResult = {\n status: 'active',\n agent: activeBody.data.agent,\n // Round-12 (F16): pass backend advisories through verbatim.\n // Pre-fix the SDK whitelisted five fields and silently dropped\n // `warnings`, which left partners with no signal that\n // `no_callback_endpoint` (or future advisories) had fired.\n ...(activeBody.warnings && { warnings: activeBody.warnings }),\n };\n return active;\n }\n\n // 202 Accepted — owner approval required.\n const pendingBody = raw as PendingRegistrationResponse;\n const pending: RegisterResult = {\n status: 'pending_approval',\n requestId: pendingBody.requestId,\n expiresAt: pendingBody.expiresAt,\n pollUrl: pendingBody.pollUrl,\n message: pendingBody.message,\n // Round-12 (F16): same pass-through on the pending path.\n ...(pendingBody.warnings && { warnings: pendingBody.warnings }),\n };\n\n if (!options.waitForApproval) return pending;\n\n return this.waitForApproval(pendingBody.requestId, options);\n }\n\n /**\n * Poll the current state of a pending-approval registration request.\n *\n * Useful for caller-driven polling when `waitForApproval: false` (the\n * default). The endpoint is unauthenticated — pass the `requestId` that\n * was returned from the 202 response.\n *\n * @returns `state: 'pending'` while awaiting; `'approved'` carries the\n * minted agent in `agent`; `'denied'` may carry the owner's\n * `reason`; `'expired'` is terminal after 14 days.\n */\n async pollRegistration(requestId: string): Promise<PollRegistrationResult> {\n const url = `${this.baseUrl}/api/agents/request-registration/${requestId}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) {\n const errBody = (await res.json().catch(() => ({}))) as ApiErrorResponse;\n throw new AstraSyncError(\n errBody.error || `pollRegistration failed: ${res.status}`,\n res.status,\n errBody.code\n );\n }\n return (await res.json()) as PollRegistrationResult;\n }\n\n /**\n * Block until a pending registration request resolves to a terminal state.\n * Resolves to the live `AgentRecord` on approval; rejects with the matching\n * Registration*Error on deny/expire/timeout. Usually called via\n * `register({ waitForApproval: true })`, but exposed for callers that want\n * to fire-and-forget the initial register call and resume waiting later\n * (e.g. after restoring a stored `requestId` on cold start).\n */\n async waitForApproval(\n requestId: string,\n options: WaitForApprovalOptions = {}\n ): Promise<AgentRecord> {\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 5_000;\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n while (Date.now() < deadline) {\n const result = await this.pollRegistration(requestId);\n const ageMs = Date.now() - start;\n options.onPending?.({ requestId, ageMs });\n\n if (result.state === 'approved') {\n if (!result.agent) {\n throw new AstraSyncError(\n `Registration ${requestId} reported approved but no agent payload returned.`,\n 500\n );\n }\n return result.agent;\n }\n if (result.state === 'denied') {\n throw new RegistrationDeniedError(requestId, result.reason);\n }\n if (result.state === 'expired') {\n throw new RegistrationExpiredError(requestId);\n }\n await sleep(pollIntervalMs);\n }\n throw new RegistrationTimeoutError(requestId);\n }\n\n /**\n * Look up an agent's public profile by ASTRA ID or UUID.\n */\n async verify(agentId: string): Promise<VerifyResponse> {\n return this.request<VerifyResponse>('GET', `/api/agents/verify/${agentId}`);\n }\n\n /**\n * Check API health.\n */\n async health(): Promise<HealthResponse> {\n const res = await fetch(`${this.baseUrl}/api/health/`);\n if (!res.ok) {\n throw new AstraSyncError(`Health check failed: ${res.status}`, res.status);\n }\n return res.json() as Promise<HealthResponse>;\n }\n\n // ── Private helpers ──────────────────────────────────────────────\n\n private async request<T>(method: string, endpoint: string, body?: unknown): Promise<T> {\n const { body: parsed } = await this.requestWithStatus<T>(method, endpoint, body);\n return parsed;\n }\n\n /**\n * Variant of {@link request} that also returns the HTTP status code, so\n * callers can branch on 201 vs 202 (or other success codes) without losing\n * type information about the response body.\n */\n private async requestWithStatus<T>(\n method: string,\n endpoint: string,\n body?: unknown\n ): Promise<{ status: number; body: T }> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Set auth header\n const token = await this.getAuthToken();\n headers['Authorization'] = `Bearer ${token}`;\n\n // Sign request if private key is configured\n if (this.privateKey) {\n const signature = await this.signRequest(method, endpoint, body || {});\n headers['X-AstraSync-Signature'] = signature;\n }\n\n const res = await fetch(url, {\n method,\n headers,\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n\n if (!res.ok) {\n const errorBody = (await res\n .json()\n .catch(() => ({ error: res.statusText }))) as ApiErrorResponse;\n\n // Handle KYD_REQUIRED specifically\n if (res.status === 403 && errorBody.code === 'KYD_REQUIRED') {\n throw new KYDRequiredError(errorBody);\n }\n\n throw new AstraSyncError(\n errorBody.error || `Request failed: ${res.status}`,\n res.status,\n errorBody.code\n );\n }\n\n return { status: res.status, body: (await res.json()) as T };\n }\n\n private async getAuthToken(): Promise<string> {\n // API key auth — use directly\n if (this.apiKey) {\n return this.apiKey;\n }\n\n // Email+password — login and cache JWT\n if (this.cachedJwt && this.jwtExpiresAt && Date.now() < this.jwtExpiresAt) {\n return this.cachedJwt;\n }\n\n const res = await fetch(`${this.baseUrl}/api/auth/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: this.email, password: this.password }),\n });\n\n if (!res.ok) {\n const errorBody = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n throw new AuthenticationError(\n (errorBody.message as string) || (errorBody.error as string) || 'Login failed'\n );\n }\n\n const data = (await res.json()) as { data: { token: string } };\n this.cachedJwt = data.data.token;\n // Cache for 6 days (tokens expire in 7)\n this.jwtExpiresAt = Date.now() + 6 * 24 * 60 * 60 * 1000;\n\n return this.cachedJwt;\n }\n\n /**\n * Sign a request using secp256k1 (ethers.js).\n * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY\n * Must match apps/backend/src/services/signature-verify.service.ts exactly.\n */\n private async signRequest(method: string, endpoint: string, body: unknown): Promise<string> {\n const { Wallet } = await import('ethers');\n const sorted = this.sortObjectKeys(body);\n const canonical = `${method}:${endpoint}:${JSON.stringify(sorted)}`;\n const wallet = new Wallet(this.privateKey!);\n return wallet.signMessage(canonical);\n }\n\n /** Recursively sort object keys for canonical JSON representation. */\n private sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortObjectKeys(item));\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,YAAoB,MAAe;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;A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A,EACT;AACF;","names":[]}
|
|
@@ -140,9 +140,15 @@ var AstraSync = class {
|
|
|
140
140
|
};
|
|
141
141
|
const { status, body: raw } = await this.requestWithStatus("POST", "/api/agents/register", body);
|
|
142
142
|
if (status === 201) {
|
|
143
|
+
const activeBody = raw;
|
|
143
144
|
const active = {
|
|
144
145
|
status: "active",
|
|
145
|
-
agent:
|
|
146
|
+
agent: activeBody.data.agent,
|
|
147
|
+
// Round-12 (F16): pass backend advisories through verbatim.
|
|
148
|
+
// Pre-fix the SDK whitelisted five fields and silently dropped
|
|
149
|
+
// `warnings`, which left partners with no signal that
|
|
150
|
+
// `no_callback_endpoint` (or future advisories) had fired.
|
|
151
|
+
...activeBody.warnings && { warnings: activeBody.warnings }
|
|
146
152
|
};
|
|
147
153
|
return active;
|
|
148
154
|
}
|
|
@@ -152,7 +158,9 @@ var AstraSync = class {
|
|
|
152
158
|
requestId: pendingBody.requestId,
|
|
153
159
|
expiresAt: pendingBody.expiresAt,
|
|
154
160
|
pollUrl: pendingBody.pollUrl,
|
|
155
|
-
message: pendingBody.message
|
|
161
|
+
message: pendingBody.message,
|
|
162
|
+
// Round-12 (F16): same pass-through on the pending path.
|
|
163
|
+
...pendingBody.warnings && { warnings: pendingBody.warnings }
|
|
156
164
|
};
|
|
157
165
|
if (!options.waitForApproval) return pending;
|
|
158
166
|
return this.waitForApproval(pendingBody.requestId, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/registration/errors.ts","../../src/registration/api.ts"],"sourcesContent":["import type { ApiErrorResponse } from './types';\n\n/** Base error class for AstraSync SDK errors. */\nexport class AstraSyncError extends Error {\n public readonly code?: string;\n public readonly statusCode: number;\n\n constructor(message: string, statusCode: number, code?: string) {\n super(message);\n this.name = 'AstraSyncError';\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/** Thrown when KYD verification is required before agent registration. */\nexport class KYDRequiredError extends AstraSyncError {\n public readonly kydUrl: string;\n public readonly ownerNotified: boolean;\n\n constructor(response: ApiErrorResponse) {\n const kydUrl = response.kydUrl || 'https://astrasync.ai/developer-profile';\n super(\n `KYD verification required before registering agents.\\nComplete your KYD profile at: ${kydUrl}`,\n 403,\n 'KYD_REQUIRED'\n );\n this.name = 'KYDRequiredError';\n this.kydUrl = kydUrl;\n this.ownerNotified = response.ownerNotified || false;\n }\n}\n\n/** Thrown when authentication fails. */\nexport class AuthenticationError extends AstraSyncError {\n constructor(message: string) {\n super(message, 401, 'AUTH_FAILED');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the owner denies the\n * pending registration request. The `reason` field, when present, mirrors the\n * deny note the owner left in the dashboard.\n */\nexport class RegistrationDeniedError extends AstraSyncError {\n public readonly requestId: string;\n public readonly reason?: string;\n\n constructor(requestId: string, reason?: string) {\n super(\n `Registration request ${requestId} was denied by the account owner.${reason ? ` Reason: ${reason}` : ''}`,\n 403,\n 'REGISTRATION_DENIED'\n );\n this.name = 'RegistrationDeniedError';\n this.requestId = requestId;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the pending request\n * passes its 14-day TTL with no owner decision. The agent must re-submit.\n */\nexport class RegistrationExpiredError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Registration request ${requestId} expired before the owner approved it. Submit a new registration request.`,\n 410,\n 'REGISTRATION_EXPIRED'\n );\n this.name = 'RegistrationExpiredError';\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the caller's local\n * `timeoutMs` elapses before the owner makes a decision. The request is still\n * live server-side — poll `pollRegistration(requestId)` to resume waiting, or\n * call `waitForApproval` again with a longer timeout.\n */\nexport class RegistrationTimeoutError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Timed out waiting for owner approval of registration request ${requestId}. The request is still active server-side; poll the request to resume waiting.`,\n 408,\n 'REGISTRATION_TIMEOUT'\n );\n this.name = 'RegistrationTimeoutError';\n this.requestId = requestId;\n }\n}\n","import type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n VerifyResponse,\n HealthResponse,\n ApiErrorResponse,\n AgentRecord,\n} from './types';\nimport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\n\nconst DEFAULT_BASE_URL = 'https://astrasync.ai';\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * AstraSync SDK client for registering and managing AI agents.\n *\n * @example\n * ```typescript\n * const client = new AstraSync({ apiKey: 'kya_your_api_key' });\n * const result = await client.register({\n * name: 'My Agent',\n * model: { modelName: 'gpt-4o', modelProvider: 'openai', modelType: 'llm' },\n * });\n * ```\n *\n * For staging, pass `baseUrl: 'https://staging.astrasync.ai'`.\n */\nexport class AstraSync {\n private readonly baseUrl: string;\n private readonly apiKey?: string;\n private readonly email?: string;\n private readonly password?: string;\n private readonly privateKey?: string;\n private cachedJwt?: string;\n private jwtExpiresAt?: number;\n\n constructor(config: AstraSyncConfig = {}) {\n let raw = (config.baseUrl || process.env.ASTRASYNC_API_URL || DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n // Round-10 (O2): tolerate the verify-side convention. `GatewayConfig.apiBaseUrl`\n // is documented as `https://astrasync.ai/api` (with /api), but\n // `AstraSyncConfig.baseUrl` is documented as the bare origin. Partners\n // passing the verify-style URL to the registration client hit a 404\n // because we'd then append `/api/agents/register` → double /api. Strip\n // a trailing `/api` and warn once so the partner can fix the source.\n if (raw.toLowerCase().endsWith('/api')) {\n raw = raw.slice(0, -'/api'.length);\n if (config.baseUrl && !config.silent) {\n // eslint-disable-next-line no-console\n console.warn(\n `[AstraSync] baseUrl '${config.baseUrl}' had a trailing /api — stripped to '${raw}'. ` +\n `Pass the bare origin (e.g. 'https://astrasync.ai' or 'https://staging.astrasync.ai') ` +\n `to AstraSync(). The /api suffix is the verify-gateway (GatewayConfig.apiBaseUrl) convention.`\n );\n }\n }\n this.baseUrl = raw;\n\n this.apiKey = config.apiKey || process.env.ASTRASYNC_API_KEY;\n this.email = config.email;\n this.password = config.password;\n this.privateKey = config.privateKey;\n\n if (!this.apiKey && !this.email) {\n throw new AuthenticationError(\n 'Authentication required. Provide apiKey, or email+password. ' +\n 'Set ASTRASYNC_API_KEY env var or pass config to constructor.'\n );\n }\n\n if (this.email && !this.password) {\n throw new AuthenticationError('Password is required when using email authentication.');\n }\n }\n\n /**\n * Register a new AI agent on the AstraSync KYA Platform.\n *\n * The backend response depends on auth context:\n * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,\n * returns `{ status: 'active', agent }`.\n * - **API-key only** (no signature): 202 pending, returns\n * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The\n * owner is notified by email and a dashboard alert is emitted; the agent\n * becomes active only after the owner approves.\n *\n * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the\n * request until it resolves, then return the live agent record. The promise\n * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or\n * `RegistrationTimeoutError` on the corresponding terminal states.\n *\n * @example Non-blocking (default — best for serverless / scheduled agents):\n * ```typescript\n * const result = await sdk.register({ name, pdlss });\n * if (result.status === 'pending_approval') {\n * storeRequestId(result.requestId);\n * return; // function exits; resume later via pollRegistration()\n * }\n * ```\n *\n * @example Blocking (best for long-running services + CLI):\n * ```typescript\n * const agent = await sdk.register({\n * name, pdlss, waitForApproval: true, timeoutMs: 600_000,\n * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),\n * });\n * ```\n */\n async register(\n options: RegisterOptions & WaitForApprovalOptions\n ): Promise<RegisterResult | AgentRecord> {\n const body: Record<string, unknown> = {\n name: options.name,\n ...(options.description && { description: options.description }),\n ...(options.agentType && { agentType: options.agentType }),\n ...(options.apiEndpoint && { apiEndpoint: options.apiEndpoint }),\n ...(options.model && { model: options.model }),\n ...(options.framework && { framework: options.framework }),\n ...(options.protocols && { protocols: options.protocols }),\n ...(options.metadata && { metadata: options.metadata }),\n ...(options.pdlss && { pdlss: options.pdlss }),\n };\n\n const { status, body: raw } = await this.requestWithStatus<\n RegistrationResponse | PendingRegistrationResponse\n >('POST', '/api/agents/register', body);\n\n if (status === 201) {\n const active: RegisterResult = {\n status: 'active',\n agent: (raw as RegistrationResponse).data.agent,\n };\n return active;\n }\n\n // 202 Accepted — owner approval required.\n const pendingBody = raw as PendingRegistrationResponse;\n const pending: RegisterResult = {\n status: 'pending_approval',\n requestId: pendingBody.requestId,\n expiresAt: pendingBody.expiresAt,\n pollUrl: pendingBody.pollUrl,\n message: pendingBody.message,\n };\n\n if (!options.waitForApproval) return pending;\n\n return this.waitForApproval(pendingBody.requestId, options);\n }\n\n /**\n * Poll the current state of a pending-approval registration request.\n *\n * Useful for caller-driven polling when `waitForApproval: false` (the\n * default). The endpoint is unauthenticated — pass the `requestId` that\n * was returned from the 202 response.\n *\n * @returns `state: 'pending'` while awaiting; `'approved'` carries the\n * minted agent in `agent`; `'denied'` may carry the owner's\n * `reason`; `'expired'` is terminal after 14 days.\n */\n async pollRegistration(requestId: string): Promise<PollRegistrationResult> {\n const url = `${this.baseUrl}/api/agents/request-registration/${requestId}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) {\n const errBody = (await res.json().catch(() => ({}))) as ApiErrorResponse;\n throw new AstraSyncError(\n errBody.error || `pollRegistration failed: ${res.status}`,\n res.status,\n errBody.code\n );\n }\n return (await res.json()) as PollRegistrationResult;\n }\n\n /**\n * Block until a pending registration request resolves to a terminal state.\n * Resolves to the live `AgentRecord` on approval; rejects with the matching\n * Registration*Error on deny/expire/timeout. Usually called via\n * `register({ waitForApproval: true })`, but exposed for callers that want\n * to fire-and-forget the initial register call and resume waiting later\n * (e.g. after restoring a stored `requestId` on cold start).\n */\n async waitForApproval(\n requestId: string,\n options: WaitForApprovalOptions = {}\n ): Promise<AgentRecord> {\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 5_000;\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n while (Date.now() < deadline) {\n const result = await this.pollRegistration(requestId);\n const ageMs = Date.now() - start;\n options.onPending?.({ requestId, ageMs });\n\n if (result.state === 'approved') {\n if (!result.agent) {\n throw new AstraSyncError(\n `Registration ${requestId} reported approved but no agent payload returned.`,\n 500\n );\n }\n return result.agent;\n }\n if (result.state === 'denied') {\n throw new RegistrationDeniedError(requestId, result.reason);\n }\n if (result.state === 'expired') {\n throw new RegistrationExpiredError(requestId);\n }\n await sleep(pollIntervalMs);\n }\n throw new RegistrationTimeoutError(requestId);\n }\n\n /**\n * Look up an agent's public profile by ASTRA ID or UUID.\n */\n async verify(agentId: string): Promise<VerifyResponse> {\n return this.request<VerifyResponse>('GET', `/api/agents/verify/${agentId}`);\n }\n\n /**\n * Check API health.\n */\n async health(): Promise<HealthResponse> {\n const res = await fetch(`${this.baseUrl}/api/health/`);\n if (!res.ok) {\n throw new AstraSyncError(`Health check failed: ${res.status}`, res.status);\n }\n return res.json() as Promise<HealthResponse>;\n }\n\n // ── Private helpers ──────────────────────────────────────────────\n\n private async request<T>(method: string, endpoint: string, body?: unknown): Promise<T> {\n const { body: parsed } = await this.requestWithStatus<T>(method, endpoint, body);\n return parsed;\n }\n\n /**\n * Variant of {@link request} that also returns the HTTP status code, so\n * callers can branch on 201 vs 202 (or other success codes) without losing\n * type information about the response body.\n */\n private async requestWithStatus<T>(\n method: string,\n endpoint: string,\n body?: unknown\n ): Promise<{ status: number; body: T }> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Set auth header\n const token = await this.getAuthToken();\n headers['Authorization'] = `Bearer ${token}`;\n\n // Sign request if private key is configured\n if (this.privateKey) {\n const signature = await this.signRequest(method, endpoint, body || {});\n headers['X-AstraSync-Signature'] = signature;\n }\n\n const res = await fetch(url, {\n method,\n headers,\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n\n if (!res.ok) {\n const errorBody = (await res\n .json()\n .catch(() => ({ error: res.statusText }))) as ApiErrorResponse;\n\n // Handle KYD_REQUIRED specifically\n if (res.status === 403 && errorBody.code === 'KYD_REQUIRED') {\n throw new KYDRequiredError(errorBody);\n }\n\n throw new AstraSyncError(\n errorBody.error || `Request failed: ${res.status}`,\n res.status,\n errorBody.code\n );\n }\n\n return { status: res.status, body: (await res.json()) as T };\n }\n\n private async getAuthToken(): Promise<string> {\n // API key auth — use directly\n if (this.apiKey) {\n return this.apiKey;\n }\n\n // Email+password — login and cache JWT\n if (this.cachedJwt && this.jwtExpiresAt && Date.now() < this.jwtExpiresAt) {\n return this.cachedJwt;\n }\n\n const res = await fetch(`${this.baseUrl}/api/auth/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: this.email, password: this.password }),\n });\n\n if (!res.ok) {\n const errorBody = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n throw new AuthenticationError(\n (errorBody.message as string) || (errorBody.error as string) || 'Login failed'\n );\n }\n\n const data = (await res.json()) as { data: { token: string } };\n this.cachedJwt = data.data.token;\n // Cache for 6 days (tokens expire in 7)\n this.jwtExpiresAt = Date.now() + 6 * 24 * 60 * 60 * 1000;\n\n return this.cachedJwt;\n }\n\n /**\n * Sign a request using secp256k1 (ethers.js).\n * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY\n * Must match apps/backend/src/services/signature-verify.service.ts exactly.\n */\n private async signRequest(method: string, endpoint: string, body: unknown): Promise<string> {\n const { Wallet } = await import('ethers');\n const sorted = this.sortObjectKeys(body);\n const canonical = `${method}:${endpoint}:${JSON.stringify(sorted)}`;\n const wallet = new Wallet(this.privateKey!);\n return wallet.signMessage(canonical);\n }\n\n /** Recursively sort object keys for canonical JSON representation. */\n private sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortObjectKeys(item));\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n}\n"],"mappings":";AAGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,YAAoB,MAAe;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,mBAAN,cAA+B,eAAe;AAAA,EAInD,YAAY,UAA4B;AACtC,UAAM,SAAS,SAAS,UAAU;AAClC;AAAA,MACE;AAAA,gCAAuF,MAAM;AAAA,MAC7F;AAAA,MACA;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,gBAAgB,SAAS,iBAAiB;AAAA,EACjD;AACF;AAGO,IAAM,sBAAN,cAAkC,eAAe;AAAA,EACtD,YAAY,SAAiB;AAC3B,UAAM,SAAS,KAAK,aAAa;AACjC,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,0BAAN,cAAsC,eAAe;AAAA,EAI1D,YAAY,WAAmB,QAAiB;AAC9C;AAAA,MACE,wBAAwB,SAAS,oCAAoC,SAAS,YAAY,MAAM,KAAK,EAAE;AAAA,MACvG;AAAA,MACA;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,SAAS;AAAA,EAChB;AACF;AAMO,IAAM,2BAAN,cAAuC,eAAe;AAAA,EAG3D,YAAY,WAAmB;AAC7B;AAAA,MACE,wBAAwB,SAAS;AAAA,MACjC;AAAA,MACA;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,YAAY;AAAA,EACnB;AACF;AAQO,IAAM,2BAAN,cAAuC,eAAe;AAAA,EAG3D,YAAY,WAAmB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I,CAAC;AAAA,IACpD;AACA,UAAM,SAAkC,CAAC;AACzC,eAAW,OAAO,OAAO,KAAK,GAAG,EAAE,KAAK,GAAG;AACzC,aAAO,GAAG,IAAI,KAAK,eAAgB,IAAgC,GAAG,CAAC;AAAA,IACzE;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/registration/errors.ts","../../src/registration/api.ts"],"sourcesContent":["import type { ApiErrorResponse } from './types';\n\n/** Base error class for AstraSync SDK errors. */\nexport class AstraSyncError extends Error {\n public readonly code?: string;\n public readonly statusCode: number;\n\n constructor(message: string, statusCode: number, code?: string) {\n super(message);\n this.name = 'AstraSyncError';\n this.statusCode = statusCode;\n this.code = code;\n }\n}\n\n/** Thrown when KYD verification is required before agent registration. */\nexport class KYDRequiredError extends AstraSyncError {\n public readonly kydUrl: string;\n public readonly ownerNotified: boolean;\n\n constructor(response: ApiErrorResponse) {\n const kydUrl = response.kydUrl || 'https://astrasync.ai/developer-profile';\n super(\n `KYD verification required before registering agents.\\nComplete your KYD profile at: ${kydUrl}`,\n 403,\n 'KYD_REQUIRED'\n );\n this.name = 'KYDRequiredError';\n this.kydUrl = kydUrl;\n this.ownerNotified = response.ownerNotified || false;\n }\n}\n\n/** Thrown when authentication fails. */\nexport class AuthenticationError extends AstraSyncError {\n constructor(message: string) {\n super(message, 401, 'AUTH_FAILED');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the owner denies the\n * pending registration request. The `reason` field, when present, mirrors the\n * deny note the owner left in the dashboard.\n */\nexport class RegistrationDeniedError extends AstraSyncError {\n public readonly requestId: string;\n public readonly reason?: string;\n\n constructor(requestId: string, reason?: string) {\n super(\n `Registration request ${requestId} was denied by the account owner.${reason ? ` Reason: ${reason}` : ''}`,\n 403,\n 'REGISTRATION_DENIED'\n );\n this.name = 'RegistrationDeniedError';\n this.requestId = requestId;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the pending request\n * passes its 14-day TTL with no owner decision. The agent must re-submit.\n */\nexport class RegistrationExpiredError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Registration request ${requestId} expired before the owner approved it. Submit a new registration request.`,\n 410,\n 'REGISTRATION_EXPIRED'\n );\n this.name = 'RegistrationExpiredError';\n this.requestId = requestId;\n }\n}\n\n/**\n * Thrown by `register({ waitForApproval: true })` when the caller's local\n * `timeoutMs` elapses before the owner makes a decision. The request is still\n * live server-side — poll `pollRegistration(requestId)` to resume waiting, or\n * call `waitForApproval` again with a longer timeout.\n */\nexport class RegistrationTimeoutError extends AstraSyncError {\n public readonly requestId: string;\n\n constructor(requestId: string) {\n super(\n `Timed out waiting for owner approval of registration request ${requestId}. The request is still active server-side; poll the request to resume waiting.`,\n 408,\n 'REGISTRATION_TIMEOUT'\n );\n this.name = 'RegistrationTimeoutError';\n this.requestId = requestId;\n }\n}\n","import type {\n AstraSyncConfig,\n RegisterOptions,\n RegisterResult,\n WaitForApprovalOptions,\n PendingRegistrationResponse,\n PollRegistrationResult,\n RegistrationResponse,\n VerifyResponse,\n HealthResponse,\n ApiErrorResponse,\n AgentRecord,\n} from './types';\nimport {\n AstraSyncError,\n KYDRequiredError,\n AuthenticationError,\n RegistrationDeniedError,\n RegistrationExpiredError,\n RegistrationTimeoutError,\n} from './errors';\n\nconst DEFAULT_BASE_URL = 'https://astrasync.ai';\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * AstraSync SDK client for registering and managing AI agents.\n *\n * @example\n * ```typescript\n * const client = new AstraSync({ apiKey: 'kya_your_api_key' });\n * const result = await client.register({\n * name: 'My Agent',\n * model: { modelName: 'gpt-4o', modelProvider: 'openai', modelType: 'llm' },\n * });\n * ```\n *\n * For staging, pass `baseUrl: 'https://staging.astrasync.ai'`.\n */\nexport class AstraSync {\n private readonly baseUrl: string;\n private readonly apiKey?: string;\n private readonly email?: string;\n private readonly password?: string;\n private readonly privateKey?: string;\n private cachedJwt?: string;\n private jwtExpiresAt?: number;\n\n constructor(config: AstraSyncConfig = {}) {\n let raw = (config.baseUrl || process.env.ASTRASYNC_API_URL || DEFAULT_BASE_URL).replace(\n /\\/+$/,\n ''\n );\n // Round-10 (O2): tolerate the verify-side convention. `GatewayConfig.apiBaseUrl`\n // is documented as `https://astrasync.ai/api` (with /api), but\n // `AstraSyncConfig.baseUrl` is documented as the bare origin. Partners\n // passing the verify-style URL to the registration client hit a 404\n // because we'd then append `/api/agents/register` → double /api. Strip\n // a trailing `/api` and warn once so the partner can fix the source.\n if (raw.toLowerCase().endsWith('/api')) {\n raw = raw.slice(0, -'/api'.length);\n if (config.baseUrl && !config.silent) {\n // eslint-disable-next-line no-console\n console.warn(\n `[AstraSync] baseUrl '${config.baseUrl}' had a trailing /api — stripped to '${raw}'. ` +\n `Pass the bare origin (e.g. 'https://astrasync.ai' or 'https://staging.astrasync.ai') ` +\n `to AstraSync(). The /api suffix is the verify-gateway (GatewayConfig.apiBaseUrl) convention.`\n );\n }\n }\n this.baseUrl = raw;\n\n this.apiKey = config.apiKey || process.env.ASTRASYNC_API_KEY;\n this.email = config.email;\n this.password = config.password;\n this.privateKey = config.privateKey;\n\n if (!this.apiKey && !this.email) {\n throw new AuthenticationError(\n 'Authentication required. Provide apiKey, or email+password. ' +\n 'Set ASTRASYNC_API_KEY env var or pass config to constructor.'\n );\n }\n\n if (this.email && !this.password) {\n throw new AuthenticationError('Password is required when using email authentication.');\n }\n }\n\n /**\n * Register a new AI agent on the AstraSync KYA Platform.\n *\n * The backend response depends on auth context:\n * - **Crypto-keypair signed** (`privateKey` configured): synchronous 201,\n * returns `{ status: 'active', agent }`.\n * - **API-key only** (no signature): 202 pending, returns\n * `{ status: 'pending_approval', requestId, pollUrl, expiresAt }`. The\n * owner is notified by email and a dashboard alert is emitted; the agent\n * becomes active only after the owner approves.\n *\n * Blocking mode: pass `{ waitForApproval: true }` to have the SDK poll the\n * request until it resolves, then return the live agent record. The promise\n * rejects with `RegistrationDeniedError`, `RegistrationExpiredError`, or\n * `RegistrationTimeoutError` on the corresponding terminal states.\n *\n * @example Non-blocking (default — best for serverless / scheduled agents):\n * ```typescript\n * const result = await sdk.register({ name, pdlss });\n * if (result.status === 'pending_approval') {\n * storeRequestId(result.requestId);\n * return; // function exits; resume later via pollRegistration()\n * }\n * ```\n *\n * @example Blocking (best for long-running services + CLI):\n * ```typescript\n * const agent = await sdk.register({\n * name, pdlss, waitForApproval: true, timeoutMs: 600_000,\n * onPending: ({ ageMs }) => console.log(`waiting ${ageMs}ms`),\n * });\n * ```\n */\n async register(\n options: RegisterOptions & WaitForApprovalOptions\n ): Promise<RegisterResult | AgentRecord> {\n const body: Record<string, unknown> = {\n name: options.name,\n ...(options.description && { description: options.description }),\n ...(options.agentType && { agentType: options.agentType }),\n ...(options.apiEndpoint && { apiEndpoint: options.apiEndpoint }),\n ...(options.model && { model: options.model }),\n ...(options.framework && { framework: options.framework }),\n ...(options.protocols && { protocols: options.protocols }),\n ...(options.metadata && { metadata: options.metadata }),\n ...(options.pdlss && { pdlss: options.pdlss }),\n };\n\n const { status, body: raw } = await this.requestWithStatus<\n RegistrationResponse | PendingRegistrationResponse\n >('POST', '/api/agents/register', body);\n\n if (status === 201) {\n const activeBody = raw as RegistrationResponse;\n const active: RegisterResult = {\n status: 'active',\n agent: activeBody.data.agent,\n // Round-12 (F16): pass backend advisories through verbatim.\n // Pre-fix the SDK whitelisted five fields and silently dropped\n // `warnings`, which left partners with no signal that\n // `no_callback_endpoint` (or future advisories) had fired.\n ...(activeBody.warnings && { warnings: activeBody.warnings }),\n };\n return active;\n }\n\n // 202 Accepted — owner approval required.\n const pendingBody = raw as PendingRegistrationResponse;\n const pending: RegisterResult = {\n status: 'pending_approval',\n requestId: pendingBody.requestId,\n expiresAt: pendingBody.expiresAt,\n pollUrl: pendingBody.pollUrl,\n message: pendingBody.message,\n // Round-12 (F16): same pass-through on the pending path.\n ...(pendingBody.warnings && { warnings: pendingBody.warnings }),\n };\n\n if (!options.waitForApproval) return pending;\n\n return this.waitForApproval(pendingBody.requestId, options);\n }\n\n /**\n * Poll the current state of a pending-approval registration request.\n *\n * Useful for caller-driven polling when `waitForApproval: false` (the\n * default). The endpoint is unauthenticated — pass the `requestId` that\n * was returned from the 202 response.\n *\n * @returns `state: 'pending'` while awaiting; `'approved'` carries the\n * minted agent in `agent`; `'denied'` may carry the owner's\n * `reason`; `'expired'` is terminal after 14 days.\n */\n async pollRegistration(requestId: string): Promise<PollRegistrationResult> {\n const url = `${this.baseUrl}/api/agents/request-registration/${requestId}`;\n const res = await fetch(url, { headers: { Accept: 'application/json' } });\n if (!res.ok) {\n const errBody = (await res.json().catch(() => ({}))) as ApiErrorResponse;\n throw new AstraSyncError(\n errBody.error || `pollRegistration failed: ${res.status}`,\n res.status,\n errBody.code\n );\n }\n return (await res.json()) as PollRegistrationResult;\n }\n\n /**\n * Block until a pending registration request resolves to a terminal state.\n * Resolves to the live `AgentRecord` on approval; rejects with the matching\n * Registration*Error on deny/expire/timeout. Usually called via\n * `register({ waitForApproval: true })`, but exposed for callers that want\n * to fire-and-forget the initial register call and resume waiting later\n * (e.g. after restoring a stored `requestId` on cold start).\n */\n async waitForApproval(\n requestId: string,\n options: WaitForApprovalOptions = {}\n ): Promise<AgentRecord> {\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n const pollIntervalMs = options.pollIntervalMs ?? 5_000;\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n while (Date.now() < deadline) {\n const result = await this.pollRegistration(requestId);\n const ageMs = Date.now() - start;\n options.onPending?.({ requestId, ageMs });\n\n if (result.state === 'approved') {\n if (!result.agent) {\n throw new AstraSyncError(\n `Registration ${requestId} reported approved but no agent payload returned.`,\n 500\n );\n }\n return result.agent;\n }\n if (result.state === 'denied') {\n throw new RegistrationDeniedError(requestId, result.reason);\n }\n if (result.state === 'expired') {\n throw new RegistrationExpiredError(requestId);\n }\n await sleep(pollIntervalMs);\n }\n throw new RegistrationTimeoutError(requestId);\n }\n\n /**\n * Look up an agent's public profile by ASTRA ID or UUID.\n */\n async verify(agentId: string): Promise<VerifyResponse> {\n return this.request<VerifyResponse>('GET', `/api/agents/verify/${agentId}`);\n }\n\n /**\n * Check API health.\n */\n async health(): Promise<HealthResponse> {\n const res = await fetch(`${this.baseUrl}/api/health/`);\n if (!res.ok) {\n throw new AstraSyncError(`Health check failed: ${res.status}`, res.status);\n }\n return res.json() as Promise<HealthResponse>;\n }\n\n // ── Private helpers ──────────────────────────────────────────────\n\n private async request<T>(method: string, endpoint: string, body?: unknown): Promise<T> {\n const { body: parsed } = await this.requestWithStatus<T>(method, endpoint, body);\n return parsed;\n }\n\n /**\n * Variant of {@link request} that also returns the HTTP status code, so\n * callers can branch on 201 vs 202 (or other success codes) without losing\n * type information about the response body.\n */\n private async requestWithStatus<T>(\n method: string,\n endpoint: string,\n body?: unknown\n ): Promise<{ status: number; body: T }> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Set auth header\n const token = await this.getAuthToken();\n headers['Authorization'] = `Bearer ${token}`;\n\n // Sign request if private key is configured\n if (this.privateKey) {\n const signature = await this.signRequest(method, endpoint, body || {});\n headers['X-AstraSync-Signature'] = signature;\n }\n\n const res = await fetch(url, {\n method,\n headers,\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n\n if (!res.ok) {\n const errorBody = (await res\n .json()\n .catch(() => ({ error: res.statusText }))) as ApiErrorResponse;\n\n // Handle KYD_REQUIRED specifically\n if (res.status === 403 && errorBody.code === 'KYD_REQUIRED') {\n throw new KYDRequiredError(errorBody);\n }\n\n throw new AstraSyncError(\n errorBody.error || `Request failed: ${res.status}`,\n res.status,\n errorBody.code\n );\n }\n\n return { status: res.status, body: (await res.json()) as T };\n }\n\n private async getAuthToken(): Promise<string> {\n // API key auth — use directly\n if (this.apiKey) {\n return this.apiKey;\n }\n\n // Email+password — login and cache JWT\n if (this.cachedJwt && this.jwtExpiresAt && Date.now() < this.jwtExpiresAt) {\n return this.cachedJwt;\n }\n\n const res = await fetch(`${this.baseUrl}/api/auth/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: this.email, password: this.password }),\n });\n\n if (!res.ok) {\n const errorBody = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n throw new AuthenticationError(\n (errorBody.message as string) || (errorBody.error as string) || 'Login failed'\n );\n }\n\n const data = (await res.json()) as { data: { token: string } };\n this.cachedJwt = data.data.token;\n // Cache for 6 days (tokens expire in 7)\n this.jwtExpiresAt = Date.now() + 6 * 24 * 60 * 60 * 1000;\n\n return this.cachedJwt;\n }\n\n /**\n * Sign a request using secp256k1 (ethers.js).\n * Canonical message format: METHOD:ENDPOINT:SORTED_JSON_BODY\n * Must match apps/backend/src/services/signature-verify.service.ts exactly.\n */\n private async signRequest(method: string, endpoint: string, body: unknown): Promise<string> {\n const { Wallet } = await import('ethers');\n const sorted = this.sortObjectKeys(body);\n const canonical = `${method}:${endpoint}:${JSON.stringify(sorted)}`;\n const wallet = new Wallet(this.privateKey!);\n return wallet.signMessage(canonical);\n }\n\n /** Recursively sort object keys for canonical JSON representation. */\n private sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.sortObjectKeys(item));\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = this.sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n}\n"],"mappings":";AAGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,YAAoB,MAAe;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,mBAAN,cAA+B,eAAe;AAAA,EAInD,YAAY,UAA4B;AACtC,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
1
|
+
import { a as AccessLevel, i as TrustLevel, S as SDKOptions, V as VerificationResult } from './types-CVT-sorC.mjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* AstraSync Universal Verification Gateway - Access Level Definitions
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AccessLevel, i as TrustLevel, S as SDKOptions, V as VerificationResult } from './types-
|
|
1
|
+
import { a as AccessLevel, i as TrustLevel, S as SDKOptions, V as VerificationResult } from './types-CVT-sorC.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* AstraSync Universal Verification Gateway - Access Level Definitions
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import '../types-
|
|
2
|
-
export { A as ACPEndpoint, a as ACPPaymentTokenType, b as ACPRequestContext, c as ACPRequestLike, d as ACPSignatureAlgorithm, e as ACPTotal, f as ACPVerifyInput, g as ACPVerifyResult, h as AP2CartMandateClaims, j as AP2ChainResult, k as AP2IntentMandateClaims, l as AP2MandateClaims, m as AP2MandateTriple, n as AP2MandateTripleInput, o as AP2MandateType, p as AP2PaymentDetailsTotal, q as AP2PaymentMandateClaims, r as AP2PaymentMandateForValue, s as AP2VerifyInput, C as CommerceContext, t as CommercePipelineInput, u as CommerceProtocol, v as CommercePurpose, w as CommerceSignatureStack, x as ConstraintEvalResult, y as ConstraintKey, z as ConstraintResult, E as ExtractorRequestLike, I as IdentityBindingResult, B as IdentityClaim, D as IdentityResolver, M as MPPChallengeForValue, F as MPPChallengeSummary, G as MPPCredentialSummary, H as MPPIntent, J as MPPKind, K as MPPReceiptSummary, L as MPPRequestContext, N as MPPRequestLike, O as MPPResponseLike, P as MPPVerifyInput, Q as MPPVerifyResult, R as ParsedRFC9421, S as PaymentMethodAllowlistInput, T as RFC9421SignatureParams, U as RFC9421Tag, V as RFC9421VerifyOptions, W as RFC9421VerifyRequest, X as RFC9421VerifyResult, Y as RegistryName, Z as RegistryResolver, _ as ResolveContext, $ as STRIPE_WEBHOOK_INFORMATIONAL_EVENTS, a0 as SpendingLimitInput, a1 as StripeWebhookInformationalEvent, a2 as TransactionContext, a3 as TransactionValueContext, a4 as TransportExtractor, a5 as UCPCheckoutContext, a6 as UCPManifestValidationResult, a7 as UCPRequestLike, a8 as UCPTotal, a9 as VIAllowedParty, aa as VIBudgetLimit, ab as VIClaimsForValue, ac as VIConstraintEvalInput, ad as VIConstraints, ae as VIExecutionMode, af as VIExtractedClaims, ag as VILayer, ah as VILineItem, ai as VIMandateType, aj as VIPaymentAmount, ak as VIRecurrence, al as VIVerifyInput, am as VIVerifyResult, an as VerifyStripeWebhookOptions, ao as VerifyStripeWebhookResult, ap as X402Kind, aq as X402RequestContext, ar as X402RequestForValue, as as X402RequestLike, at as X402RequirementsSummary, au as X402ResponseLike, av as applyCredentials, aw as bindIdentity, ax as claim, ay as clearTransportExtractors, az as createMastercardRegistry, aA as createVisaRegistry, aB as createWebBotAuthRegistry, aC as detectProtocol, aD as evaluatePaymentMethodAllowlist, aE as evaluateSpendingLimit, aF as evaluateVIConstraints, aG as extractA2ACredentials, aH as extractACPContext, aI as extractACPTransactionValue, aJ as extractAP2Mandate, aK as extractAP2Mandates, aL as extractAP2TransactionValue, aM as extractCredentialsFromProtocol, aN as extractHttpCredentials, aO as extractMPPContext, aP as extractMPPFromRequest, aQ as extractMPPFromResponse, aR as extractMPPTransactionValue, aS as extractMcpCredentials, aT as extractUCPContext, aU as extractUCPTransactionValue, aV as extractVIClaims, aW as extractVITransactionValue, aX as extractX402Context, aY as extractX402FromRequest, aZ as extractX402FromResponse, a_ as extractX402TransactionValue, a$ as fetchUCPManifest, b0 as getTransportExtractor, b1 as getTransportExtractors, b2 as isStripeWebhookInformational, b3 as mapACPRequestToPurpose, b4 as mapAP2MandateToPurpose, b5 as mapMPPRequestToPurpose, b6 as mapRFC9421TagToPurpose, b7 as mapUCPRequestToPurpose, b8 as mapVIMandateToPurpose, b9 as mapX402RequestToPurpose, ba as parseRFC9421, bb as registerTransportExtractor, bc as runCommercePipeline, bd as runMatchingExtractors, be as setA2AMetadata, bf as setHttpHeaders, bg as setMcpMeta, bh as validateUCPManifest, bi as verifyACPSignature, bj as verifyAP2Chain, bk as verifyMPP, bl as verifyRFC9421, bm as verifyStripeWebhook, bn as verifyVIChain } from '../index-
|
|
1
|
+
import '../types-CVT-sorC.mjs';
|
|
2
|
+
export { A as ACPEndpoint, a as ACPPaymentTokenType, b as ACPRequestContext, c as ACPRequestLike, d as ACPSignatureAlgorithm, e as ACPTotal, f as ACPVerifyInput, g as ACPVerifyResult, h as AP2CartMandateClaims, j as AP2ChainResult, k as AP2IntentMandateClaims, l as AP2MandateClaims, m as AP2MandateTriple, n as AP2MandateTripleInput, o as AP2MandateType, p as AP2PaymentDetailsTotal, q as AP2PaymentMandateClaims, r as AP2PaymentMandateForValue, s as AP2VerifyInput, C as CommerceContext, t as CommercePipelineInput, u as CommerceProtocol, v as CommercePurpose, w as CommerceSignatureStack, x as ConstraintEvalResult, y as ConstraintKey, z as ConstraintResult, E as ExtractorRequestLike, I as IdentityBindingResult, B as IdentityClaim, D as IdentityResolver, M as MPPChallengeForValue, F as MPPChallengeSummary, G as MPPCredentialSummary, H as MPPIntent, J as MPPKind, K as MPPReceiptSummary, L as MPPRequestContext, N as MPPRequestLike, O as MPPResponseLike, P as MPPVerifyInput, Q as MPPVerifyResult, R as ParsedRFC9421, S as PaymentMethodAllowlistInput, T as RFC9421SignatureParams, U as RFC9421Tag, V as RFC9421VerifyOptions, W as RFC9421VerifyRequest, X as RFC9421VerifyResult, Y as RegistryName, Z as RegistryResolver, _ as ResolveContext, $ as STRIPE_WEBHOOK_INFORMATIONAL_EVENTS, a0 as SpendingLimitInput, a1 as StripeWebhookInformationalEvent, a2 as TransactionContext, a3 as TransactionValueContext, a4 as TransportExtractor, a5 as UCPCheckoutContext, a6 as UCPManifestValidationResult, a7 as UCPRequestLike, a8 as UCPTotal, a9 as VIAllowedParty, aa as VIBudgetLimit, ab as VIClaimsForValue, ac as VIConstraintEvalInput, ad as VIConstraints, ae as VIExecutionMode, af as VIExtractedClaims, ag as VILayer, ah as VILineItem, ai as VIMandateType, aj as VIPaymentAmount, ak as VIRecurrence, al as VIVerifyInput, am as VIVerifyResult, an as VerifyStripeWebhookOptions, ao as VerifyStripeWebhookResult, ap as X402Kind, aq as X402RequestContext, ar as X402RequestForValue, as as X402RequestLike, at as X402RequirementsSummary, au as X402ResponseLike, av as applyCredentials, aw as bindIdentity, ax as claim, ay as clearTransportExtractors, az as createMastercardRegistry, aA as createVisaRegistry, aB as createWebBotAuthRegistry, aC as detectProtocol, aD as evaluatePaymentMethodAllowlist, aE as evaluateSpendingLimit, aF as evaluateVIConstraints, aG as extractA2ACredentials, aH as extractACPContext, aI as extractACPTransactionValue, aJ as extractAP2Mandate, aK as extractAP2Mandates, aL as extractAP2TransactionValue, aM as extractCredentialsFromProtocol, aN as extractHttpCredentials, aO as extractMPPContext, aP as extractMPPFromRequest, aQ as extractMPPFromResponse, aR as extractMPPTransactionValue, aS as extractMcpCredentials, aT as extractUCPContext, aU as extractUCPTransactionValue, aV as extractVIClaims, aW as extractVITransactionValue, aX as extractX402Context, aY as extractX402FromRequest, aZ as extractX402FromResponse, a_ as extractX402TransactionValue, a$ as fetchUCPManifest, b0 as getTransportExtractor, b1 as getTransportExtractors, b2 as isStripeWebhookInformational, b3 as mapACPRequestToPurpose, b4 as mapAP2MandateToPurpose, b5 as mapMPPRequestToPurpose, b6 as mapRFC9421TagToPurpose, b7 as mapUCPRequestToPurpose, b8 as mapVIMandateToPurpose, b9 as mapX402RequestToPurpose, ba as parseRFC9421, bb as registerTransportExtractor, bc as runCommercePipeline, bd as runMatchingExtractors, be as setA2AMetadata, bf as setHttpHeaders, bg as setMcpMeta, bh as validateUCPManifest, bi as verifyACPSignature, bj as verifyAP2Chain, bk as verifyMPP, bl as verifyRFC9421, bm as verifyStripeWebhook, bn as verifyVIChain } from '../index-D698fDOk.mjs';
|
|
3
3
|
import 'jose';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import '../types-
|
|
2
|
-
export { A as ACPEndpoint, a as ACPPaymentTokenType, b as ACPRequestContext, c as ACPRequestLike, d as ACPSignatureAlgorithm, e as ACPTotal, f as ACPVerifyInput, g as ACPVerifyResult, h as AP2CartMandateClaims, j as AP2ChainResult, k as AP2IntentMandateClaims, l as AP2MandateClaims, m as AP2MandateTriple, n as AP2MandateTripleInput, o as AP2MandateType, p as AP2PaymentDetailsTotal, q as AP2PaymentMandateClaims, r as AP2PaymentMandateForValue, s as AP2VerifyInput, C as CommerceContext, t as CommercePipelineInput, u as CommerceProtocol, v as CommercePurpose, w as CommerceSignatureStack, x as ConstraintEvalResult, y as ConstraintKey, z as ConstraintResult, E as ExtractorRequestLike, I as IdentityBindingResult, B as IdentityClaim, D as IdentityResolver, M as MPPChallengeForValue, F as MPPChallengeSummary, G as MPPCredentialSummary, H as MPPIntent, J as MPPKind, K as MPPReceiptSummary, L as MPPRequestContext, N as MPPRequestLike, O as MPPResponseLike, P as MPPVerifyInput, Q as MPPVerifyResult, R as ParsedRFC9421, S as PaymentMethodAllowlistInput, T as RFC9421SignatureParams, U as RFC9421Tag, V as RFC9421VerifyOptions, W as RFC9421VerifyRequest, X as RFC9421VerifyResult, Y as RegistryName, Z as RegistryResolver, _ as ResolveContext, $ as STRIPE_WEBHOOK_INFORMATIONAL_EVENTS, a0 as SpendingLimitInput, a1 as StripeWebhookInformationalEvent, a2 as TransactionContext, a3 as TransactionValueContext, a4 as TransportExtractor, a5 as UCPCheckoutContext, a6 as UCPManifestValidationResult, a7 as UCPRequestLike, a8 as UCPTotal, a9 as VIAllowedParty, aa as VIBudgetLimit, ab as VIClaimsForValue, ac as VIConstraintEvalInput, ad as VIConstraints, ae as VIExecutionMode, af as VIExtractedClaims, ag as VILayer, ah as VILineItem, ai as VIMandateType, aj as VIPaymentAmount, ak as VIRecurrence, al as VIVerifyInput, am as VIVerifyResult, an as VerifyStripeWebhookOptions, ao as VerifyStripeWebhookResult, ap as X402Kind, aq as X402RequestContext, ar as X402RequestForValue, as as X402RequestLike, at as X402RequirementsSummary, au as X402ResponseLike, av as applyCredentials, aw as bindIdentity, ax as claim, ay as clearTransportExtractors, az as createMastercardRegistry, aA as createVisaRegistry, aB as createWebBotAuthRegistry, aC as detectProtocol, aD as evaluatePaymentMethodAllowlist, aE as evaluateSpendingLimit, aF as evaluateVIConstraints, aG as extractA2ACredentials, aH as extractACPContext, aI as extractACPTransactionValue, aJ as extractAP2Mandate, aK as extractAP2Mandates, aL as extractAP2TransactionValue, aM as extractCredentialsFromProtocol, aN as extractHttpCredentials, aO as extractMPPContext, aP as extractMPPFromRequest, aQ as extractMPPFromResponse, aR as extractMPPTransactionValue, aS as extractMcpCredentials, aT as extractUCPContext, aU as extractUCPTransactionValue, aV as extractVIClaims, aW as extractVITransactionValue, aX as extractX402Context, aY as extractX402FromRequest, aZ as extractX402FromResponse, a_ as extractX402TransactionValue, a$ as fetchUCPManifest, b0 as getTransportExtractor, b1 as getTransportExtractors, b2 as isStripeWebhookInformational, b3 as mapACPRequestToPurpose, b4 as mapAP2MandateToPurpose, b5 as mapMPPRequestToPurpose, b6 as mapRFC9421TagToPurpose, b7 as mapUCPRequestToPurpose, b8 as mapVIMandateToPurpose, b9 as mapX402RequestToPurpose, ba as parseRFC9421, bb as registerTransportExtractor, bc as runCommercePipeline, bd as runMatchingExtractors, be as setA2AMetadata, bf as setHttpHeaders, bg as setMcpMeta, bh as validateUCPManifest, bi as verifyACPSignature, bj as verifyAP2Chain, bk as verifyMPP, bl as verifyRFC9421, bm as verifyStripeWebhook, bn as verifyVIChain } from '../index-
|
|
1
|
+
import '../types-CVT-sorC.js';
|
|
2
|
+
export { A as ACPEndpoint, a as ACPPaymentTokenType, b as ACPRequestContext, c as ACPRequestLike, d as ACPSignatureAlgorithm, e as ACPTotal, f as ACPVerifyInput, g as ACPVerifyResult, h as AP2CartMandateClaims, j as AP2ChainResult, k as AP2IntentMandateClaims, l as AP2MandateClaims, m as AP2MandateTriple, n as AP2MandateTripleInput, o as AP2MandateType, p as AP2PaymentDetailsTotal, q as AP2PaymentMandateClaims, r as AP2PaymentMandateForValue, s as AP2VerifyInput, C as CommerceContext, t as CommercePipelineInput, u as CommerceProtocol, v as CommercePurpose, w as CommerceSignatureStack, x as ConstraintEvalResult, y as ConstraintKey, z as ConstraintResult, E as ExtractorRequestLike, I as IdentityBindingResult, B as IdentityClaim, D as IdentityResolver, M as MPPChallengeForValue, F as MPPChallengeSummary, G as MPPCredentialSummary, H as MPPIntent, J as MPPKind, K as MPPReceiptSummary, L as MPPRequestContext, N as MPPRequestLike, O as MPPResponseLike, P as MPPVerifyInput, Q as MPPVerifyResult, R as ParsedRFC9421, S as PaymentMethodAllowlistInput, T as RFC9421SignatureParams, U as RFC9421Tag, V as RFC9421VerifyOptions, W as RFC9421VerifyRequest, X as RFC9421VerifyResult, Y as RegistryName, Z as RegistryResolver, _ as ResolveContext, $ as STRIPE_WEBHOOK_INFORMATIONAL_EVENTS, a0 as SpendingLimitInput, a1 as StripeWebhookInformationalEvent, a2 as TransactionContext, a3 as TransactionValueContext, a4 as TransportExtractor, a5 as UCPCheckoutContext, a6 as UCPManifestValidationResult, a7 as UCPRequestLike, a8 as UCPTotal, a9 as VIAllowedParty, aa as VIBudgetLimit, ab as VIClaimsForValue, ac as VIConstraintEvalInput, ad as VIConstraints, ae as VIExecutionMode, af as VIExtractedClaims, ag as VILayer, ah as VILineItem, ai as VIMandateType, aj as VIPaymentAmount, ak as VIRecurrence, al as VIVerifyInput, am as VIVerifyResult, an as VerifyStripeWebhookOptions, ao as VerifyStripeWebhookResult, ap as X402Kind, aq as X402RequestContext, ar as X402RequestForValue, as as X402RequestLike, at as X402RequirementsSummary, au as X402ResponseLike, av as applyCredentials, aw as bindIdentity, ax as claim, ay as clearTransportExtractors, az as createMastercardRegistry, aA as createVisaRegistry, aB as createWebBotAuthRegistry, aC as detectProtocol, aD as evaluatePaymentMethodAllowlist, aE as evaluateSpendingLimit, aF as evaluateVIConstraints, aG as extractA2ACredentials, aH as extractACPContext, aI as extractACPTransactionValue, aJ as extractAP2Mandate, aK as extractAP2Mandates, aL as extractAP2TransactionValue, aM as extractCredentialsFromProtocol, aN as extractHttpCredentials, aO as extractMPPContext, aP as extractMPPFromRequest, aQ as extractMPPFromResponse, aR as extractMPPTransactionValue, aS as extractMcpCredentials, aT as extractUCPContext, aU as extractUCPTransactionValue, aV as extractVIClaims, aW as extractVITransactionValue, aX as extractX402Context, aY as extractX402FromRequest, aZ as extractX402FromResponse, a_ as extractX402TransactionValue, a$ as fetchUCPManifest, b0 as getTransportExtractor, b1 as getTransportExtractors, b2 as isStripeWebhookInformational, b3 as mapACPRequestToPurpose, b4 as mapAP2MandateToPurpose, b5 as mapMPPRequestToPurpose, b6 as mapRFC9421TagToPurpose, b7 as mapUCPRequestToPurpose, b8 as mapVIMandateToPurpose, b9 as mapX402RequestToPurpose, ba as parseRFC9421, bb as registerTransportExtractor, bc as runCommercePipeline, bd as runMatchingExtractors, be as setA2AMetadata, bf as setHttpHeaders, bg as setMcpMeta, bh as validateUCPManifest, bi as verifyACPSignature, bj as verifyAP2Chain, bk as verifyMPP, bl as verifyRFC9421, bm as verifyStripeWebhook, bn as verifyVIChain } from '../index-6Jus6yWU.js';
|
|
3
3
|
import 'jose';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AccessLevel, C as CounterpartyType, T as TokenGuidance } from './types-
|
|
1
|
+
import { a as AccessLevel, C as CounterpartyType, T as TokenGuidance } from './types-CVT-sorC.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* AstraSync Gateway - Types for gateway modes, local evaluation, and adapter interface.
|
|
@@ -401,6 +401,14 @@ interface VerificationRequest {
|
|
|
401
401
|
runtimeChallengeOptions?: {
|
|
402
402
|
timeoutOverride?: number;
|
|
403
403
|
};
|
|
404
|
+
/**
|
|
405
|
+
* Round-12 (F19): transport protocol marker. Set by the MCP middleware
|
|
406
|
+
* to `'mcp'`; non-MCP callers leave it unset (server treats as `'rest'`).
|
|
407
|
+
* Separates "how did the call arrive" from "what does the agent want"
|
|
408
|
+
* (`purpose`). Stored on platform_events.eventData for activity-feed
|
|
409
|
+
* visibility into transport-vs-intent.
|
|
410
|
+
*/
|
|
411
|
+
invocationProtocol?: 'rest' | 'mcp' | 'a2a' | 'acp' | 'ap2' | 'mpp' | 'ucp';
|
|
404
412
|
}
|
|
405
413
|
/**
|
|
406
414
|
* Route-specific access configuration
|
|
@@ -451,6 +459,21 @@ interface ExpressMiddlewareOptions extends GatewayConfig {
|
|
|
451
459
|
recordDecisions?: boolean;
|
|
452
460
|
/** Enable runtime challenge for all verify-access calls (default: true) */
|
|
453
461
|
enableRuntimeChallenge?: boolean;
|
|
462
|
+
/**
|
|
463
|
+
* Round-12 (F9): when true, the middleware calls verify-access for any
|
|
464
|
+
* request that presents AstraSync credentials, even on routes with
|
|
465
|
+
* `minAccessLevel: 'none'`. Populates `req.agentVerification` and
|
|
466
|
+
* records the verification event for the audit trail. Enforcement
|
|
467
|
+
* still respects route policy — a 'none' floor still grants regardless
|
|
468
|
+
* of access level. Default false to preserve existing behaviour.
|
|
469
|
+
*
|
|
470
|
+
* Use this when a single route serves both anonymous and verified
|
|
471
|
+
* traffic with different response shapes (e.g. anonymous catalog vs
|
|
472
|
+
* verified catalog with agent-only SKUs). Without the flag, anonymous
|
|
473
|
+
* passes are invisible to the merchant handler and to the AstraSync
|
|
474
|
+
* activity feed.
|
|
475
|
+
*/
|
|
476
|
+
evaluateAlwaysIfCredentialed?: boolean;
|
|
454
477
|
/**
|
|
455
478
|
* Refresh interval (ms) for the remote-fetched route policy. Default:
|
|
456
479
|
* 5 minutes. Operators can shorten this to test policy edits faster, or
|
|
@@ -401,6 +401,14 @@ interface VerificationRequest {
|
|
|
401
401
|
runtimeChallengeOptions?: {
|
|
402
402
|
timeoutOverride?: number;
|
|
403
403
|
};
|
|
404
|
+
/**
|
|
405
|
+
* Round-12 (F19): transport protocol marker. Set by the MCP middleware
|
|
406
|
+
* to `'mcp'`; non-MCP callers leave it unset (server treats as `'rest'`).
|
|
407
|
+
* Separates "how did the call arrive" from "what does the agent want"
|
|
408
|
+
* (`purpose`). Stored on platform_events.eventData for activity-feed
|
|
409
|
+
* visibility into transport-vs-intent.
|
|
410
|
+
*/
|
|
411
|
+
invocationProtocol?: 'rest' | 'mcp' | 'a2a' | 'acp' | 'ap2' | 'mpp' | 'ucp';
|
|
404
412
|
}
|
|
405
413
|
/**
|
|
406
414
|
* Route-specific access configuration
|
|
@@ -451,6 +459,21 @@ interface ExpressMiddlewareOptions extends GatewayConfig {
|
|
|
451
459
|
recordDecisions?: boolean;
|
|
452
460
|
/** Enable runtime challenge for all verify-access calls (default: true) */
|
|
453
461
|
enableRuntimeChallenge?: boolean;
|
|
462
|
+
/**
|
|
463
|
+
* Round-12 (F9): when true, the middleware calls verify-access for any
|
|
464
|
+
* request that presents AstraSync credentials, even on routes with
|
|
465
|
+
* `minAccessLevel: 'none'`. Populates `req.agentVerification` and
|
|
466
|
+
* records the verification event for the audit trail. Enforcement
|
|
467
|
+
* still respects route policy — a 'none' floor still grants regardless
|
|
468
|
+
* of access level. Default false to preserve existing behaviour.
|
|
469
|
+
*
|
|
470
|
+
* Use this when a single route serves both anonymous and verified
|
|
471
|
+
* traffic with different response shapes (e.g. anonymous catalog vs
|
|
472
|
+
* verified catalog with agent-only SKUs). Without the flag, anonymous
|
|
473
|
+
* passes are invisible to the merchant handler and to the AstraSync
|
|
474
|
+
* activity feed.
|
|
475
|
+
*/
|
|
476
|
+
evaluateAlwaysIfCredentialed?: boolean;
|
|
454
477
|
/**
|
|
455
478
|
* Refresh interval (ms) for the remote-fetched route policy. Default:
|
|
456
479
|
* 5 minutes. Operators can shorten this to test policy edits faster, or
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as AccessLevel, C as CounterpartyType, T as TokenGuidance } from './types-
|
|
1
|
+
import { a as AccessLevel, C as CounterpartyType, T as TokenGuidance } from './types-CVT-sorC.mjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* AstraSync Gateway - Types for gateway modes, local evaluation, and adapter interface.
|