@axiom-lattice/protocols 7.1.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiom-lattice/protocols",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "description": "Unified protocol type definitions for Axiom Lattice framework",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -0,0 +1,80 @@
1
+ /** Interactive login surface. Machine credentials are not part of this extension point. */
2
+ export type LoginSurface = "console";
3
+
4
+ /** One selectable sign-in method for a UI. */
5
+ export interface AuthProviderDescriptor {
6
+ id: string;
7
+ displayName: string;
8
+ interaction: "form" | "redirect" | "none";
9
+ surfaces: LoginSurface[];
10
+ /**
11
+ * True when the form provider is only an emergency local account and normal
12
+ * password sign-in is disabled. UIs should label it instead of treating it as
13
+ * the default sign-in method.
14
+ */
15
+ breakGlassOnly?: boolean;
16
+ }
17
+
18
+ /** Authenticated external identity. Contains no tenant or authorization data. */
19
+ export interface Principal {
20
+ subject: string;
21
+ method: string;
22
+ email?: string;
23
+ emailVerified?: boolean;
24
+ name?: string;
25
+ /** IdP-provided avatar URL (OIDC `picture`); validated only at render time. */
26
+ picture?: string;
27
+ tenantHint?: string;
28
+ claims?: Record<string, unknown>;
29
+ }
30
+
31
+ /** A cookie a provider asks the route layer to set. */
32
+ export interface AuthCookie {
33
+ name: string;
34
+ value: string;
35
+ options: {
36
+ httpOnly?: boolean;
37
+ secure?: boolean;
38
+ sameSite?: "lax" | "strict" | "none";
39
+ path?: string;
40
+ maxAge?: number;
41
+ };
42
+ }
43
+
44
+ export type AuthChallenge =
45
+ | { kind: "redirect"; url: string; cookies?: AuthCookie[] }
46
+ | { kind: "form"; fields: Array<{ name: string; label: string; secret?: boolean }> }
47
+ | { kind: "none" };
48
+
49
+ export interface AuthRequestContext {
50
+ surface: LoginSurface;
51
+ tenantId?: string;
52
+ params?: Record<string, string>;
53
+ cookies?: Record<string, string>;
54
+ }
55
+
56
+ export interface AuthProvider {
57
+ readonly descriptor: AuthProviderDescriptor;
58
+ begin?(ctx: AuthRequestContext): Promise<AuthChallenge>;
59
+ callback?(ctx: AuthRequestContext): Promise<Principal>;
60
+ verify?(ctx: AuthRequestContext & { credential: unknown }): Promise<Principal>;
61
+ }
62
+
63
+ export type AuthErrorCode =
64
+ | "INVALID_CREDENTIALS"
65
+ | "PROVIDER_ERROR"
66
+ | "TENANT_UNAVAILABLE"
67
+ | "INVALID_STATE"
68
+ | "EMAIL_REQUIRED"
69
+ | "NOT_PROVISIONED";
70
+
71
+ export class AuthError extends Error {
72
+ constructor(
73
+ readonly code: AuthErrorCode,
74
+ readonly status: 400 | 401 | 502,
75
+ message: string,
76
+ ) {
77
+ super(message);
78
+ this.name = "AuthError";
79
+ }
80
+ }
@@ -0,0 +1,59 @@
1
+ import type { PlatformRole } from "./PlatformMemberStoreProtocol";
2
+ import type { UserTenantRole } from "./UserTenantLinkProtocol";
3
+
4
+ export type InviteLinkScope = "platform" | "tenant";
5
+
6
+ /**
7
+ * A bearer invitation link. The token is stored encrypted at rest and also
8
+ * hashed for lookup; the plaintext token is only returned to platform admins
9
+ * who are allowed to manage the link.
10
+ */
11
+ export interface InviteLink {
12
+ id: string;
13
+ scope: InviteLinkScope;
14
+ token: string;
15
+ tokenHash: string;
16
+ email?: string;
17
+ platformRole?: PlatformRole;
18
+ tenantId?: string;
19
+ tenantRole?: UserTenantRole;
20
+ createdBy?: string;
21
+ createdAt: Date;
22
+ updatedAt: Date;
23
+ expiresAt: Date;
24
+ maxUses: number;
25
+ usedCount: number;
26
+ revokedAt?: Date;
27
+ }
28
+
29
+ export interface CreateInviteLinkInput {
30
+ id: string;
31
+ scope: InviteLinkScope;
32
+ token: string;
33
+ tokenHash: string;
34
+ email?: string;
35
+ platformRole?: PlatformRole;
36
+ tenantId?: string;
37
+ tenantRole?: UserTenantRole;
38
+ createdBy?: string;
39
+ expiresAt: Date;
40
+ maxUses: number;
41
+ }
42
+
43
+ export interface InviteLinkStore {
44
+ list(): Promise<InviteLink[]>;
45
+ get(id: string): Promise<InviteLink | null>;
46
+ getByTokenHash(tokenHash: string): Promise<InviteLink | null>;
47
+ create(input: CreateInviteLinkInput): Promise<InviteLink>;
48
+ /**
49
+ * Atomically consumes one use of a live link.
50
+ *
51
+ * Returns null when the link is missing, revoked, expired, or exhausted.
52
+ */
53
+ consume(tokenHash: string, now: Date): Promise<InviteLink | null>;
54
+ revoke(id: string, now: Date): Promise<InviteLink | null>;
55
+ }
56
+
57
+ export function normalizeInviteLinkEmail(email: string): string {
58
+ return email.trim().toLowerCase();
59
+ }
@@ -0,0 +1,117 @@
1
+ import type { PlatformRole } from "./PlatformMemberStoreProtocol";
2
+ import type { UserTenantRole } from "./UserTenantLinkProtocol";
3
+
4
+ /**
5
+ * Pending SSO identity claims.
6
+ *
7
+ * A claim is created when an enterprise IdP authenticates a user without an
8
+ * email. It deliberately does not create a user or link an external identity
9
+ * until a platform administrator reviews it. This keeps unverified,
10
+ * user-entered email separate from local accounts and lets an admin either
11
+ * create a new user or explicitly link the SSO identity to an existing one.
12
+ */
13
+ export type OidcIdentityClaimStatus =
14
+ | "pending"
15
+ | "approved"
16
+ | "rejected"
17
+ | "expired";
18
+
19
+ export interface OidcIdentityClaim {
20
+ id: string;
21
+ providerId: string;
22
+ issuer: string;
23
+ subject: string;
24
+ email: string;
25
+ name?: string;
26
+ picture?: string;
27
+ status: OidcIdentityClaimStatus;
28
+ createdAt: Date;
29
+ updatedAt: Date;
30
+ expiresAt: Date;
31
+ reviewedBy?: string;
32
+ reviewedAt?: Date;
33
+ linkedUserId?: string;
34
+ /** Where the request came from; omitted for legacy email-completion claims. */
35
+ source?: "email_completion" | "invite_link";
36
+ inviteLinkId?: string;
37
+ /** Existing user the request is about, for invite links. */
38
+ requestedUserId?: string;
39
+ requestedPlatformRole?: PlatformRole;
40
+ requestedTenantId?: string;
41
+ requestedTenantRole?: UserTenantRole;
42
+ }
43
+
44
+ export interface CreateOidcIdentityClaimInput {
45
+ id: string;
46
+ providerId: string;
47
+ issuer: string;
48
+ subject: string;
49
+ email: string;
50
+ name?: string;
51
+ picture?: string;
52
+ expiresAt: Date;
53
+ source?: "email_completion" | "invite_link";
54
+ inviteLinkId?: string;
55
+ requestedUserId?: string;
56
+ requestedPlatformRole?: PlatformRole;
57
+ requestedTenantId?: string;
58
+ requestedTenantRole?: UserTenantRole;
59
+ }
60
+
61
+ export interface UpdateOidcIdentityClaimInput {
62
+ email?: string;
63
+ name?: string;
64
+ picture?: string;
65
+ }
66
+
67
+ export interface OidcIdentityClaimApproval {
68
+ reviewedBy: string;
69
+ linkedUserId: string;
70
+ }
71
+
72
+ export interface OidcIdentityClaimStore {
73
+ /** Lists claims in a stable order, optionally filtered by status. */
74
+ list(status?: OidcIdentityClaimStatus): Promise<OidcIdentityClaim[]>;
75
+ get(id: string): Promise<OidcIdentityClaim | null>;
76
+ /** Returns the live pending claim for a subject, or null. */
77
+ getPendingBySubject(
78
+ providerId: string,
79
+ issuer: string,
80
+ subject: string,
81
+ now: Date,
82
+ ): Promise<OidcIdentityClaim | null>;
83
+ /**
84
+ * Creates a pending claim.
85
+ *
86
+ * Expired pending claims for the same subject are marked `expired` rather
87
+ * than blocking a retry. A live pending claim raises
88
+ * {@link OidcIdentityClaimConflictError}.
89
+ */
90
+ create(input: CreateOidcIdentityClaimInput): Promise<OidcIdentityClaim>;
91
+ /** Updates the requested profile of a live pending claim. */
92
+ updatePending(
93
+ id: string,
94
+ updates: UpdateOidcIdentityClaimInput,
95
+ now: Date,
96
+ ): Promise<OidcIdentityClaim | null>;
97
+ /** Approves a live pending claim with CAS semantics. */
98
+ approve(
99
+ id: string,
100
+ approval: OidcIdentityClaimApproval,
101
+ now: Date,
102
+ ): Promise<OidcIdentityClaim | null>;
103
+ /** Rejects a live pending claim with CAS semantics. */
104
+ reject(id: string, reviewedBy: string, now: Date): Promise<OidcIdentityClaim | null>;
105
+ delete(id: string): Promise<boolean>;
106
+ }
107
+
108
+ export class OidcIdentityClaimConflictError extends Error {
109
+ constructor(readonly providerId: string, readonly issuer: string, readonly subject: string) {
110
+ super("A pending SSO identity claim already exists for this subject");
111
+ this.name = "OidcIdentityClaimConflictError";
112
+ }
113
+ }
114
+
115
+ export function normalizeOidcIdentityEmail(email: string): string {
116
+ return email.trim().toLowerCase();
117
+ }
@@ -0,0 +1,84 @@
1
+ export interface OidcProviderConfig {
2
+ id: string;
3
+ displayName: string;
4
+ issuer: string;
5
+ clientId: string;
6
+ clientSecret: string;
7
+ scopes: string;
8
+ enabled: boolean;
9
+ jitProvisioning: boolean;
10
+ autoLinkEmail: boolean;
11
+ defaultTenantId?: string;
12
+ /**
13
+ * Exact hostnames allowed to resolve to a private address for this provider.
14
+ *
15
+ * `undefined` falls back to the deployment allowlist; an explicit empty array
16
+ * denies all private-network issuers for this provider.
17
+ */
18
+ allowedPrivateHosts?: string[];
19
+ createdAt: Date;
20
+ updatedAt: Date;
21
+ }
22
+
23
+ export interface CreateOidcProviderConfigInput {
24
+ displayName: string;
25
+ issuer: string;
26
+ clientId: string;
27
+ clientSecret: string;
28
+ scopes: string;
29
+ enabled: boolean;
30
+ jitProvisioning: boolean;
31
+ autoLinkEmail: boolean;
32
+ defaultTenantId?: string;
33
+ allowedPrivateHosts?: string[];
34
+ }
35
+
36
+ export interface UpdateOidcProviderConfigInput {
37
+ displayName?: string;
38
+ issuer?: string;
39
+ clientId?: string;
40
+ clientSecret?: string;
41
+ scopes?: string;
42
+ enabled?: boolean;
43
+ jitProvisioning?: boolean;
44
+ autoLinkEmail?: boolean;
45
+ defaultTenantId?: string | null;
46
+ allowedPrivateHosts?: string[];
47
+ }
48
+
49
+ /**
50
+ * Normalizes an allowed-private-hosts list by trimming and lowercasing each
51
+ * entry and removing duplicates. Empty entries are preserved; callers that
52
+ * accept user input must reject them before calling this helper.
53
+ *
54
+ * @param values - Raw hostname entries.
55
+ * @returns Deduplicated, normalized hostname entries.
56
+ */
57
+ export function normalizeAllowedPrivateHosts(
58
+ values: readonly string[],
59
+ ): string[] {
60
+ return [...new Set(values.map((value) => value.trim().toLowerCase()))];
61
+ }
62
+
63
+ export class OidcProviderConfigConflictError extends Error {
64
+ readonly code = "OIDC_PROVIDER_CONFIG_CONFLICT";
65
+
66
+ constructor(readonly id: string) {
67
+ super(`OIDC provider config "${id}" already exists`);
68
+ this.name = "OidcProviderConfigConflictError";
69
+ }
70
+ }
71
+
72
+ export interface OidcProviderConfigStore {
73
+ list(): Promise<OidcProviderConfig[]>;
74
+ get(id: string): Promise<OidcProviderConfig | null>;
75
+ create(
76
+ id: string,
77
+ input: CreateOidcProviderConfigInput,
78
+ ): Promise<OidcProviderConfig>;
79
+ update(
80
+ id: string,
81
+ updates: UpdateOidcProviderConfigInput,
82
+ ): Promise<OidcProviderConfig | null>;
83
+ delete(id: string): Promise<boolean>;
84
+ }
@@ -0,0 +1,60 @@
1
+ import type { PlatformRole } from "./PlatformMemberStoreProtocol";
2
+
3
+ /**
4
+ * Normalizes a platform invitation email for storage and lookup.
5
+ *
6
+ * Emails are trimmed and lower-cased so the same address maps to a single
7
+ * invitation regardless of caller formatting.
8
+ *
9
+ * @param email Raw email address supplied by a caller.
10
+ * @returns The normalized email address.
11
+ */
12
+ export function normalizePlatformInvitationEmail(email: string): string {
13
+ return email.trim().toLowerCase();
14
+ }
15
+
16
+ /** Durable invitation for a platform-level role, keyed by normalized email. */
17
+ export interface PlatformInvitation {
18
+ /** Normalized (trimmed, lower-cased) invitee email. */
19
+ email: string;
20
+ /** Platform role granted when the invitation is consumed. */
21
+ role: PlatformRole;
22
+ /** User id of the platform owner/admin who created the invitation. */
23
+ invitedBy?: string;
24
+ /** When the invitation was created. */
25
+ createdAt: Date;
26
+ /** Optional expiry; invitations at or after this instant cannot be consumed. */
27
+ expiresAt?: Date;
28
+ /** When the invitation was consumed, or omitted while pending. */
29
+ consumedAt?: Date;
30
+ }
31
+
32
+ /**
33
+ * Persistence operations for platform invitations.
34
+ *
35
+ * Implementations normalize emails on every write and lookup. All operations
36
+ * are idempotent with respect to normalization.
37
+ */
38
+ export interface PlatformInvitationStore {
39
+ /** Lists every invitation, ordered by normalized email. */
40
+ list(): Promise<PlatformInvitation[]>;
41
+ /** Returns the invitation for an email, or null. */
42
+ get(email: string): Promise<PlatformInvitation | null>;
43
+ /**
44
+ * Inserts or replaces an invitation keyed by normalized email.
45
+ *
46
+ * The supplied invitation replaces any existing row in full (last write wins),
47
+ * including `expiresAt` and `consumedAt`.
48
+ */
49
+ upsert(invitation: PlatformInvitation): Promise<PlatformInvitation>;
50
+ /** Deletes an invitation. Returns whether a row was removed. */
51
+ delete(email: string): Promise<boolean>;
52
+ /**
53
+ * Atomically consumes a pending, unexpired invitation.
54
+ *
55
+ * A row is consumable only when `consumedAt` is unset and `expiresAt` is
56
+ * unset or strictly after `at`. Returns the consumed invitation, or null
57
+ * when the row is missing, already consumed, or expired.
58
+ */
59
+ consume(email: string, at: Date): Promise<PlatformInvitation | null>;
60
+ }
@@ -0,0 +1,23 @@
1
+ /** Platform-level role, independent of any tenant role. */
2
+ export type PlatformRole = "owner" | "admin" | "auditor";
3
+
4
+ /** Durable platform grant for a single user. */
5
+ export interface PlatformMember {
6
+ userId: string;
7
+ role: PlatformRole;
8
+ grantedBy?: string;
9
+ grantedAt: Date;
10
+ updatedAt: Date;
11
+ }
12
+
13
+ /** Persistence operations for platform members. */
14
+ export interface PlatformMemberStore {
15
+ /** Lists every platform member. */
16
+ list(): Promise<PlatformMember[]>;
17
+ /** Returns the platform member for a user, or null. */
18
+ get(userId: string): Promise<PlatformMember | null>;
19
+ /** Inserts or replaces a member keyed by user id (last write wins). */
20
+ upsert(member: PlatformMember): Promise<PlatformMember>;
21
+ /** Deletes a member. Returns whether a row was removed. */
22
+ delete(userId: string): Promise<boolean>;
23
+ }
@@ -0,0 +1,151 @@
1
+ /** Source that produced an effective platform setting value. */
2
+ export type PlatformSettingSource = "default" | "env" | "platform";
3
+
4
+ /** Branding fields applied to the console and public surfaces. */
5
+ export interface PlatformBranding {
6
+ brandName?: string;
7
+ logoUrl?: string;
8
+ faviconUrl?: string;
9
+ primaryColor?: string;
10
+ backgroundColor?: string;
11
+ loginTitle?: string;
12
+ loginSubtitle?: string;
13
+ }
14
+
15
+ /** Host-scoped branding and public endpoint overrides. */
16
+ export interface BrandingDomain {
17
+ host: string;
18
+ status?: "active" | "pending";
19
+ publicGatewayUrl?: string;
20
+ publicConsoleUrl?: string;
21
+ branding?: PlatformBranding;
22
+ }
23
+
24
+ /** Platform default branding plus host-specific overrides. */
25
+ export interface PlatformBrandingSettings {
26
+ default?: PlatformBranding;
27
+ domains?: BrandingDomain[];
28
+ }
29
+
30
+ /** Branding resolved for a request host. */
31
+ export interface ResolvedPlatformBranding {
32
+ branding: PlatformBranding;
33
+ source: "domain" | "default";
34
+ host?: string;
35
+ publicGatewayUrl?: string;
36
+ publicConsoleUrl?: string;
37
+ }
38
+
39
+ /** Persisted, partial platform settings document managed by platform admins. */
40
+ export interface PlatformSettingsDocument {
41
+ auth?: { emailCompletionEnabled?: boolean };
42
+ invite?: { defaultExpiresInHours?: number; defaultMaxUses?: number };
43
+ rateLimits?: {
44
+ openApiPerMinute?: number;
45
+ openAgentPerMinute?: number;
46
+ a2aJsonRpcPerMinute?: number;
47
+ a2aJsonRpcIpPerMinute?: number;
48
+ maxActiveRunTasksPerTenant?: number | null;
49
+ };
50
+ branding?: PlatformBrandingSettings;
51
+ }
52
+
53
+ /** Stored platform settings record with version and audit metadata. */
54
+ export interface PlatformSettingsRecord extends PlatformSettingsDocument {
55
+ version: number;
56
+ updatedBy?: string;
57
+ updatedAt: Date;
58
+ }
59
+
60
+ /** Fully-resolved platform settings (no optional fields). */
61
+ export interface EffectivePlatformSettings {
62
+ auth: { emailCompletionEnabled: boolean };
63
+ invite: { defaultExpiresInHours: number; defaultMaxUses: number };
64
+ rateLimits: {
65
+ openApiPerMinute: number;
66
+ openAgentPerMinute: number;
67
+ a2aJsonRpcPerMinute: number;
68
+ a2aJsonRpcIpPerMinute: number;
69
+ maxActiveRunTasksPerTenant: number | null;
70
+ };
71
+ }
72
+
73
+ /** Read-only snapshot of effective settings, provenance, and fallbacks. */
74
+ export interface PlatformSettingsSnapshot {
75
+ version: number;
76
+ effective: EffectivePlatformSettings;
77
+ sources: Record<string, PlatformSettingSource>;
78
+ fallbacks: EffectivePlatformSettings;
79
+ updatedBy?: string;
80
+ updatedAt?: Date;
81
+ /** Time this snapshot was last loaded or applied from the store. */
82
+ refreshedAt?: Date;
83
+ }
84
+
85
+ /** Read-only accessor for effective platform settings. */
86
+ export interface PlatformSettingsProvider {
87
+ getSnapshot(): PlatformSettingsSnapshot;
88
+ getEffective(): EffectivePlatformSettings;
89
+ getInviteDefaults(): EffectivePlatformSettings["invite"];
90
+ getRateLimits(): EffectivePlatformSettings["rateLimits"];
91
+ }
92
+
93
+ /** Persistence operations for platform settings with version CAS. */
94
+ export interface PlatformSettingsStore {
95
+ get(): Promise<PlatformSettingsRecord | null>;
96
+ save(
97
+ document: PlatformSettingsDocument,
98
+ expectedVersion: number,
99
+ updatedBy?: string,
100
+ ): Promise<PlatformSettingsRecord>;
101
+ }
102
+
103
+ /** Thrown when a save is attempted against a stale settings version. */
104
+ export class PlatformSettingsVersionConflictError extends Error {
105
+ readonly code = "PLATFORM_SETTINGS_VERSION_CONFLICT";
106
+ constructor(
107
+ readonly expectedVersion: number,
108
+ readonly actualVersion?: number,
109
+ ) {
110
+ super(`Platform settings version conflict at ${expectedVersion}`);
111
+ this.name = "PlatformSettingsVersionConflictError";
112
+ }
113
+ }
114
+
115
+ /** Built-in fallback values used when neither platform nor env set a value. */
116
+ export const PLATFORM_SETTINGS_DEFAULTS = {
117
+ auth: { emailCompletionEnabled: false },
118
+ invite: { defaultExpiresInHours: 168, defaultMaxUses: 1 },
119
+ rateLimits: {
120
+ openApiPerMinute: 60_000,
121
+ openAgentPerMinute: 2_000,
122
+ a2aJsonRpcPerMinute: 600,
123
+ a2aJsonRpcIpPerMinute: 300,
124
+ maxActiveRunTasksPerTenant: null,
125
+ },
126
+ } as const satisfies EffectivePlatformSettings;
127
+
128
+ /** Branding used when neither the platform default nor a domain overrides it. */
129
+ export const DEFAULT_PLATFORM_BRANDING: PlatformBranding = {
130
+ brandName: "AlphaFina",
131
+ };
132
+
133
+ /**
134
+ * Canonicalizes a request or configured host for matching.
135
+ *
136
+ * Lowercases the value, strips an optional port, unwraps bracketed IPv6
137
+ * literals, and removes trailing dots.
138
+ */
139
+ export function normalizeBrandingHost(raw: string): string {
140
+ let host = raw.trim().toLowerCase();
141
+ if (host.startsWith("[")) {
142
+ const end = host.indexOf("]");
143
+ if (end !== -1) host = host.slice(1, end);
144
+ } else {
145
+ const firstColon = host.indexOf(":");
146
+ if (firstColon !== -1 && host.indexOf(":", firstColon + 1) === -1) {
147
+ host = host.slice(0, firstColon);
148
+ }
149
+ }
150
+ return host.replace(/\.+$/, "");
151
+ }
@@ -36,7 +36,7 @@ export interface SandboxPluginConnectionDef {
36
36
 
37
37
  /**
38
38
  * Authoritative declarative definition of a tenant plugin, stored at
39
- * `/root/.agents/plugins/<type>/plugin.json`.
39
+ * the configured agents root `/plugins/<type>/plugin.json`.
40
40
  */
41
41
  export interface SandboxPluginManifest {
42
42
  schemaVersion: 1;
@@ -0,0 +1,53 @@
1
+ export interface UserExternalIdentity {
2
+ userId: string;
3
+ providerId: string;
4
+ /** OIDC issuer (or derived provider key); prevents cross-IdP subject collisions. */
5
+ issuer: string;
6
+ subject: string;
7
+ email?: string;
8
+ linkedAt: Date;
9
+ }
10
+
11
+ export class ExternalIdentityConflictError extends Error {
12
+ readonly code = "EXTERNAL_IDENTITY_CONFLICT";
13
+
14
+ constructor(
15
+ readonly providerId: string,
16
+ readonly issuer: string,
17
+ readonly subject: string,
18
+ ) {
19
+ super(
20
+ `External identity ${providerId}/${issuer}/${subject} is already linked to another user`,
21
+ );
22
+ this.name = "ExternalIdentityConflictError";
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Raised when a store cannot read back an external identity immediately after a
28
+ * successful write, which indicates a persistence invariant failure rather than a
29
+ * user-facing conflict.
30
+ */
31
+ export class ExternalIdentityPersistError extends Error {
32
+ readonly code = "EXTERNAL_IDENTITY_PERSIST_FAILED";
33
+
34
+ constructor(
35
+ readonly providerId: string,
36
+ readonly issuer: string,
37
+ readonly subject: string,
38
+ ) {
39
+ super(`Failed to persist external identity ${providerId}/${issuer}/${subject}`);
40
+ this.name = "ExternalIdentityPersistError";
41
+ }
42
+ }
43
+
44
+ export interface UserExternalIdentityStore {
45
+ getByProviderSubject(
46
+ providerId: string,
47
+ issuer: string,
48
+ subject: string,
49
+ ): Promise<UserExternalIdentity | null>;
50
+ listByUser(userId: string): Promise<UserExternalIdentity[]>;
51
+ link(identity: UserExternalIdentity): Promise<void>;
52
+ unlink(providerId: string, issuer: string, subject: string): Promise<void>;
53
+ }
@@ -0,0 +1,20 @@
1
+ import { AuthError, ExternalIdentityConflictError } from "../index";
2
+
3
+ describe("auth protocol contracts", () => {
4
+ it("preserves the AuthError code and HTTP status", () => {
5
+ const error = new AuthError("INVALID_STATE", 400, "bad state");
6
+ expect(error).toBeInstanceOf(Error);
7
+ expect(error.name).toBe("AuthError");
8
+ expect(error.code).toBe("INVALID_STATE");
9
+ expect(error.status).toBe(400);
10
+ });
11
+
12
+ it("names the conflicting external identity", () => {
13
+ const error = new ExternalIdentityConflictError("oidc", "https://idp.example.com", "azure-oid-1");
14
+ expect(error.name).toBe("ExternalIdentityConflictError");
15
+ expect(error.code).toBe("EXTERNAL_IDENTITY_CONFLICT");
16
+ expect(error.providerId).toBe("oidc");
17
+ expect(error.issuer).toBe("https://idp.example.com");
18
+ expect(error.subject).toBe("azure-oid-1");
19
+ });
20
+ });