@deuriib/better-dgii-ecf 0.0.0-stage → 0.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client-provider.ts","../src/persistence.ts","../src/tax-payer.ts","../src/resolution.ts","../src/xml.ts","../src/endpoints/shared.ts","../src/endpoints/documents.ts","../src/endpoints/inquiries.ts","../src/endpoints/status.ts","../src/endpoints/audit.ts","../src/plugin.ts"],"names":["defineErrorCodes","APIError","BetterAuthError","ECF","createHash","Environment","Signature","z","createAuthEndpoint","sessionMiddleware","scopeShape","z2","z3","StatusEnvironment","z4"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,IAAM,uBAAuBA,2BAAA,CAAiB;AAAA,EACnD,qBAAA,EAAuB,oDAAA;AAAA,EACvB,yBAAA,EACE,yHAAA;AAAA,EACF,wBAAA,EACE,6EAAA;AAAA,EACF,yBAAA,EACE,iGAAA;AAAA,EACF,0BAAA,EACE,2EAAA;AAAA,EACF,2BAAA,EAA6B,yCAAA;AAAA,EAC7B,0BAAA,EACE,4FAAA;AAAA,EACF,iBAAA,EAAmB,+DAAA;AAAA,EACnB,sBAAA,EACE,8EAAA;AAAA,EACF,4BAAA,EACE,4DAAA;AAAA,EACF,0BAAA,EACE,yFAAA;AAAA,EACF,4BAAA,EACE,qEAAA;AAAA,EACF,wBAAA,EACE,2EAAA;AAAA,EACF,mBAAA,EAAqB,4DAAA;AAAA,EACrB,mBAAA,EAAqB,yBAAA;AAAA,EACrB,yBAAA,EAA2B,sCAAA;AAAA,EAC3B,4BAAA,EACE,sEAAA;AAAA,EACF,0BAAA,EACE;AACJ,CAAC;AAaD,IAAM,mBAAA,GACJ;AAAA,EACE,WAAA,EAAa,aAAA;AAAA,EACb,OAAA,EAAS,aAAA;AAAA,EACT,UAAA,EAAY,aAAA;AAAA,EACZ,WAAA,EAAa,uBAAA;AAAA,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,EAAA;AAAA,QACR,GAAA,EAAK,EAAA;AAAA,QACL,WAAA,EAAa,CAAC,IAAA,KAAiB,IAAA,CAAK,WAAW,WAAW;AAAA;AAC5D;AACF,GACF;AAEA,EAAA,OAAO,OAAO,MAAA,CAAO,MAAA,EAAQ,EAAE,cAAA,EAAgB,UAAU,CAAA;AAC3D","file":"index.cjs","sourcesContent":["import { APIError } from 'better-auth/api';\nimport { defineErrorCodes } from '@better-auth/core/utils/error-codes';\nimport type { DgiiError, DgiiErrorCode } from '@deuriib/dgii-ecf';\n\n/**\n * Error codes this plugin can return.\n *\n * They are declared through `defineErrorCodes` so they flow into Better Auth's\n * own type surface (`auth.$ERROR_CODES`, client `error.code`) and so the keys\n * are constrained to UPPER_SNAKE_CASE at compile time. Every code describes a\n * condition the plugin itself decided on; a failure DGII produced is reported\n * as {@link DGII_ECF_ERROR_CODES.DGII_REQUEST_FAILED} with the upstream detail\n * attached, never smuggled into a success payload.\n */\nexport const DGII_ECF_ERROR_CODES = defineErrorCodes({\n DGII_SESSION_REQUIRED: 'A session is required to call a DGII e-CF endpoint',\n DGII_TAXPAYER_ID_REQUIRED:\n 'No taxpayer id (RNC) could be resolved: send `taxPayerId`, set the organization field, or configure `resolveTaxPayerId`',\n DGII_TAXPAYER_ID_INVALID:\n 'The taxpayer id is not a valid DGII RNC (9 digits) or cédula (11 digits)',\n DGII_TAXPAYER_ID_MISMATCH:\n 'The signed document was issued under a taxpayer id other than the one resolved for this request',\n DGII_TAXPAYER_ID_FORBIDDEN:\n 'This session is not allowed to act on behalf of the requested taxpayer id',\n DGII_ORGANIZATION_NOT_FOUND: 'The organization in scope was not found',\n DGII_ORGANIZATION_REQUIRED:\n 'This request needs an organization: send `organizationId` or select an active organization',\n DGII_NOT_A_MEMBER: 'The session user is not a member of the organization in scope',\n DGII_INSUFFICIENT_ROLE:\n 'The session user does not hold a role allowed to perform this DGII operation',\n DGII_CREDENTIALS_UNAVAILABLE:\n 'No DGII credentials could be resolved for this taxpayer id',\n DGII_CLIENT_NOT_CONFIGURED:\n 'The plugin was configured without `credentials` or `getClient`, so it cannot reach DGII',\n DGII_STATUS_API_KEY_REQUIRED:\n 'The DGII status service needs an API key: configure `status.apiKey`',\n DGII_DOCUMENT_UNREADABLE:\n 'The signed document carries no issuer taxpayer id (RNCEmisor / RncEmisor)',\n DGII_SIGNING_FAILED: 'The document could not be signed with the organization key',\n DGII_REQUEST_FAILED: 'The DGII request failed',\n DGII_SUBMISSION_NOT_FOUND: 'No stored submission matches this id',\n DGII_PERSISTENCE_UNAVAILABLE:\n 'Submission persistence is disabled, so this operation is unavailable',\n DGII_IDEMPOTENCY_IN_FLIGHT:\n 'A submission with this idempotency key is still in flight or has an unknown outcome; reconcile it before retrying',\n});\n\nexport type DgiiEcfErrorCode = keyof typeof DGII_ECF_ERROR_CODES;\n\n/**\n * HTTP status for a failure the DGII SDK reported.\n *\n * The distinction matters to callers: a 400 means the request or the document\n * is wrong and resending it unchanged will fail again, while a 502 means DGII\n * (or the network to it) is the problem and the call is worth retrying. An\n * upstream credential problem is a 500: the application's server-side\n * configuration is broken and no retry from the client can fix it.\n */\nconst STATUS_BY_DGII_CODE: Record<DgiiErrorCode, Parameters<typeof APIError.from>[0]> =\n {\n INVALID_XML: 'BAD_REQUEST',\n SIGNING: 'BAD_REQUEST',\n VALIDATION: 'BAD_REQUEST',\n CERTIFICATE: 'INTERNAL_SERVER_ERROR',\n IDEMPOTENCY: 'CONFLICT',\n AUTH: 'BAD_GATEWAY',\n HTTP: 'BAD_GATEWAY',\n TIMEOUT: 'BAD_GATEWAY',\n CIRCUIT_OPEN: 'BAD_GATEWAY',\n UNKNOWN: 'BAD_GATEWAY',\n };\n\ninterface DgiiFailureDetail {\n readonly code: DgiiErrorCode;\n readonly status?: number | undefined;\n readonly statusText?: string | undefined;\n readonly resource?: string | undefined;\n readonly method?: string | undefined;\n readonly mensajes?: readonly { valor: string; codigo: number | string }[] | undefined;\n}\n\n/**\n * Shapes a {@link DgiiError} for the wire.\n *\n * `data` and `baseURL` are deliberately dropped. `data` is whatever body DGII\n * returned, and on the authentication endpoints that body carries the bearer\n * token — echoing it back in an error message would leak a credential into\n * logs, browser devtools and error trackers.\n */\nconst toFailureDetail = (error: DgiiError): DgiiFailureDetail => ({\n code: error.code,\n status: error.status,\n statusText: error.statusText,\n resource: error.resource,\n method: error.method,\n mensajes: error.mensajes,\n});\n\n/** The shape `defineErrorCodes` produces, without depending on its internals. */\nexport interface ErrorCodeLike {\n readonly code: string;\n readonly message: string;\n}\n\nexport const badRequest = (error: ErrorCodeLike, message?: string): APIError =>\n new APIError('BAD_REQUEST', {\n message: message ?? error.message,\n code: error.code,\n });\n\nexport const forbidden = (error: ErrorCodeLike, message?: string): APIError =>\n new APIError('FORBIDDEN', {\n message: message ?? error.message,\n code: error.code,\n });\n\nexport const conflict = (error: ErrorCodeLike, message?: string): APIError =>\n new APIError('CONFLICT', {\n message: message ?? error.message,\n code: error.code,\n });\n\nexport const serverError = (error: ErrorCodeLike, message?: string): APIError =>\n new APIError('INTERNAL_SERVER_ERROR', {\n message: message ?? error.message,\n code: error.code,\n });\n\n/** Translate a DGII SDK failure into an `APIError` the client can branch on. */\nexport const toApiError = (error: DgiiError): APIError =>\n new APIError(STATUS_BY_DGII_CODE[error.code], {\n message: error.message,\n code: DGII_ECF_ERROR_CODES.DGII_REQUEST_FAILED.code,\n dgii: toFailureDetail(error),\n });\n","import { APIError } from 'better-auth/api';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { ECF } from '@deuriib/dgii-ecf';\nimport type { DgiiEcfOptions, DgiiEcfScope } from './types.js';\nimport { DGII_ECF_ERROR_CODES } from './errors.js';\n\n/**\n * Supplies the DGII client for a resolved scope.\n *\n * The plugin owns no key material of its own: the host resolves it per\n * taxpayer, over a callback that never sees the HTTP request. That is the whole\n * security model — a browser can call these endpoints, but it can never supply,\n * read or influence which certificate signs a document.\n */\nexport interface DgiiEcfClientProvider {\n /** The client for this scope, or an `APIError` when none can be built. */\n get(scope: DgiiEcfScope): Promise<ECF>;\n /** Drop cached clients, all of them or only one taxpayer's. */\n invalidate(taxPayerId?: string): void;\n /** Number of cached clients; always 0 when `getClient` is configured. */\n readonly size: number;\n /**\n * True when the plugin builds the `ECF` instances (the `credentials` mode).\n *\n * The status endpoints use it to decide whether the plugin's own\n * `status.apiKey` is the authority: a host that supplies its own client kept\n * the status key to itself too, so the plugin must not demand one.\n */\n readonly constructsClients: boolean;\n}\n\nconst DEFAULT_MAX_SIZE = 50;\nconst DEFAULT_TTL_MS = 10 * 60 * 1000;\n\nconst cacheKey = (scope: DgiiEcfScope): string =>\n `${scope.environment}\\u0000${scope.taxPayerId}`;\n\ninterface CacheEntry {\n readonly client: ECF;\n readonly expiresAt: number;\n}\n\nconst unavailable = (taxPayerId: string): APIError =>\n new APIError('INTERNAL_SERVER_ERROR', {\n message: `No DGII credentials were resolved for taxpayer ${taxPayerId}`,\n code: DGII_ECF_ERROR_CODES.DGII_CREDENTIALS_UNAVAILABLE.code,\n });\n\n/**\n * Build the provider from the plugin options.\n *\n * `getClient` wins over `credentials` when both are present: a host that already\n * pools clients is the authority on their lifecycle, so the plugin refuses to\n * cache a second copy behind its back.\n *\n * Configuration is validated here rather than per request. A plugin instance\n * that cannot reach DGII at all should fail when `betterAuth()` is constructed,\n * not on the first invoice.\n */\nexport const createClientProvider = (\n options: DgiiEcfOptions,\n now: () => number = Date.now,\n): DgiiEcfClientProvider => {\n const getClient = options.getClient;\n\n if (getClient !== undefined) {\n return {\n async get(scope) {\n const client = await getClient(scope);\n if (client === null) {\n throw unavailable(scope.taxPayerId);\n }\n return client;\n },\n invalidate() {\n // Nothing is cached here; the resolver owns the instances.\n },\n size: 0,\n constructsClients: false,\n };\n }\n\n const resolveCredentials = options.credentials;\n if (resolveCredentials === undefined) {\n throw new BetterAuthError(\n '[better-dgii-ecf] Configure `credentials` or `getClient` — the plugin cannot reach DGII without one of them.',\n );\n }\n\n const maxSize = Math.max(1, options.clientCache?.maxSize ?? DEFAULT_MAX_SIZE);\n const ttlMs = Math.max(0, options.clientCache?.ttlMs ?? DEFAULT_TTL_MS);\n const cache = new Map<string, CacheEntry>();\n\n const evictExpired = (at: number): void => {\n for (const [key, entry] of cache) {\n if (entry.expiresAt <= at) {\n cache.delete(key);\n }\n }\n };\n\n return {\n async get(scope) {\n const at = now();\n evictExpired(at);\n\n const key = cacheKey(scope);\n const cached = cache.get(key);\n if (cached !== undefined && cached.expiresAt > at) {\n // Refresh recency so the size cap evicts the least recently used entry.\n cache.delete(key);\n cache.set(key, cached);\n return cached.client;\n }\n\n const material = await resolveCredentials(scope);\n if (material === null) {\n throw unavailable(scope.taxPayerId);\n }\n if (material.key === undefined || material.cert === undefined) {\n throw new APIError('INTERNAL_SERVER_ERROR', {\n message: `The credentials resolved for taxpayer ${scope.taxPayerId} carry no key/cert PEM pair`,\n code: DGII_ECF_ERROR_CODES.DGII_CREDENTIALS_UNAVAILABLE.code,\n });\n }\n\n const statusApiKey = options.status?.apiKey;\n const client = new ECF(material, scope.environment, {\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n ...(statusApiKey === undefined ? {} : { statusApiKey }),\n });\n\n if (ttlMs > 0) {\n while (cache.size >= maxSize) {\n const oldest = cache.keys().next();\n if (oldest.done === true) {\n break;\n }\n cache.delete(oldest.value);\n }\n cache.set(key, { client, expiresAt: at + ttlMs });\n }\n return client;\n },\n invalidate(taxPayerId) {\n if (taxPayerId === undefined) {\n cache.clear();\n return;\n }\n for (const key of cache.keys()) {\n if (key.endsWith(`\\u0000${taxPayerId}`)) {\n cache.delete(key);\n }\n }\n },\n get size() {\n return cache.size;\n },\n constructsClients: true,\n };\n};\n","import { createHash } from 'node:crypto';\nimport { APIError } from 'better-auth/api';\nimport type { GenericEndpointContext } from '@better-auth/core';\nimport { DGII_ECF_ERROR_CODES } from './errors.js';\nimport type { DgiiEcfPersistenceOptions } from './types.js';\n\n/**\n * Submission persistence: the audit trail and the replay guard.\n *\n * Two problems are solved by the same row:\n *\n * 1. **Replay safety.** The DGII SDK keeps its idempotency markers in memory, so\n * a restart or a second instance loses them and a retried POST can submit the\n * same fiscal document twice. The row makes the guard durable.\n * 2. **Audit.** Who submitted what, under which taxpayer, with which track id\n * and what DGII answered. Fiscal operations need that trail.\n *\n * Only derived data is stored: the SHA-256 of the signed document, never the\n * document, and never key material or a bearer token.\n */\n\n/** Model key of the table this plugin owns. */\nexport const SUBMISSION_MODEL = 'dgiiEcfSubmission';\n\nexport type SubmissionStatus = 'pending' | 'succeeded' | 'failed';\n\nexport interface SubmissionRecord extends Record<string, unknown> {\n id: string;\n organizationId?: string | null;\n taxPayerId: string;\n userId: string;\n environment: string;\n operation: string;\n status: SubmissionStatus;\n idempotencyKey?: string | null;\n encf?: string | null;\n trackId?: string | null;\n documentHash?: string | null;\n errorCode?: string | null;\n response?: string | null;\n createdAt?: Date | string;\n updatedAt?: Date | string;\n}\n\nexport interface BeginSubmissionInput {\n readonly organizationId: string | null;\n readonly taxPayerId: string;\n readonly userId: string;\n readonly environment: string;\n readonly operation: string;\n readonly idempotencyKey: string;\n readonly encf: string | null;\n readonly documentHash: string | null;\n}\n\nexport interface ListSubmissionsInput {\n readonly organizationId: string | null;\n readonly taxPayerId: string | null;\n readonly limit: number;\n}\n\nconst DEFAULT_MAX_RESPONSE_LENGTH = 8192;\n\n/** SHA-256 of a signed document, hex encoded — the replay key of last resort. */\nexport const hashDocument = (xml: string): string =>\n createHash('sha256').update(xml, 'utf8').digest('hex');\n\nconst serializeResponse = (value: unknown, maxLength: number): string | null => {\n if (value === undefined || value === null) {\n return null;\n }\n let serialized: string;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return null;\n }\n if (serialized === undefined) {\n return null;\n }\n return serialized.length > maxLength ? serialized.slice(0, maxLength) : serialized;\n};\n\nexport interface DgiiEcfSubmissionStore {\n readonly enabled: boolean;\n /**\n * A previously recorded submission for the same taxpayer and replay key.\n *\n * Returns the record whatever its status: the caller decides what a `pending`\n * or `failed` record means for the attempt it is about to make.\n */\n findReplay(\n taxPayerId: string,\n idempotencyKey: string,\n ): Promise<SubmissionRecord | null>;\n /** Record the attempt before it is transmitted; `null` when persistence is off. */\n begin(input: BeginSubmissionInput): Promise<string | null>;\n /** Finish a recorded attempt, whatever its outcome. */\n complete(\n id: string | null,\n outcome: {\n status: Exclude<SubmissionStatus, 'pending'>;\n trackId?: string | null;\n response?: unknown;\n errorCode?: string | null;\n },\n ): Promise<void>;\n /** Audit listing for the organization (or taxpayer) in scope. */\n list(input: ListSubmissionsInput): Promise<SubmissionRecord[]>;\n}\n\nconst disabledStore: DgiiEcfSubmissionStore = {\n enabled: false,\n async findReplay() {\n return null;\n },\n async begin() {\n return null;\n },\n async complete() {\n // Persistence is off: there is no row to finish.\n },\n async list() {\n throw new APIError('NOT_IMPLEMENTED', {\n message: DGII_ECF_ERROR_CODES.DGII_PERSISTENCE_UNAVAILABLE.message,\n code: DGII_ECF_ERROR_CODES.DGII_PERSISTENCE_UNAVAILABLE.code,\n });\n },\n};\n\n/**\n * Build the store over the Better Auth adapter.\n *\n * Failures to write are surfaced, not swallowed: a submission that cannot be\n * recorded must not be transmitted, because the record is the only thing that\n * makes the retry safe. The pending row is written *before* the request leaves,\n * so an interrupted send leaves a marker a later caller can reconcile.\n */\nexport const createSubmissionStore = (\n ctx: GenericEndpointContext,\n options: DgiiEcfPersistenceOptions | undefined,\n): DgiiEcfSubmissionStore => {\n if (options?.enabled === false) {\n return disabledStore;\n }\n const adapter = ctx.context.adapter;\n const storeResponses = options?.storeResponses ?? true;\n const maxResponseLength = options?.maxResponseLength ?? DEFAULT_MAX_RESPONSE_LENGTH;\n\n return {\n enabled: true,\n async findReplay(taxPayerId, idempotencyKey) {\n // `findOne` takes no ordering, and a key can legitimately repeat (a failed\n // attempt followed by a new one), so the newest row is read explicitly.\n const rows = await adapter.findMany<SubmissionRecord>({\n model: SUBMISSION_MODEL,\n where: [\n { field: 'taxPayerId', value: taxPayerId },\n { field: 'idempotencyKey', value: idempotencyKey },\n ],\n limit: 1,\n sortBy: { field: 'createdAt', direction: 'desc' },\n });\n return rows[0] ?? null;\n },\n async begin(input) {\n const created = await adapter.create<SubmissionRecord>({\n model: SUBMISSION_MODEL,\n data: {\n organizationId: input.organizationId,\n taxPayerId: input.taxPayerId,\n userId: input.userId,\n environment: input.environment,\n operation: input.operation,\n status: 'pending',\n idempotencyKey: input.idempotencyKey,\n encf: input.encf,\n trackId: null,\n documentHash: input.documentHash,\n errorCode: null,\n response: null,\n },\n });\n return created.id;\n },\n async complete(id, outcome) {\n if (id === null) {\n return;\n }\n await adapter.update<SubmissionRecord>({\n model: SUBMISSION_MODEL,\n where: [{ field: 'id', value: id }],\n update: {\n status: outcome.status,\n trackId: outcome.trackId ?? null,\n errorCode: outcome.errorCode ?? null,\n response: storeResponses\n ? serializeResponse(outcome.response, maxResponseLength)\n : null,\n },\n });\n },\n async list({ organizationId, taxPayerId, limit }) {\n const where: { field: string; value: string }[] = [];\n if (organizationId !== null) {\n where.push({ field: 'organizationId', value: organizationId });\n }\n if (taxPayerId !== null) {\n where.push({ field: 'taxPayerId', value: taxPayerId });\n }\n return adapter.findMany<SubmissionRecord>({\n model: SUBMISSION_MODEL,\n ...(where.length > 0 ? { where } : {}),\n limit,\n sortBy: { field: 'createdAt', direction: 'desc' },\n });\n },\n };\n};\n\n/**\n * Replay decision for a submission about to be transmitted.\n *\n * - A `succeeded` record is returned as-is: the document already exists at\n * DGII, so re-sending it cannot be the caller's intent.\n * - A `pending` record means an earlier attempt may have reached DGII. Refusing\n * with a conflict is the only safe answer — the caller reconciles by e-NCF\n * instead of gambling on a duplicate fiscal document.\n * - A `failed` record is not a replay: the previous attempt did not land, so the\n * new one may proceed.\n */\nexport const planReplay = (\n record: SubmissionRecord | null,\n):\n | { kind: 'proceed' }\n | { kind: 'replay'; record: SubmissionRecord }\n | { kind: 'conflict' } => {\n if (record === null) {\n return { kind: 'proceed' };\n }\n if (record.status === 'succeeded') {\n return { kind: 'replay', record };\n }\n if (record.status === 'pending') {\n return { kind: 'conflict' };\n }\n return { kind: 'proceed' };\n};\n\n/** Parse a stored response back into the shape the caller originally received. */\nexport const parseStoredResponse = (record: SubmissionRecord): unknown => {\n const raw = record.response;\n if (typeof raw !== 'string' || raw === '') {\n return null;\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n};\n","/**\n * Taxpayer id (RNC / cédula) handling for the DGII e-CF services.\n *\n * Two things are deliberately kept apart:\n *\n * - **Normalization** is unconditional. DGII accepts the identifier with or\n * without separators, and a database that stores `1-31-12345-6` while the\n * organization field stores `131123456` must not produce a mismatch.\n * - **Validation** is a policy. The only rule enforced by default is the\n * documented shape: 9 digits for an RNC, 11 for a cédula. Anything stricter\n * (a check digit, an allow-list of registered taxpayers) is the host's call,\n * so it is injected rather than assumed.\n */\n\n/** Separators DGII tolerates in a taxpayer id: spaces, dashes and dots. */\nconst SEPARATORS = /[\\s.\\-–—]/g;\n\n/** 9 digits = RNC (legal entity), 11 digits = cédula (natural person). */\nconst SHAPE = /^(?:\\d{9}|\\d{11})$/;\n\n/** Strip the separators a human types so comparison and storage are stable. */\nexport const normalizeTaxPayerId = (value: string): string =>\n value.replace(SEPARATORS, '').trim();\n\n/**\n * True when the value is a syntactically valid DGII identifier.\n *\n * The input is expected to be already normalized; call\n * {@link normalizeTaxPayerId} first when it comes from user input.\n */\nexport const isTaxPayerIdShape = (value: string): boolean => SHAPE.test(value);\n\n/**\n * Custom validation hook. Return `true` to accept, or a string to accept with\n * a normalized replacement (for example an alias resolved to its canonical\n * RNC). Returning `false` rejects.\n */\nexport type TaxPayerIdValidator = (\n taxPayerId: string,\n) => boolean | string | Promise<boolean | string>;\n\n/** How strictly a resolved taxpayer id is checked. Defaults to `format`. */\nexport type TaxPayerIdValidation = 'format' | 'off' | TaxPayerIdValidator;\n\nexport class TaxPayerIdError extends Error {\n readonly reason: 'shape' | 'custom';\n\n constructor(reason: 'shape' | 'custom', message: string) {\n super(message);\n this.name = 'TaxPayerIdError';\n this.reason = reason;\n }\n}\n\n/**\n * Normalize and validate, returning the canonical id.\n *\n * Throws {@link TaxPayerIdError} so the endpoint layer can map the failure to a\n * single error code regardless of which rule rejected it.\n */\nexport const applyTaxPayerIdValidation = async (\n raw: string,\n validation: TaxPayerIdValidation,\n): Promise<string> => {\n const normalized = normalizeTaxPayerId(raw);\n if (normalized === '') {\n throw new TaxPayerIdError('shape', 'The taxpayer id is empty');\n }\n if (validation === 'off') {\n return normalized;\n }\n if (validation === 'format') {\n if (!isTaxPayerIdShape(normalized)) {\n throw new TaxPayerIdError(\n 'shape',\n `\"${raw}\" is not a DGII RNC (9 digits) or cédula (11 digits)`,\n );\n }\n return normalized;\n }\n const verdict = await validation(normalized);\n if (verdict === false) {\n throw new TaxPayerIdError('custom', `\"${raw}\" was rejected by the validator`);\n }\n if (typeof verdict === 'string') {\n return normalizeTaxPayerId(verdict);\n }\n return normalized;\n};\n","import { APIError } from 'better-auth/api';\nimport { Environment } from '@deuriib/dgii-ecf';\nimport type { Session, User } from 'better-auth';\nimport type { GenericEndpointContext } from '@better-auth/core';\nimport { badRequest, DGII_ECF_ERROR_CODES, forbidden } from './errors.js';\nimport {\n applyTaxPayerIdValidation,\n normalizeTaxPayerId,\n TaxPayerIdError,\n} from './tax-payer.js';\nimport type {\n DgiiEcfOptions,\n DgiiEcfScope,\n DgiiEcfTaxPayerIdSource,\n DgiiEcfTaxPayerIdResolver,\n TaxPayerIdValidation,\n} from './types.js';\n\n/** Organization model key used by the Better Auth organization plugin. */\nconst ORGANIZATION_MODEL = 'organization';\n/** Membership model key used by the Better Auth organization plugin. */\nconst MEMBER_MODEL = 'member';\n\nconst DEFAULT_ROLES = ['owner', 'admin'];\n\n/** The identity behind a call, resolved once per request. */\nexport interface DgiiEcfRequestScope extends DgiiEcfScope {\n readonly organizationTaxPayerId: string | null;\n readonly source: DgiiEcfTaxPayerIdSource;\n readonly user: User;\n readonly session: Session;\n}\n\nexport interface DgiiEcfEndpointInput {\n taxPayerId?: string | undefined;\n organizationId?: string | undefined;\n}\n\ninterface OrganizationRow extends Record<string, unknown> {\n id?: string;\n}\n\ninterface MemberRow extends Record<string, unknown> {\n role?: unknown;\n}\n\n/**\n * True when the organization plugin is part of this Better Auth instance.\n *\n * The plugin never assumes it: without it there is no tenant model, and the\n * authorization policy degrades to the documented single-tenant mode instead of\n * silently failing every call.\n */\nexport const hasOrganizationPlugin = (ctx: GenericEndpointContext): boolean =>\n (ctx.context.options.plugins ?? []).some((plugin) => plugin.id === 'organization');\n\nconst readOrganizationField = (row: OrganizationRow, field: string): string | null => {\n // The declared field name wins; the snake_case spelling is accepted because a\n // host may map the column with `fieldName`.\n const raw = row[field] ?? row.taxPayerId ?? row.tax_payer_id;\n if (typeof raw !== 'string') {\n return null;\n }\n const normalized = normalizeTaxPayerId(raw);\n return normalized === '' ? null : normalized;\n};\n\nconst readActiveOrganizationId = (session: Session): string | null => {\n const raw = (session as { activeOrganizationId?: unknown }).activeOrganizationId;\n return typeof raw === 'string' && raw !== '' ? raw : null;\n};\n\nconst rolesOf = (member: MemberRow): string[] =>\n String(member.role ?? '')\n .split(',')\n .map((role) => role.trim())\n .filter((role) => role !== '');\n\nexport interface ResolveScopeContext {\n readonly ctx: GenericEndpointContext;\n readonly options: DgiiEcfOptions;\n readonly input: DgiiEcfEndpointInput;\n}\n\nconst environmentOf = async (\n options: DgiiEcfOptions,\n scope: Omit<DgiiEcfRequestScope, 'environment'>,\n): Promise<Environment> => {\n const configured = options.environment ?? Environment.Dev;\n if (typeof configured === 'function') {\n return configured({\n taxPayerId: scope.taxPayerId,\n organizationId: scope.organizationId,\n userId: scope.user.id,\n });\n }\n return configured;\n};\n\n/**\n * Resolve (and authorize) the taxpayer a call acts for.\n *\n * Resolution order is fixed and observable to callers through the `source`\n * field returned by `GET /dgii-ecf/taxpayer`:\n *\n * 1. `taxPayerId` in the request — the per-call mode.\n * 2. The organization's stored field — the organization-plugin mode.\n * 3. The configured `resolveTaxPayerId` resolver — the user/tenant mapping mode.\n *\n * Authorization happens after resolution, never before: a request-supplied id is\n * checked against the organization's stored id and the caller's role, so naming\n * a taxpayer in the body cannot grant access to it.\n */\nexport const resolveRequestScope = async ({\n ctx,\n options,\n input,\n}: ResolveScopeContext): Promise<DgiiEcfRequestScope> => {\n const authenticated = ctx.context.session;\n if (authenticated === null) {\n throw new APIError('UNAUTHORIZED', {\n message: DGII_ECF_ERROR_CODES.DGII_SESSION_REQUIRED.message,\n code: DGII_ECF_ERROR_CODES.DGII_SESSION_REQUIRED.code,\n });\n }\n const { user, session } = authenticated;\n\n const withOrganization = hasOrganizationPlugin(ctx);\n const organizationId =\n input.organizationId ??\n (withOrganization ? readActiveOrganizationId(session) : null);\n\n let organization: OrganizationRow | null = null;\n let organizationTaxPayerId: string | null = null;\n if (withOrganization && organizationId !== null) {\n organization = await ctx.context.adapter.findOne<OrganizationRow>({\n model: ORGANIZATION_MODEL,\n where: [{ field: 'id', value: organizationId }],\n });\n if (organization === null) {\n throw new APIError('NOT_FOUND', {\n message: DGII_ECF_ERROR_CODES.DGII_ORGANIZATION_NOT_FOUND.message,\n code: DGII_ECF_ERROR_CODES.DGII_ORGANIZATION_NOT_FOUND.code,\n });\n }\n organizationTaxPayerId = readOrganizationField(\n organization,\n options.organization?.field ?? 'taxPayerId',\n );\n }\n\n const validation: TaxPayerIdValidation = options.validateTaxPayerId ?? 'format';\n const toCanonical = async (raw: string): Promise<string> => {\n try {\n return await applyTaxPayerIdValidation(raw, validation);\n } catch (error) {\n if (error instanceof TaxPayerIdError) {\n throw badRequest(DGII_ECF_ERROR_CODES.DGII_TAXPAYER_ID_INVALID, error.message);\n }\n throw error;\n }\n };\n\n let taxPayerId: string | null = null;\n let source: DgiiEcfTaxPayerIdSource = 'request';\n\n if (input.taxPayerId !== undefined) {\n taxPayerId = await toCanonical(input.taxPayerId);\n } else if (organizationTaxPayerId !== null) {\n taxPayerId = await toCanonical(organizationTaxPayerId);\n source = 'organization';\n } else {\n const resolver: DgiiEcfTaxPayerIdResolver | undefined = options.resolveTaxPayerId;\n const fromResolver =\n resolver === undefined ? null : await resolver({ user, session, organizationId });\n if (fromResolver !== null) {\n taxPayerId = await toCanonical(fromResolver);\n source = 'resolver';\n }\n }\n\n if (taxPayerId === null) {\n throw badRequest(DGII_ECF_ERROR_CODES.DGII_TAXPAYER_ID_REQUIRED);\n }\n\n await authorize({\n ctx,\n options,\n user,\n session,\n taxPayerId,\n organizationId: withOrganization ? organizationId : null,\n organization,\n organizationTaxPayerId,\n source,\n withOrganization,\n });\n\n const resolved: Omit<DgiiEcfRequestScope, 'environment'> = {\n taxPayerId,\n organizationId: withOrganization ? organizationId : null,\n organizationTaxPayerId,\n source,\n userId: user.id,\n user,\n session,\n };\n\n return { ...resolved, environment: await environmentOf(options, resolved) };\n};\n\ninterface AuthorizeInput {\n readonly ctx: GenericEndpointContext;\n readonly options: DgiiEcfOptions;\n readonly user: User;\n readonly session: Session;\n readonly taxPayerId: string;\n readonly organizationId: string | null;\n readonly organization: OrganizationRow | null;\n readonly organizationTaxPayerId: string | null;\n readonly source: DgiiEcfTaxPayerIdSource;\n readonly withOrganization: boolean;\n}\n\n/**\n * The built-in policy.\n *\n * With the organization plugin installed the tenant is the unit of trust: the\n * caller must be a member of the organization in scope, hold an allowed role,\n * and — when the organization stores a taxpayer id — the resolved id must be\n * that one. A request may name a taxpayer, but it cannot name one that the\n * organization does not own.\n *\n * Without the organization plugin there is nothing to check against, so the\n * request-supplied id is accepted: this is the single-tenant mode documented in\n * SECURITY.md. Installing the organization plugin is what turns the strict\n * policy on.\n */\nconst authorize = async (input: AuthorizeInput): Promise<void> => {\n const custom = input.options.authorize;\n if (custom !== undefined) {\n const allowed = await custom({\n user: input.user,\n session: input.session,\n taxPayerId: input.taxPayerId,\n organizationId: input.organizationId,\n organizationTaxPayerId: input.organizationTaxPayerId,\n source: input.source,\n });\n if (!allowed) {\n throw forbidden(DGII_ECF_ERROR_CODES.DGII_TAXPAYER_ID_FORBIDDEN);\n }\n return;\n }\n\n if (!input.withOrganization) {\n return;\n }\n\n if (input.organizationId === null || input.organization === null) {\n if (input.source === 'request' && input.options.allowUntrustedTaxPayerId === true) {\n return;\n }\n if (input.source === 'resolver') {\n // A resolver is server-side configuration: the host decided this mapping.\n return;\n }\n throw badRequest(DGII_ECF_ERROR_CODES.DGII_ORGANIZATION_REQUIRED);\n }\n\n const member = await input.ctx.context.adapter.findOne<MemberRow>({\n model: MEMBER_MODEL,\n where: [\n { field: 'organizationId', value: input.organizationId },\n { field: 'userId', value: input.user.id },\n ],\n });\n if (member === null) {\n throw forbidden(DGII_ECF_ERROR_CODES.DGII_NOT_A_MEMBER);\n }\n\n const allowedRoles = input.options.roles ?? DEFAULT_ROLES;\n const memberRoles = rolesOf(member);\n if (!memberRoles.some((role) => allowedRoles.includes(role))) {\n throw forbidden(\n DGII_ECF_ERROR_CODES.DGII_INSUFFICIENT_ROLE,\n `${DGII_ECF_ERROR_CODES.DGII_INSUFFICIENT_ROLE.message} (required one of: ${allowedRoles.join(', ')})`,\n );\n }\n\n if (\n input.organizationTaxPayerId !== null &&\n input.organizationTaxPayerId !== input.taxPayerId\n ) {\n throw forbidden(\n DGII_ECF_ERROR_CODES.DGII_TAXPAYER_ID_FORBIDDEN,\n `Organization ${input.organizationId} issues under ${input.organizationTaxPayerId}, not ${input.taxPayerId}`,\n );\n }\n};\n","/**\n * Minimal, tolerant readers for signed DGII XML.\n *\n * The plugin never parses a full document: it needs two facts — which taxpayer\n * issued it, and which root element it is — and both are readable with a single\n * match. This mirrors the DGII SDK's internal readers so both layers agree on\n * what a document says, without the plugin reaching into the SDK's non-public\n * modules.\n *\n * Two properties are load-bearing:\n *\n * 1. **Nothing is read from a comment.** A document is attacker-influenced input,\n * and `<!-- <RNCEmisor>…</RNCEmisor> -->` would otherwise be observable as the\n * issuer. That is not a cosmetic bug: the issuer check is what stops a member\n * of one organization from submitting a document for another taxpayer, so a\n * value an author can hide in a comment cannot be the value the check reads.\n * 2. **Tolerance, not sanitization.** Markup is skipped by scanning spans\n * (comment, processing instruction, declaration) rather than by deleting\n * patterns, because deleting markup and then searching the remainder is how\n * residue becomes a false root or a false issuer.\n */\n\nconst PATTERN_CACHE = new Map<string, RegExp>();\n\n/**\n * An attribute span may contain `>` inside quotes (`nota=\"a > b\"`), so each\n * quoted form gets its own alternative instead of a blanket `[^>]*`.\n */\nconst ATTRIBUTE_SPAN = `(?:[^>\"']|\"[^\"]*\"|'[^']*')*`;\n\nconst escapeRegExp = (value: string): string =>\n value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nconst elementPattern = (tag: string): RegExp => {\n const cached = PATTERN_CACHE.get(tag);\n if (cached !== undefined) {\n return cached;\n }\n const name = escapeRegExp(tag);\n const prefix = '(?:[\\\\w.-]+:)?';\n const pattern = new RegExp(\n `<${prefix}${name}${ATTRIBUTE_SPAN}>([\\\\s\\\\S]*?)<\\\\/${prefix}${name}\\\\s*>`,\n );\n PATTERN_CACHE.set(tag, pattern);\n return pattern;\n};\n\n/**\n * End (exclusive) of the non-element span that starts at `open`, or `-1` when\n * the `<` begins an element.\n *\n * An unterminated span swallows the rest of the document: an unterminated\n * comment is a malformed document, and treating its contents as markup is\n * exactly the behaviour this function exists to prevent.\n */\nconst skipNonElement = (xml: string, open: number): number => {\n if (xml.startsWith('<!--', open)) {\n const end = xml.indexOf('-->', open + 4);\n return end === -1 ? xml.length : end + 3;\n }\n if (xml.startsWith('<?', open)) {\n const end = xml.indexOf('?>', open + 2);\n return end === -1 ? xml.length : end + 2;\n }\n if (xml.startsWith('<!', open)) {\n // A declaration (DOCTYPE, or a CDATA section). The internal subset of a\n // DOCTYPE may contain `>` inside `[...]`, so the bracket depth is tracked.\n let depth = 0;\n for (let cursor = open + 2; cursor < xml.length; cursor += 1) {\n const character = xml[cursor];\n if (character === '[') {\n depth += 1;\n } else if (character === ']') {\n depth = Math.max(0, depth - 1);\n } else if (character === '>' && depth === 0) {\n return cursor + 1;\n }\n }\n return xml.length;\n }\n return -1;\n};\n\n/**\n * The document with every comment, processing instruction and declaration\n * removed — element markup untouched.\n *\n * Removing these spans means a later element match can only find real elements.\n * The scan is linear and allocation-light; DGII documents are small and a request\n * reads at most a handful of values from one.\n */\nconst withoutNonElementMarkup = (xml: string): string => {\n const parts: string[] = [];\n let index = 0;\n for (;;) {\n const open = xml.indexOf('<', index);\n if (open === -1) {\n parts.push(xml.slice(index));\n return parts.join('');\n }\n parts.push(xml.slice(index, open));\n const end = skipNonElement(xml, open);\n if (end === -1) {\n // A real element: keep the `<` and continue scanning after it, so a later\n // comment inside the element (or after it) is still removed.\n parts.push('<');\n index = open + 1;\n continue;\n }\n index = end;\n }\n};\n\n/**\n * Text content of the first `<tag>` element, tolerating a namespace prefix and\n * attributes. Returns `undefined` when the element is absent, self-closing or\n * blank. Matching is case-sensitive, as XML element names are.\n */\nexport const elementText = (xml: string, tag: string): string | undefined => {\n const text = elementPattern(tag).exec(withoutNonElementMarkup(xml))?.[1]?.trim();\n return text === undefined || text === '' ? undefined : text;\n};\n\nconst ROOT_PATTERN = /<\\s*(?:[A-Za-z_][\\w.-]*:)?([A-Za-z_][\\w.-]*)[\\s/>]/;\n\n/**\n * Local name of the document's root element, ignoring the XML declaration, a\n * DOCTYPE and any leading comments.\n *\n * DGII routing depends on the root: `<ECF>` goes to the general reception and\n * `<RFCE>` to the consumption-summary reception.\n */\nexport const rootElementName = (xml: string): string | undefined =>\n ROOT_PATTERN.exec(withoutNonElementMarkup(xml))?.[1];\n\n/** Issuer identifiers DGII uses across the e-CF, ACECF and ANECF schemas. */\nconst ISSUER_TAGS = ['RNCEmisor', 'RncEmisor'] as const;\n\n/**\n * The taxpayer id that issued the document, or `undefined` when the document\n * does not carry one.\n *\n * Both spellings are read because DGII's schemas disagree: the e-CF and ACECF\n * documents use `RNCEmisor` and the ANECF voiding request uses `RncEmisor`.\n */\nexport const issuerTaxPayerId = (xml: string): string | undefined => {\n for (const tag of ISSUER_TAGS) {\n const value = elementText(xml, tag);\n if (value !== undefined) {\n return value;\n }\n }\n return undefined;\n};\n","import { APIError } from 'better-auth/api';\nimport type { GenericEndpointContext } from '@better-auth/core';\nimport type { DgiiResult, ECF } from '@deuriib/dgii-ecf';\nimport { Signature } from '@deuriib/dgii-ecf';\nimport {\n badRequest,\n conflict,\n DGII_ECF_ERROR_CODES,\n forbidden,\n serverError,\n toApiError,\n} from '../errors.js';\nimport type { DgiiEcfClientProvider } from '../client-provider.js';\nimport { type DgiiEcfRequestScope, resolveRequestScope } from '../resolution.js';\nimport {\n createSubmissionStore,\n hashDocument,\n parseStoredResponse,\n planReplay,\n} from '../persistence.js';\nimport { normalizeTaxPayerId } from '../tax-payer.js';\nimport type { DgiiEcfOptions, DgiiEcfScope } from '../types.js';\nimport { elementText, issuerTaxPayerId, rootElementName } from '../xml.js';\n\n/** What every endpoint handler needs from the plugin closure. */\nexport interface DgiiEcfEndpointDeps {\n readonly options: DgiiEcfOptions;\n readonly provider: DgiiEcfClientProvider;\n}\n\nexport interface EndpointInput {\n taxPayerId?: string | undefined;\n organizationId?: string | undefined;\n}\n\nexport interface PreparedRequest {\n readonly scope: DgiiEcfRequestScope;\n readonly client: ECF;\n}\n\n/**\n * Resolve the scope, then the client — in that order.\n *\n * Authorization is part of resolution, so a caller who may not act on behalf of\n * a taxpayer never reaches the credential resolver and cannot learn, from timing\n * or error shape, whether that taxpayer has credentials configured.\n */\nexport const prepare = async (\n deps: DgiiEcfEndpointDeps,\n ctx: GenericEndpointContext,\n input: EndpointInput,\n): Promise<PreparedRequest> => {\n const scope = await resolveRequestScope({ ctx, options: deps.options, input });\n const client = await deps.provider.get(scope);\n return { scope, client };\n};\n\n/**\n * Unwrap a DGII SDK result, mapping a failure to an `APIError`.\n *\n * The SDK never throws domain errors; it returns `Result`. This is the single\n * place that turns `Err` into an HTTP response, so the status mapping stays\n * consistent across every endpoint.\n */\nexport const unwrap = <T>(result: DgiiResult<T>): T => {\n if (result.isErr()) {\n throw toApiError(result.error);\n }\n return result.value;\n};\n\n/**\n * Refuse a document whose issuer is not the taxpayer this request acts for.\n *\n * Without this check a member of organization A could build a perfectly valid\n * document for RNC B, have it signed with A's certificate (which is merely a\n * signing key, not an authorization), and submit it under A's credentials. The\n * issuer is the fiscal identity of the document, so it must equal the identity\n * the caller was authorized for.\n */\nexport const assertIssuer = (xml: string, taxPayerId: string): void => {\n const issuer = issuerTaxPayerId(xml);\n if (issuer === undefined) {\n throw badRequest(DGII_ECF_ERROR_CODES.DGII_DOCUMENT_UNREADABLE);\n }\n if (normalizeTaxPayerId(issuer) !== taxPayerId) {\n throw forbidden(\n DGII_ECF_ERROR_CODES.DGII_TAXPAYER_ID_MISMATCH,\n `The document is issued by ${issuer} but this request acts for ${taxPayerId}`,\n );\n }\n};\n\n/**\n * Sign a document server-side with the organization's key.\n *\n * The signature is what makes the credential model work: the browser sends the\n * document body, the server signs it, and the private key never leaves the\n * process. Signing requires the `credentials` resolver — a host that supplies a\n * ready-made client has kept the key outside the plugin's reach on purpose.\n */\nexport const signDocument = async (\n deps: DgiiEcfEndpointDeps,\n scope: DgiiEcfScope,\n xml: string,\n): Promise<string> => {\n const resolver = deps.options.credentials;\n if (resolver === undefined) {\n throw serverError(\n DGII_ECF_ERROR_CODES.DGII_CREDENTIALS_UNAVAILABLE,\n 'Server-side signing needs the `credentials` resolver; `getClient` hands the key to the host.',\n );\n }\n const material = await resolver(scope);\n if (material === null) {\n throw serverError(\n DGII_ECF_ERROR_CODES.DGII_CREDENTIALS_UNAVAILABLE,\n `No credentials were resolved for taxpayer ${scope.taxPayerId}`,\n );\n }\n const { key, cert } = material;\n if (key === undefined || cert === undefined) {\n // `P12ReaderData` keeps both fields optional, but a signature needs both.\n // Failing here names the real problem instead of surfacing a CERTIFICATE\n // error from underneath the signer.\n throw serverError(\n DGII_ECF_ERROR_CODES.DGII_CREDENTIALS_UNAVAILABLE,\n 'The resolved credentials carry no `key`/`cert` PEM pair, so the document cannot be signed',\n );\n }\n const signature = new Signature(key, cert);\n const root = rootElementName(xml);\n const signed =\n root === undefined ? signature.signXml(xml) : signature.signXml(xml, root);\n if (signed.isErr()) {\n throw new APIError('BAD_REQUEST', {\n message: signed.error.message,\n code: DGII_ECF_ERROR_CODES.DGII_SIGNING_FAILED.code,\n dgii: { code: signed.error.code },\n });\n }\n return signed.value;\n};\n\n/** The e-NCF a document refers to, used for the audit trail. */\nexport const documentEncf = (xml: string): string | null =>\n elementText(xml, 'eNCF') ??\n elementText(xml, 'SecuenciaeNCFDesde') ??\n elementText(xml, 'RangoNCF') ??\n null;\n\nexport interface RunSubmissionInput<T> {\n readonly ctx: GenericEndpointContext;\n readonly deps: DgiiEcfEndpointDeps;\n readonly scope: DgiiEcfRequestScope;\n /** Operation name recorded in the audit trail. */\n readonly operation: string;\n /** Signed XML about to be transmitted. */\n readonly xml: string;\n /** Caller-supplied idempotency key; defaults to the document hash. */\n readonly idempotencyKey?: string | undefined;\n /** The actual transmission. Only called when a replay is not possible. */\n readonly send: () => Promise<DgiiResult<T>>;\n}\n\nexport interface SubmissionOutcome<T> {\n readonly result: T;\n /** True when the answer came from the stored record, not from DGII. */\n readonly replayed: boolean;\n /** Row id of the audit record, when persistence is enabled. */\n readonly submissionId: string | null;\n}\n\nconst trackIdOf = (value: unknown): string | null => {\n if (typeof value !== 'object' || value === null) {\n return null;\n }\n const candidate = (value as { trackId?: unknown }).trackId;\n return typeof candidate === 'string' && candidate !== '' ? candidate : null;\n};\n\n/**\n * Run a submission through the durable replay guard and the audit trail.\n *\n * Order matters and is the whole point: look for a replay, write the pending\n * row, transmit, then record the outcome. A crash between \"write pending\" and\n * \"record outcome\" leaves a row that makes the next attempt refuse instead of\n * guessing — a duplicate fiscal document is worse than a failed request.\n */\nexport const runSubmission = async <T>({\n ctx,\n deps,\n scope,\n operation,\n xml,\n idempotencyKey,\n send,\n}: RunSubmissionInput<T>): Promise<SubmissionOutcome<T>> => {\n const store = createSubmissionStore(ctx, deps.options.persistence);\n const documentHash = hashDocument(xml);\n const replayKey = idempotencyKey ?? documentHash;\n\n if (store.enabled) {\n const existing = await store.findReplay(scope.taxPayerId, replayKey);\n const decision = planReplay(existing);\n if (decision.kind === 'conflict') {\n throw conflict(\n DGII_ECF_ERROR_CODES.DGII_IDEMPOTENCY_IN_FLIGHT,\n `A submission for this document is still in flight (record ${existing?.id ?? 'unknown'}). Reconcile it by e-NCF before retrying.`,\n );\n }\n if (decision.kind === 'replay') {\n return {\n result: parseStoredResponse(decision.record) as T,\n replayed: true,\n submissionId: decision.record.id,\n };\n }\n }\n\n const submissionId = await store.begin({\n organizationId: scope.organizationId,\n taxPayerId: scope.taxPayerId,\n userId: scope.userId,\n environment: scope.environment,\n operation,\n idempotencyKey: replayKey,\n encf: documentEncf(xml),\n documentHash,\n });\n\n let result: T;\n try {\n result = unwrap(await send());\n } catch (error) {\n const errorCode =\n error instanceof APIError\n ? String(error.body?.code ?? error.status)\n : error instanceof Error\n ? error.name\n : 'UNKNOWN';\n await store.complete(submissionId, { status: 'failed', errorCode });\n throw error;\n }\n\n await store.complete(submissionId, {\n status: 'succeeded',\n trackId: trackIdOf(result),\n response: result,\n });\n\n return { result, replayed: false, submissionId };\n};\n\n/** The scope fields every response echoes back. */\nexport const scopeEcho = (scope: DgiiEcfScope) => ({\n taxPayerId: scope.taxPayerId,\n organizationId: scope.organizationId,\n environment: scope.environment,\n});\n","import { createAuthEndpoint, sessionMiddleware } from 'better-auth/api';\nimport * as z from 'zod';\nimport type {\n B2BCommercialApprovalResponse,\n CommercialApprovalResponse,\n InvoiceResponse,\n} from '@deuriib/dgii-ecf';\nimport {\n assertIssuer,\n type DgiiEcfEndpointDeps,\n documentEncf,\n prepare,\n runSubmission,\n scopeEcho,\n signDocument,\n unwrap,\n} from './shared.js';\n\n/**\n * Document transmission endpoints.\n *\n * Every one of them takes XML — signed already, or signable — never a JSON\n * invoice model: building a DGII document is a domain problem the host owns,\n * while signing and transmitting are the plugin's. `sign: true` moves the\n * signature server-side, next to the key, which is the reason a browser can call\n * these endpoints at all without ever holding a certificate.\n */\n\nconst scopeShape = {\n taxPayerId: z.string().min(1).optional().meta({\n description:\n 'Taxpayer id (RNC / cédula) to act for. Overrides the organization field for this request only.',\n }),\n organizationId: z.string().min(1).optional().meta({\n description:\n 'Organization to act for. Defaults to the session active organization.',\n }),\n};\n\nconst documentShape = {\n ...scopeShape,\n xml: z.string().min(1).meta({ description: 'The DGII document, as XML.' }),\n fileName: z.string().min(1).max(255).optional().meta({\n description: 'Multipart file name sent to DGII. Defaults to the document e-NCF.',\n }),\n sign: z.boolean().optional().meta({\n description:\n 'Sign the XML server-side with the organization key before transmitting. Requires the `credentials` resolver.',\n }),\n idempotencyKey: z.string().min(1).max(200).optional().meta({\n description:\n 'Replay guard key. Defaults to the SHA-256 of the document, so retrying the same document never double-issues.',\n }),\n};\n\nconst fileNameFor = (xml: string, fallback: string): string => {\n const encf = documentEncf(xml);\n return encf === null ? `${fallback}.xml` : `${encf}.xml`;\n};\n\n/** POST /dgii-ecf/documents — route to the reception the document belongs to. */\nexport const sendDocument = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents',\n {\n method: 'POST',\n body: z.object({\n ...documentShape,\n buyerHost: z.string().url().optional().meta({\n description:\n 'Deliver directly to the buyer Sender↔Receiver host instead of DGII.',\n }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const xml =\n ctx.body.sign === true\n ? await signDocument(deps, scope, ctx.body.xml)\n : ctx.body.xml;\n assertIssuer(xml, scope.taxPayerId);\n\n const outcome = await runSubmission({\n ctx,\n deps,\n scope,\n operation: 'sendDocument',\n xml,\n idempotencyKey: ctx.body.idempotencyKey,\n send: () =>\n client.sendDocument(\n xml,\n ctx.body.fileName ?? fileNameFor(xml, 'document'),\n ctx.body.buyerHost,\n ),\n });\n\n return ctx.json({\n ...scopeEcho(scope),\n submissionId: outcome.submissionId,\n replayed: outcome.replayed,\n result: outcome.result,\n });\n },\n );\n\n/** POST /dgii-ecf/documents/electronic — general e-CF reception only. */\nexport const sendElectronicDocument = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents/electronic',\n {\n method: 'POST',\n body: z.object({\n ...documentShape,\n buyerHost: z.string().url().optional(),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const xml =\n ctx.body.sign === true\n ? await signDocument(deps, scope, ctx.body.xml)\n : ctx.body.xml;\n assertIssuer(xml, scope.taxPayerId);\n\n const outcome = await runSubmission<InvoiceResponse>({\n ctx,\n deps,\n scope,\n operation: 'sendElectronicDocument',\n xml,\n idempotencyKey: ctx.body.idempotencyKey,\n send: () =>\n client.sendElectronicDocument(\n xml,\n ctx.body.fileName ?? fileNameFor(xml, 'ecf'),\n ctx.body.buyerHost,\n ),\n });\n\n return ctx.json({\n ...scopeEcho(scope),\n submissionId: outcome.submissionId,\n replayed: outcome.replayed,\n result: outcome.result,\n });\n },\n );\n\n/** POST /dgii-ecf/documents/summary — RFCE summary invoices only. */\nexport const sendSummary = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents/summary',\n {\n method: 'POST',\n body: z.object(documentShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const xml =\n ctx.body.sign === true\n ? await signDocument(deps, scope, ctx.body.xml)\n : ctx.body.xml;\n assertIssuer(xml, scope.taxPayerId);\n\n const outcome = await runSubmission({\n ctx,\n deps,\n scope,\n operation: 'sendSummary',\n xml,\n idempotencyKey: ctx.body.idempotencyKey,\n send: () =>\n client.sendSummary(xml, ctx.body.fileName ?? fileNameFor(xml, 'summary')),\n });\n\n return ctx.json({\n ...scopeEcho(scope),\n submissionId: outcome.submissionId,\n replayed: outcome.replayed,\n result: outcome.result,\n });\n },\n );\n\n/** POST /dgii-ecf/documents/commercial-approval — ACECF. */\nexport const sendCommercialApproval = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents/commercial-approval',\n {\n method: 'POST',\n body: z.object({\n ...documentShape,\n buyerHost: z.string().url().optional().meta({\n description: 'Deliver the approval directly to the issuer host.',\n }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const xml =\n ctx.body.sign === true\n ? await signDocument(deps, scope, ctx.body.xml)\n : ctx.body.xml;\n assertIssuer(xml, scope.taxPayerId);\n\n const buyerHost = ctx.body.buyerHost;\n const outcome = await runSubmission<\n CommercialApprovalResponse | B2BCommercialApprovalResponse\n >({\n ctx,\n deps,\n scope,\n operation: 'sendCommercialApproval',\n xml,\n idempotencyKey: ctx.body.idempotencyKey,\n send: () => {\n const fileName = ctx.body.fileName ?? fileNameFor(xml, 'approval');\n return buyerHost === undefined\n ? client.sendCommercialApproval(xml, fileName)\n : client.sendCommercialApproval(xml, fileName, buyerHost);\n },\n });\n\n return ctx.json({\n ...scopeEcho(scope),\n submissionId: outcome.submissionId,\n replayed: outcome.replayed,\n result: outcome.result,\n });\n },\n );\n\n/** POST /dgii-ecf/documents/void-range — ANECF range voiding. */\nexport const voidENCF = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents/void-range',\n {\n method: 'POST',\n body: z.object(documentShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const xml =\n ctx.body.sign === true\n ? await signDocument(deps, scope, ctx.body.xml)\n : ctx.body.xml;\n assertIssuer(xml, scope.taxPayerId);\n\n const outcome = await runSubmission({\n ctx,\n deps,\n scope,\n operation: 'voidENCF',\n xml,\n idempotencyKey: ctx.body.idempotencyKey,\n send: () =>\n client.voidENCF(xml, ctx.body.fileName ?? fileNameFor(xml, 'void-range')),\n });\n\n return ctx.json({\n ...scopeEcho(scope),\n submissionId: outcome.submissionId,\n replayed: outcome.replayed,\n result: outcome.result,\n });\n },\n );\n\n/**\n * POST /dgii-ecf/documents/reconcile — resolve a submission whose outcome is\n * unknown.\n *\n * This is the counterpart of the replay guard: when a pending record exists the\n * caller reconciles by e-NCF instead of re-sending, and DGII — not the plugin —\n * decides whether the document landed.\n */\nexport const reconcileSubmission = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/documents/reconcile',\n {\n method: 'POST',\n body: z.object({\n ...scopeShape,\n xml: z.string().min(1).meta({ description: 'The signed document, as XML.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n assertIssuer(ctx.body.xml, scope.taxPayerId);\n\n const result = unwrap(await client.reconcileSubmission(ctx.body.xml));\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n","import { createAuthEndpoint, sessionMiddleware } from 'better-auth/api';\nimport * as z from 'zod';\nimport { type DgiiEcfEndpointDeps, prepare, scopeEcho, unwrap } from './shared.js';\n\n/**\n * Read-only DGII queries: tracking, existence checks and the service\n * directories.\n *\n * None of them mutate fiscal state, so none of them touch the replay guard, and\n * each one carries its own taxpayer scope check — a track id is not a secret, so\n * the only thing standing between organizations is the authorization performed\n * during scope resolution.\n */\n\nconst scopeShape = {\n taxPayerId: z.string().min(1).optional().meta({\n description:\n 'Taxpayer id (RNC / cédula) to act for. Overrides the organization field.',\n }),\n organizationId: z.string().min(1).optional().meta({\n description:\n 'Organization to act for. Defaults to the session active organization.',\n }),\n};\n\n/** GET /dgii-ecf/tracks — DGII per-track result (`consultaresultado`). */\nexport const trackStatus = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/tracks',\n {\n method: 'GET',\n query: z.object({\n ...scopeShape,\n trackId: z.string().min(1).meta({ description: 'DGII track id.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const result = unwrap(await client.statusTrackId(ctx.query.trackId));\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n\n/**\n * POST /dgii-ecf/inquiries/status — DGII existence read (`consultaestado`).\n *\n * DGII answers \"No encontrado\" for a document it never received, so this is the\n * read a caller uses to decide whether a pending submission landed.\n */\nexport const inquiryStatus = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/inquiries/status',\n {\n method: 'POST',\n body: z.object({\n ...scopeShape,\n ncf: z.string().min(1).meta({ description: 'The e-NCF to look up.' }),\n buyerTaxPayerId: z\n .string()\n .min(1)\n .optional()\n .meta({ description: 'Buyer RNC, when DGII needs it to disambiguate.' }),\n securityCode: z\n .string()\n .min(1)\n .optional()\n .meta({ description: 'Six-digit security code of the document.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const result = unwrap(\n await client.inquiryStatus(\n scope.taxPayerId,\n ctx.body.ncf,\n ctx.body.buyerTaxPayerId,\n ctx.body.securityCode,\n ),\n );\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n\n/** POST /dgii-ecf/inquiries/tracks — every track DGII knows for an e-NCF. */\nexport const trackStatuses = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/inquiries/tracks',\n {\n method: 'POST',\n body: z.object({\n ...scopeShape,\n encf: z.string().min(1).meta({ description: 'The e-NCF to list tracks for.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const result = unwrap(\n await client.trackStatuses(scope.taxPayerId, ctx.body.encf),\n );\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n\n/**\n * POST /dgii-ecf/inquiries/summary — RFCE inquiry.\n *\n * Production only: DGII does not publish the consumption-summary inquiry in the\n * certification environments, and the SDK refuses it there rather than returning\n * an empty answer that would read as \"not found\".\n */\nexport const summaryInvoiceInquiry = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/inquiries/summary',\n {\n method: 'POST',\n body: z.object({\n ...scopeShape,\n encf: z.string().min(1).meta({ description: 'The RFCE e-NCF to look up.' }),\n securityCode: z\n .string()\n .min(1)\n .meta({ description: 'Six-digit security code of the summary invoice.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const result = unwrap(\n await client.getSummaryInvoiceInquiry(\n scope.taxPayerId,\n ctx.body.encf,\n ctx.body.securityCode,\n ),\n );\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n\n/** GET /dgii-ecf/directories/customers — the service directory for one RNC. */\nexport const customerDirectory = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/directories/customers',\n {\n method: 'GET',\n query: z.object({\n ...scopeShape,\n rnc: z.string().min(1).optional().meta({\n description:\n 'RNC to look up. Defaults to the taxpayer this request acts for.',\n }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const result = unwrap(\n await client.getCustomerDirectory(ctx.query.rnc ?? scope.taxPayerId),\n );\n return ctx.json({ ...scopeEcho(scope), result: result ?? [] });\n },\n );\n\n/** GET /dgii-ecf/directories — every receiver that publishes service URLs. */\nexport const directoryListing = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/directories/all',\n {\n method: 'GET',\n query: z.object(scopeShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const result = unwrap(await client.getDirectoryListing());\n return ctx.json({ ...scopeEcho(scope), result });\n },\n );\n","import { createAuthEndpoint, sessionMiddleware } from 'better-auth/api';\nimport * as z from 'zod';\nimport { StatusEnvironment } from '@deuriib/dgii-ecf';\nimport { type DgiiEcfEndpointDeps, prepare, scopeEcho, unwrap } from './shared.js';\nimport { DGII_ECF_ERROR_CODES, serverError } from '../errors.js';\n\n/**\n * DGII operational endpoints.\n *\n * The status service answers \"is DGII up right now\", which a back office needs\n * before it lets anybody transmit. It takes an API key instead of the bearer\n * token, so it works without a session against DGII — but it still needs the\n * plugin's own session, because where an application exposes DGII health is a\n * business decision, not a public endpoint's.\n */\n\nconst scopeShape = {\n taxPayerId: z.string().min(1).optional().meta({\n description:\n 'Taxpayer id (RNC / cédula) to act for. Overrides the organization field.',\n }),\n organizationId: z.string().min(1).optional().meta({\n description:\n 'Organization to act for. Defaults to the session active organization.',\n }),\n};\n\n/** Environments the status service names with its own numeric codes. */\nconst STATUS_ENVIRONMENTS = {\n precertification: StatusEnvironment.PreCertification,\n production: StatusEnvironment.Production,\n certification: StatusEnvironment.Certification,\n} as const;\n\nconst requireStatusKey = (deps: DgiiEcfEndpointDeps): void => {\n if (deps.provider.constructsClients && deps.options.status?.apiKey === undefined) {\n throw serverError(DGII_ECF_ERROR_CODES.DGII_STATUS_API_KEY_REQUIRED);\n }\n};\n\n/**\n * POST /dgii-ecf/authenticate — warm the DGII token for a taxpayer.\n *\n * The token itself is never returned. It is a bearer credential for DGII, valid\n * for the certificate that minted it; handing it to a browser would undo the\n * reason this plugin exists. Callers get the validity window instead, which is\n * what a UI actually shows.\n */\nexport const authenticate = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/authenticate',\n {\n method: 'POST',\n body: z.object({\n ...scopeShape,\n buyerHost: z\n .string()\n .url()\n .optional()\n .meta({ description: 'Authenticate against a buyer Sender↔Receiver host.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope, client } = await prepare(deps, ctx, ctx.body);\n const token = unwrap(await client.authenticate(ctx.body.buyerHost));\n return ctx.json({\n ...scopeEcho(scope),\n issuedAt: token.expedido,\n expiresAt: token.expira,\n });\n },\n );\n\n/** GET /dgii-ecf/service-status — operational status of every DGII service. */\nexport const serviceStatus = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/service-status',\n {\n method: 'GET',\n query: z.object(scopeShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n requireStatusKey(deps);\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const services = unwrap(await client.getServiceStatus());\n return ctx.json({ ...scopeEcho(scope), services });\n },\n );\n\n/** GET /dgii-ecf/maintenance-windows — DGII scheduled maintenance. */\nexport const maintenanceWindows = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/maintenance-windows',\n {\n method: 'GET',\n query: z.object(scopeShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n requireStatusKey(deps);\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const windows = unwrap(await client.getMaintenanceWindows());\n return ctx.json({ ...scopeEcho(scope), windows });\n },\n );\n\n/** GET /dgii-ecf/service-availability — is one environment inside a window. */\nexport const serviceAvailability = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/service-availability',\n {\n method: 'GET',\n query: z.object({\n ...scopeShape,\n environment: z\n .enum(['precertification', 'production', 'certification'])\n .meta({ description: 'DGII environment to query.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n requireStatusKey(deps);\n const { scope, client } = await prepare(deps, ctx, ctx.query);\n const result = unwrap(\n await client.checkServiceAvailability(\n STATUS_ENVIRONMENTS[ctx.query.environment],\n ),\n );\n return ctx.json({\n ...scopeEcho(scope),\n environmentChecked: ctx.query.environment,\n estado: result.estado,\n });\n },\n );\n","import { createAuthEndpoint, sessionMiddleware } from 'better-auth/api';\nimport * as z from 'zod';\nimport { type DgiiEcfEndpointDeps, prepare, scopeEcho } from './shared.js';\nimport { createSubmissionStore } from '../persistence.js';\n\n/**\n * Introspection endpoints: \"which taxpayer will this call use\" and \"what has\n * already been submitted\".\n *\n * Both exist because the two hardest questions in a multi-tenant fiscal\n * integration are answered by the server, not by the client's own bookkeeping.\n */\n\nconst scopeShape = {\n taxPayerId: z.string().min(1).optional().meta({\n description:\n 'Taxpayer id (RNC / cédula) to act for. Overrides the organization field.',\n }),\n organizationId: z.string().min(1).optional().meta({\n description:\n 'Organization to act for. Defaults to the session active organization.',\n }),\n};\n\n/**\n * GET /dgii-ecf/taxpayer — the resolved identity of the next call.\n *\n * `source` says which of the three resolution modes answered, which is what a\n * UI needs to explain itself (\"this invoice will be issued as RNC … because your\n * organization stores it\") instead of guessing.\n */\nexport const resolveTaxPayer = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/taxpayer',\n {\n method: 'GET',\n query: z.object(scopeShape),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope } = await prepare(deps, ctx, ctx.query);\n return ctx.json({\n taxPayerId: scope.taxPayerId,\n organizationId: scope.organizationId,\n organizationTaxPayerId: scope.organizationTaxPayerId,\n source: scope.source,\n environment: scope.environment,\n });\n },\n );\n\n/** GET /dgii-ecf/submissions — the audit trail for the scope in question. */\nexport const listSubmissions = (deps: DgiiEcfEndpointDeps) =>\n createAuthEndpoint(\n '/dgii-ecf/submissions',\n {\n method: 'GET',\n query: z.object({\n ...scopeShape,\n limit: z.coerce.number().int().min(1).max(100).optional().meta({\n description: 'Maximum number of records to return. Defaults to 20.',\n }),\n status: z\n .enum(['pending', 'succeeded', 'failed'])\n .optional()\n .meta({ description: 'Filter by record status.' }),\n }),\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const { scope } = await prepare(deps, ctx, ctx.query);\n const store = createSubmissionStore(ctx, deps.options.persistence);\n\n // Filtering happens here rather than in the query: the adapter's `where`\n // set is built from authorized values only, so a caller cannot widen the\n // listing by inventing an organization id.\n const records = await store.list({\n organizationId: scope.organizationId,\n taxPayerId: scope.organizationId === null ? scope.taxPayerId : null,\n limit: Math.min(ctx.query.limit ?? 20, 100),\n });\n\n const filtered =\n ctx.query.status === undefined\n ? records\n : records.filter((record) => record.status === ctx.query.status);\n\n return ctx.json({\n ...scopeEcho(scope),\n submissions: filtered.map((record) => ({\n id: record.id,\n operation: record.operation,\n status: record.status,\n taxPayerId: record.taxPayerId,\n organizationId: record.organizationId ?? null,\n environment: record.environment,\n encf: record.encf ?? null,\n trackId: record.trackId ?? null,\n documentHash: record.documentHash ?? null,\n errorCode: record.errorCode ?? null,\n createdAt: record.createdAt ?? null,\n })),\n });\n },\n );\n","import type { BetterAuthPlugin } from 'better-auth';\nimport type { DBFieldAttribute } from '@better-auth/core/db';\nimport { createClientProvider, type DgiiEcfClientProvider } from './client-provider.js';\nimport { DGII_ECF_ERROR_CODES } from './errors.js';\nimport { SUBMISSION_MODEL } from './persistence.js';\nimport type { DgiiEcfOptions } from './types.js';\nimport {\n sendCommercialApproval,\n sendDocument,\n sendElectronicDocument,\n sendSummary,\n reconcileSubmission,\n voidENCF,\n} from './endpoints/documents.js';\nimport {\n customerDirectory,\n directoryListing,\n inquiryStatus,\n summaryInvoiceInquiry,\n trackStatus,\n trackStatuses,\n} from './endpoints/inquiries.js';\nimport {\n authenticate,\n maintenanceWindows,\n serviceAvailability,\n serviceStatus,\n} from './endpoints/status.js';\nimport { listSubmissions, resolveTaxPayer } from './endpoints/audit.js';\n\n/**\n * The `organization` field the plugin reads.\n *\n * `input: false` because this definition is used when *the plugin* registers the\n * field (the read-only `organization.extendSchema` mode): the value is written\n * by another system, so Better Auth's input parser must not accept it.\n */\nconst readonlyTaxPayerIdField = (): DBFieldAttribute => ({\n type: 'string',\n required: false,\n input: false,\n returned: true,\n unique: false,\n});\n\n/**\n * Fragments to drop into `organization({ schema })`.\n *\n * Exported so an application declares the field exactly once, with exactly the\n * definition this plugin expects. This is the supported way to make the value\n * *writable*: the organization plugin builds its create/update schemas from its\n * own `additionalFields`, so a field registered only by this plugin's schema is\n * readable but not accepted by `organization.update`.\n *\n * @example\n * ```ts\n * organization({ schema: { organization: dgiiEcfOrganizationSchema() } })\n * ```\n */\nexport const dgiiEcfOrganizationSchema = (\n field = 'taxPayerId',\n): {\n additionalFields: Record<string, DBFieldAttribute>;\n} => ({\n additionalFields: {\n [field]: {\n type: 'string',\n required: false,\n // Writable: this fragment is declared by the organization plugin, which\n // is what makes `organization.create` / `organization.update` accept it.\n input: true,\n returned: true,\n unique: false,\n },\n },\n});\n\n/**\n * Better Auth plugin wiring the DGII e-CF SDK into an authenticated API.\n *\n * Three responsibilities, and deliberately no fourth:\n *\n * 1. **Identity** — decide *which* taxpayer a call acts for: the request, the\n * organization, or a server-side mapping, authorized in that order.\n * 2. **Credentials** — resolve key material per taxpayer through a server-side\n * callback, so no certificate or bearer token ever reaches a browser.\n * 3. **Durability** — record submissions, so a retry is replay-safe across\n * restarts and the fiscal audit trail survives the process.\n *\n * Document *content* stays the host's job: the plugin signs and transmits XML,\n * it does not model invoices.\n */\nexport const dgiiEcf = (options: DgiiEcfOptions = {}) => {\n // Built once: the provider owns the client cache, so it must outlive requests.\n const provider = createClientProvider(options);\n const deps = { options, provider } as const;\n\n const schema: NonNullable<BetterAuthPlugin['schema']> = {\n [SUBMISSION_MODEL]: {\n modelName: SUBMISSION_MODEL,\n fields: {\n organizationId: { type: 'string', required: false },\n taxPayerId: { type: 'string', required: true },\n userId: { type: 'string', required: true },\n environment: { type: 'string', required: true },\n operation: { type: 'string', required: true },\n status: { type: 'string', required: true },\n idempotencyKey: { type: 'string', required: false },\n encf: { type: 'string', required: false },\n trackId: { type: 'string', required: false },\n documentHash: { type: 'string', required: false },\n errorCode: { type: 'string', required: false },\n response: { type: 'string', required: false },\n // Better Auth does not add timestamps implicitly: a plugin table that\n // wants them declares them. `createdAt` orders the replay lookup and the\n // audit listing; `updatedAt` records when a submission was closed.\n createdAt: { type: 'date', required: true, defaultValue: () => new Date() },\n updatedAt: { type: 'date', required: false, onUpdate: () => new Date() },\n },\n indexes: [\n // The replay lookup: taxpayer + key must be a cheap read.\n { fields: ['taxPayerId', 'idempotencyKey'] },\n // The audit listing: \"everything this organization submitted\".\n { fields: ['organizationId', 'createdAt'] },\n ],\n },\n };\n\n if (options.organization?.extendSchema === true) {\n schema.organization = {\n fields: {\n [options.organization.field ?? 'taxPayerId']: readonlyTaxPayerIdField(),\n },\n };\n }\n\n // The plugin literal stays exactly a `BetterAuthPlugin` so Better Auth can\n // infer its endpoints; the provider is attached afterwards because widening\n // the return type would erase that inference.\n const plugin = {\n id: 'dgii-ecf',\n $ERROR_CODES: DGII_ECF_ERROR_CODES,\n schema,\n endpoints: {\n // Identity\n dgiiEcfResolveTaxPayer: resolveTaxPayer(deps),\n // Session / token\n dgiiEcfAuthenticate: authenticate(deps),\n // Documents\n dgiiEcfSendDocument: sendDocument(deps),\n dgiiEcfSendElectronicDocument: sendElectronicDocument(deps),\n dgiiEcfSendSummary: sendSummary(deps),\n dgiiEcfSendCommercialApproval: sendCommercialApproval(deps),\n dgiiEcfVoidENCF: voidENCF(deps),\n dgiiEcfReconcileSubmission: reconcileSubmission(deps),\n // Queries\n dgiiEcfTrackStatus: trackStatus(deps),\n dgiiEcfInquiryStatus: inquiryStatus(deps),\n dgiiEcfTrackStatuses: trackStatuses(deps),\n dgiiEcfSummaryInvoiceInquiry: summaryInvoiceInquiry(deps),\n dgiiEcfCustomerDirectory: customerDirectory(deps),\n dgiiEcfDirectoryListing: directoryListing(deps),\n // DGII operations\n dgiiEcfServiceStatus: serviceStatus(deps),\n dgiiEcfMaintenanceWindows: maintenanceWindows(deps),\n dgiiEcfServiceAvailability: serviceAvailability(deps),\n // Audit\n dgiiEcfListSubmissions: listSubmissions(deps),\n },\n rateLimit: [\n {\n // Fiscal transmissions are metered by DGII and expensive to retry, so\n // the whole surface gets a conservative per-window budget.\n window: 60,\n max: 60,\n pathMatcher: (path: string) => path.startsWith('/dgii-ecf'),\n },\n ],\n } satisfies BetterAuthPlugin;\n\n return Object.assign(plugin, { clientProvider: provider });\n};\n\n/**\n * Public type of the plugin.\n *\n * `ReturnType` rather than an interface on purpose: an explicit interface would\n * widen `endpoints` to an index signature and destroy the client-side inference\n * that makes a renamed path a compile error.\n */\nexport type DgiiEcfPlugin = ReturnType<typeof dgiiEcf>;\n\n/** Exposed so a host can drop a cached client after rotating a certificate. */\nexport type { DgiiEcfClientProvider };\n\ndeclare module '@better-auth/core' {\n interface BetterAuthPluginRegistry<AuthOptions, Options> {\n 'dgii-ecf': {\n creator: typeof dgiiEcf;\n };\n }\n}\n"]}
@@ -0,0 +1,40 @@
1
+ export { a as DgiiEcfAuthorizer, b as DgiiEcfClientCacheOptions, c as DgiiEcfClientProvider, d as DgiiEcfClientResolver, e as DgiiEcfCredentialsResolver, f as DgiiEcfOptions, g as DgiiEcfOrganizationOptions, h as DgiiEcfPersistenceOptions, D as DgiiEcfPlugin, i as DgiiEcfScope, j as DgiiEcfStatusOptions, k as DgiiEcfSubmissionStore, l as DgiiEcfTaxPayerIdResolver, m as DgiiEcfTaxPayerIdSource, S as SUBMISSION_MODEL, n as SubmissionRecord, o as SubmissionStatus, T as TaxPayerIdValidation, p as TaxPayerIdValidator, q as dgiiEcf, r as dgiiEcfOrganizationSchema, s as isTaxPayerIdShape, t as normalizeTaxPayerId } from './plugin-BVYTmUJU.cjs';
2
+ import * as _better_auth_core_utils_error_codes from '@better-auth/core/utils/error-codes';
3
+ export { Environment } from '@deuriib/dgii-ecf';
4
+ import 'better-auth';
5
+ import 'zod/v4/core';
6
+ import '@better-auth/core/db';
7
+
8
+ /**
9
+ * Error codes this plugin can return.
10
+ *
11
+ * They are declared through `defineErrorCodes` so they flow into Better Auth's
12
+ * own type surface (`auth.$ERROR_CODES`, client `error.code`) and so the keys
13
+ * are constrained to UPPER_SNAKE_CASE at compile time. Every code describes a
14
+ * condition the plugin itself decided on; a failure DGII produced is reported
15
+ * as {@link DGII_ECF_ERROR_CODES.DGII_REQUEST_FAILED} with the upstream detail
16
+ * attached, never smuggled into a success payload.
17
+ */
18
+ declare const DGII_ECF_ERROR_CODES: {
19
+ DGII_SESSION_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_SESSION_REQUIRED">;
20
+ DGII_TAXPAYER_ID_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_REQUIRED">;
21
+ DGII_TAXPAYER_ID_INVALID: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_INVALID">;
22
+ DGII_TAXPAYER_ID_MISMATCH: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_MISMATCH">;
23
+ DGII_TAXPAYER_ID_FORBIDDEN: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_FORBIDDEN">;
24
+ DGII_ORGANIZATION_NOT_FOUND: _better_auth_core_utils_error_codes.RawError<"DGII_ORGANIZATION_NOT_FOUND">;
25
+ DGII_ORGANIZATION_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_ORGANIZATION_REQUIRED">;
26
+ DGII_NOT_A_MEMBER: _better_auth_core_utils_error_codes.RawError<"DGII_NOT_A_MEMBER">;
27
+ DGII_INSUFFICIENT_ROLE: _better_auth_core_utils_error_codes.RawError<"DGII_INSUFFICIENT_ROLE">;
28
+ DGII_CREDENTIALS_UNAVAILABLE: _better_auth_core_utils_error_codes.RawError<"DGII_CREDENTIALS_UNAVAILABLE">;
29
+ DGII_CLIENT_NOT_CONFIGURED: _better_auth_core_utils_error_codes.RawError<"DGII_CLIENT_NOT_CONFIGURED">;
30
+ DGII_STATUS_API_KEY_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_STATUS_API_KEY_REQUIRED">;
31
+ DGII_DOCUMENT_UNREADABLE: _better_auth_core_utils_error_codes.RawError<"DGII_DOCUMENT_UNREADABLE">;
32
+ DGII_SIGNING_FAILED: _better_auth_core_utils_error_codes.RawError<"DGII_SIGNING_FAILED">;
33
+ DGII_REQUEST_FAILED: _better_auth_core_utils_error_codes.RawError<"DGII_REQUEST_FAILED">;
34
+ DGII_SUBMISSION_NOT_FOUND: _better_auth_core_utils_error_codes.RawError<"DGII_SUBMISSION_NOT_FOUND">;
35
+ DGII_PERSISTENCE_UNAVAILABLE: _better_auth_core_utils_error_codes.RawError<"DGII_PERSISTENCE_UNAVAILABLE">;
36
+ DGII_IDEMPOTENCY_IN_FLIGHT: _better_auth_core_utils_error_codes.RawError<"DGII_IDEMPOTENCY_IN_FLIGHT">;
37
+ };
38
+ type DgiiEcfErrorCode = keyof typeof DGII_ECF_ERROR_CODES;
39
+
40
+ export { DGII_ECF_ERROR_CODES, type DgiiEcfErrorCode };
@@ -0,0 +1,40 @@
1
+ export { a as DgiiEcfAuthorizer, b as DgiiEcfClientCacheOptions, c as DgiiEcfClientProvider, d as DgiiEcfClientResolver, e as DgiiEcfCredentialsResolver, f as DgiiEcfOptions, g as DgiiEcfOrganizationOptions, h as DgiiEcfPersistenceOptions, D as DgiiEcfPlugin, i as DgiiEcfScope, j as DgiiEcfStatusOptions, k as DgiiEcfSubmissionStore, l as DgiiEcfTaxPayerIdResolver, m as DgiiEcfTaxPayerIdSource, S as SUBMISSION_MODEL, n as SubmissionRecord, o as SubmissionStatus, T as TaxPayerIdValidation, p as TaxPayerIdValidator, q as dgiiEcf, r as dgiiEcfOrganizationSchema, s as isTaxPayerIdShape, t as normalizeTaxPayerId } from './plugin-BVYTmUJU.js';
2
+ import * as _better_auth_core_utils_error_codes from '@better-auth/core/utils/error-codes';
3
+ export { Environment } from '@deuriib/dgii-ecf';
4
+ import 'better-auth';
5
+ import 'zod/v4/core';
6
+ import '@better-auth/core/db';
7
+
8
+ /**
9
+ * Error codes this plugin can return.
10
+ *
11
+ * They are declared through `defineErrorCodes` so they flow into Better Auth's
12
+ * own type surface (`auth.$ERROR_CODES`, client `error.code`) and so the keys
13
+ * are constrained to UPPER_SNAKE_CASE at compile time. Every code describes a
14
+ * condition the plugin itself decided on; a failure DGII produced is reported
15
+ * as {@link DGII_ECF_ERROR_CODES.DGII_REQUEST_FAILED} with the upstream detail
16
+ * attached, never smuggled into a success payload.
17
+ */
18
+ declare const DGII_ECF_ERROR_CODES: {
19
+ DGII_SESSION_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_SESSION_REQUIRED">;
20
+ DGII_TAXPAYER_ID_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_REQUIRED">;
21
+ DGII_TAXPAYER_ID_INVALID: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_INVALID">;
22
+ DGII_TAXPAYER_ID_MISMATCH: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_MISMATCH">;
23
+ DGII_TAXPAYER_ID_FORBIDDEN: _better_auth_core_utils_error_codes.RawError<"DGII_TAXPAYER_ID_FORBIDDEN">;
24
+ DGII_ORGANIZATION_NOT_FOUND: _better_auth_core_utils_error_codes.RawError<"DGII_ORGANIZATION_NOT_FOUND">;
25
+ DGII_ORGANIZATION_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_ORGANIZATION_REQUIRED">;
26
+ DGII_NOT_A_MEMBER: _better_auth_core_utils_error_codes.RawError<"DGII_NOT_A_MEMBER">;
27
+ DGII_INSUFFICIENT_ROLE: _better_auth_core_utils_error_codes.RawError<"DGII_INSUFFICIENT_ROLE">;
28
+ DGII_CREDENTIALS_UNAVAILABLE: _better_auth_core_utils_error_codes.RawError<"DGII_CREDENTIALS_UNAVAILABLE">;
29
+ DGII_CLIENT_NOT_CONFIGURED: _better_auth_core_utils_error_codes.RawError<"DGII_CLIENT_NOT_CONFIGURED">;
30
+ DGII_STATUS_API_KEY_REQUIRED: _better_auth_core_utils_error_codes.RawError<"DGII_STATUS_API_KEY_REQUIRED">;
31
+ DGII_DOCUMENT_UNREADABLE: _better_auth_core_utils_error_codes.RawError<"DGII_DOCUMENT_UNREADABLE">;
32
+ DGII_SIGNING_FAILED: _better_auth_core_utils_error_codes.RawError<"DGII_SIGNING_FAILED">;
33
+ DGII_REQUEST_FAILED: _better_auth_core_utils_error_codes.RawError<"DGII_REQUEST_FAILED">;
34
+ DGII_SUBMISSION_NOT_FOUND: _better_auth_core_utils_error_codes.RawError<"DGII_SUBMISSION_NOT_FOUND">;
35
+ DGII_PERSISTENCE_UNAVAILABLE: _better_auth_core_utils_error_codes.RawError<"DGII_PERSISTENCE_UNAVAILABLE">;
36
+ DGII_IDEMPOTENCY_IN_FLIGHT: _better_auth_core_utils_error_codes.RawError<"DGII_IDEMPOTENCY_IN_FLIGHT">;
37
+ };
38
+ type DgiiEcfErrorCode = keyof typeof DGII_ECF_ERROR_CODES;
39
+
40
+ export { DGII_ECF_ERROR_CODES, type DgiiEcfErrorCode };