Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Split the API envelope view out, and move the private address check

Claude4565643575c5
diff --git a/src/app/api/v1/envelopes/route.ts b/src/app/api/v1/envelopes/route.ts
index 838812c..ef870bc 100644
--- a/src/app/api/v1/envelopes/route.ts
+++ b/src/app/api/v1/envelopes/route.ts
@@ -39,6 +39,14 @@ export async function GET(request: Request) {
const page = await listApiEnvelopes(actor.userId, query.data);
+ if (!page) {
+ return apiError(
+ 400,
+ "invalid_request",
+ "cursor: not a cursor this API gave out.",
+ );
+ }
+
return apiJson({
data: page.data,
nextCursor: page.nextCursor,
diff --git a/src/lib/api/envelope-view.ts b/src/lib/api/envelope-view.ts
new file mode 100644
index 0000000..d126e7b
--- /dev/null
+++ b/src/lib/api/envelope-view.ts
@@ -0,0 +1,380 @@
+import { z } from "zod";
+
+import {
+ getDb,
+ queryMany,
+ queryOne,
+ type DbExecutor,
+} from "../db/connection.ts";
+import type { EnvelopeStatus, SignerStatus } from "../types/domain.ts";
+
+// How the public API shows an envelope: one shape, ApiEnvelope, returned by
+// every endpoint and carried by webhooks. Only reads here, so the webhook
+// outbox can build payloads without pulling in the code that changes
+// envelopes.
+
+const DEFAULT_PAGE_SIZE = 25;
+const MAX_PAGE_SIZE = 100;
+
+export type ApiSigner = {
+ declinedAt: string | null;
+ declineReason: string | null;
+ email: string;
+ id: string;
+ name: string;
+ order: number;
+ ref: string | null;
+ signedAt: string | null;
+ status: SignerStatus;
+ viewedAt: string | null;
+};
+
+export type ApiEnvelope = {
+ completedAt: string | null;
+ copyRecipients: Array<{ email: string; id: string; name: string }>;
+ createdAt: string;
+ declinedAt: string | null;
+ expired: boolean;
+ expiresAt: string | null;
+ files: { certificate: string | null; signed: string | null };
+ id: string;
+ metadata: Record<string, unknown> | null;
+ object: "envelope";
+ pageCount: number;
+ sentAt: string | null;
+ signatureLevel: string;
+ signers: ApiSigner[];
+ status: EnvelopeStatus;
+ title: string;
+ voidedAt: string | null;
+};
+
+export function isoTime(seconds: number | null | undefined): string | null {
+ return typeof seconds === "number"
+ ? new Date(seconds * 1000).toISOString()
+ : null;
+}
+
+type EnvelopeRow = {
+ apiMetadata: Record<string, unknown> | null;
+ completedAt: number | null;
+ createdAt: number;
+ declinedAt: number | null;
+ evidenceKey: string | null;
+ expiresAt: number | null;
+ id: string;
+ pageCount: number;
+ sentAt: number | null;
+ signatureLevel: string | null;
+ signedPdfKey: string | null;
+ status: EnvelopeStatus;
+ title: string;
+ voidedAt: number | null;
+};
+
+type SignerRow = {
+ apiRef: string | null;
+ declinedAt: number | null;
+ declineReason: string | null;
+ email: string;
+ envelopeId: string;
+ id: string;
+ name: string;
+ role: "cc" | "signer";
+ signedAt: number | null;
+ signOrder: number;
+ status: SignerStatus;
+ viewedAt: number | null;
+};
+
+const ENVELOPE_COLUMNS = `
+ e.id,
+ e.title,
+ e.status,
+ e.page_count AS "pageCount",
+ e.signed_pdf_key AS "signedPdfKey",
+ e.evidence_key AS "evidenceKey",
+ e.sent_at AS "sentAt",
+ e.completed_at AS "completedAt",
+ e.declined_at AS "declinedAt",
+ e.voided_at AS "voidedAt",
+ e.expires_at AS "expiresAt",
+ e.signature_level AS "signatureLevel",
+ e.api_metadata AS "apiMetadata",
+ e.created_at AS "createdAt"
+`;
+
+async function readSigners(
+ envelopeIds: string[],
+ database: DbExecutor,
+): Promise<Map<string, SignerRow[]>> {
+ const bySignerEnvelope = new Map<string, SignerRow[]>();
+
+ if (envelopeIds.length === 0) {
+ return bySignerEnvelope;
+ }
+
+ const rows = await queryMany<SignerRow>(
+ database,
+ `
+ SELECT
+ s.id,
+ s.envelope_id AS "envelopeId",
+ s.name,
+ s.email,
+ s.role,
+ s.sign_order AS "signOrder",
+ s.status,
+ s.signed_at AS "signedAt",
+ s.declined_at AS "declinedAt",
+ s.decline_reason AS "declineReason",
+ s.api_ref AS "apiRef",
+ (
+ SELECT min(a.created_at)
+ FROM audit_events a
+ WHERE a.envelope_id = s.envelope_id
+ AND a.event = 'viewed'
+ AND a.metadata->>'signerId' = s.id
+ ) AS "viewedAt"
+ FROM signers s
+ WHERE s.envelope_id = ANY($1)
+ ORDER BY s.envelope_id, s.sign_order, s.id
+ `,
+ [envelopeIds],
+ );
+
+ for (const row of rows) {
+ const list = bySignerEnvelope.get(row.envelopeId) ?? [];
+
+ list.push(row);
+ bySignerEnvelope.set(row.envelopeId, list);
+ }
+
+ return bySignerEnvelope;
+}
+
+export function toApiEnvelope(
+ row: EnvelopeRow,
+ signers: SignerRow[],
+ now: number = Math.floor(Date.now() / 1000),
+): ApiEnvelope {
+ const base = `/api/v1/envelopes/${encodeURIComponent(row.id)}/files`;
+ const finished =
+ row.status === "completed" ||
+ row.status === "declined" ||
+ row.status === "voided";
+
+ return {
+ completedAt: isoTime(row.completedAt),
+ copyRecipients: signers
+ .filter((signer) => signer.role === "cc")
+ .map((signer) => ({
+ email: signer.email,
+ id: signer.id,
+ name: signer.name,
+ })),
+ createdAt: isoTime(row.createdAt) ?? new Date(0).toISOString(),
+ declinedAt: isoTime(row.declinedAt),
+ expired:
+ row.status === "sent" && row.expiresAt !== null && row.expiresAt <= now,
+ expiresAt: isoTime(row.expiresAt),
+ files: {
+ certificate: finished ? `${base}/certificate` : null,
+ signed: row.status === "completed" ? `${base}/signed` : null,
+ },
+ id: row.id,
+ metadata: row.apiMetadata,
+ object: "envelope",
+ pageCount: row.pageCount,
+ sentAt: isoTime(row.sentAt),
+ signatureLevel: row.signatureLevel ?? "simple",
+ signers: signers
+ .filter((signer) => signer.role === "signer")
+ .map((signer) => ({
+ declinedAt: isoTime(signer.declinedAt),
+ declineReason: signer.declineReason,
+ email: signer.email,
+ id: signer.id,
+ name: signer.name,
+ order: signer.signOrder,
+ ref: signer.apiRef,
+ signedAt: isoTime(signer.signedAt),
+ status: signer.status,
+ viewedAt: isoTime(signer.viewedAt),
+ })),
+ status: row.status,
+ title: row.title,
+ voidedAt: isoTime(row.voidedAt),
+ };
+}
+
+/** One envelope the account can see, or null. */
+export async function getApiEnvelope(
+ userId: string,
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+): Promise<ApiEnvelope | null> {
+ const row = await queryOne<EnvelopeRow>(
+ database,
+ `SELECT ${ENVELOPE_COLUMNS} FROM envelopes e WHERE e.id = $1 AND e.user_id = $2`,
+ [envelopeId, userId],
+ );
+
+ if (!row) {
+ return null;
+ }
+
+ const signers = await readSigners([row.id], database);
+
+ return toApiEnvelope(row, signers.get(row.id) ?? []);
+}
+
+export function encodeCursor(createdAt: number, id: string): string {
+ return Buffer.from(`${String(createdAt)}:${id}`, "utf8").toString(
+ "base64url",
+ );
+}
+
+export function decodeCursor(
+ cursor: string,
+): { createdAt: number; id: string } | null {
+ const decoded = Buffer.from(cursor, "base64url").toString("utf8");
+ const separator = decoded.indexOf(":");
+
+ if (separator <= 0) {
+ return null;
+ }
+
+ const createdAt = Number(decoded.slice(0, separator));
+ const id = decoded.slice(separator + 1);
+
+ return Number.isSafeInteger(createdAt) && id.length > 0
+ ? { createdAt, id }
+ : null;
+}
+
+export const apiListQuerySchema = z.object({
+ cursor: z.string().max(200).optional(),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(MAX_PAGE_SIZE)
+ .default(DEFAULT_PAGE_SIZE),
+ status: z
+ .enum(["draft", "sent", "completed", "declined", "voided"])
+ .optional(),
+});
+
+/**
+ * The account's envelopes, newest first, a page at a time. Null for a
+ * cursor this API did not give out.
+ */
+export async function listApiEnvelopes(
+ userId: string,
+ query: z.infer<typeof apiListQuerySchema>,
+ database: DbExecutor = getDb(),
+): Promise<{ data: ApiEnvelope[]; nextCursor: string | null } | null> {
+ const values: unknown[] = [userId];
+ const clauses = ["e.user_id = $1"];
+
+ if (query.status) {
+ values.push(query.status);
+ clauses.push(`e.status = $${String(values.length)}`);
+ }
+
+ if (query.cursor) {
+ const cursor = decodeCursor(query.cursor);
+
+ if (!cursor) {
+ return null;
+ }
+
+ values.push(cursor.createdAt, cursor.id);
+ clauses.push(
+ `(e.created_at, e.id) < ($${String(values.length - 1)}, $${String(values.length)})`,
+ );
+ }
+
+ values.push(query.limit + 1);
+
+ const rows = await queryMany<EnvelopeRow>(
+ database,
+ `
+ SELECT ${ENVELOPE_COLUMNS}
+ FROM envelopes e
+ WHERE ${clauses.join(" AND ")}
+ ORDER BY e.created_at DESC, e.id DESC
+ LIMIT $${String(values.length)}
+ `,
+ values,
+ );
+ const page = rows.slice(0, query.limit);
+ const signers = await readSigners(
+ page.map((row) => row.id),
+ database,
+ );
+ const last = page.at(-1);
+
+ return {
+ data: page.map((row) => toApiEnvelope(row, signers.get(row.id) ?? [])),
+ nextCursor:
+ rows.length > query.limit && last
+ ? encodeCursor(last.createdAt, last.id)
+ : null,
+ };
+}
+
+type AuditRow = {
+ actorEmail: string | null;
+ actorType: string;
+ createdAt: number;
+ event: string;
+ id: string;
+ ipAddress: string | null;
+ metadata: Record<string, unknown> | null;
+};
+
+/** The envelope's audit trail, oldest first, as the API returns it. */
+export async function listApiEnvelopeEvents(
+ userId: string,
+ envelopeId: string,
+ database: DbExecutor = getDb(),
+) {
+ const owner = await queryOne<{ id: string }>(
+ database,
+ `SELECT id FROM envelopes WHERE id = $1 AND user_id = $2`,
+ [envelopeId, userId],
+ );
+
+ if (!owner) {
+ return null;
+ }
+
+ const rows = await queryMany<AuditRow>(
+ database,
+ `
+ SELECT
+ id,
+ event,
+ actor_type AS "actorType",
+ actor_email AS "actorEmail",
+ ip_address AS "ipAddress",
+ metadata,
+ created_at AS "createdAt"
+ FROM audit_events
+ WHERE envelope_id = $1
+ ORDER BY sequence ASC
+ `,
+ [envelopeId],
+ );
+
+ return rows.map((row) => ({
+ actor: { email: row.actorEmail, type: row.actorType },
+ at: isoTime(row.createdAt),
+ event: row.event,
+ id: row.id,
+ ipAddress: row.ipAddress,
+ metadata: row.metadata,
+ }));
+}
diff --git a/src/lib/api/envelopes.dbtest.ts b/src/lib/api/envelopes.dbtest.ts
index 917179c..a20b0b8 100644
--- a/src/lib/api/envelopes.dbtest.ts
+++ b/src/lib/api/envelopes.dbtest.ts
@@ -341,6 +341,7 @@ test("the list pages with a cursor, newest first, and filters by status", async
// Same-second creations still come back in a stable order.
const first = await listApiEnvelopes(actor.userId, { limit: 2 }, database);
+ assert.ok(first);
assert.equal(first.data.length, 2);
assert.ok(first.nextCursor);
@@ -350,6 +351,7 @@ test("the list pages with a cursor, newest first, and filters by status", async
database,
);
+ assert.ok(second);
assert.equal(second.data.length, 1);
assert.equal(second.nextCursor, null);
assert.deepEqual(
@@ -363,7 +365,7 @@ test("the list pages with a cursor, newest first, and filters by status", async
{ limit: 25, status: "sent" },
database,
)
- ).data.length,
+ )?.data.length,
0,
);
});
diff --git a/src/lib/api/envelopes.ts b/src/lib/api/envelopes.ts
index 57b16ae..0333be3 100644
--- a/src/lib/api/envelopes.ts
+++ b/src/lib/api/envelopes.ts
@@ -1,12 +1,6 @@
import { z } from "zod";
-import {
- getDb,
- queryMany,
- queryOne,
- type DbExecutor,
- type DbPool,
-} from "../db/connection.ts";
+import { getDb, type DbExecutor, type DbPool } from "../db/connection.ts";
import {
createDraftEnvelope,
deleteDraftEnvelope,
@@ -29,8 +23,6 @@ import {
MAX_COPY_RECIPIENTS_PER_ENVELOPE,
MAX_SIGNERS_PER_ENVELOPE,
signatureMeanings,
- type EnvelopeStatus,
- type SignerStatus,
} from "../types/domain.ts";
// Envelopes as the public API sees them: one shape, ApiEnvelope, returned by
@@ -40,47 +32,19 @@ import {
export const MAX_API_METADATA_BYTES = 2048;
export const MAX_API_FIELDS = 500;
-const DEFAULT_PAGE_SIZE = 25;
-const MAX_PAGE_SIZE = 100;
-
-export type ApiSigner = {
- declinedAt: string | null;
- declineReason: string | null;
- email: string;
- id: string;
- name: string;
- order: number;
- ref: string | null;
- signedAt: string | null;
- status: SignerStatus;
- viewedAt: string | null;
-};
-export type ApiEnvelope = {
- completedAt: string | null;
- copyRecipients: Array<{ email: string; id: string; name: string }>;
- createdAt: string;
- declinedAt: string | null;
- expired: boolean;
- expiresAt: string | null;
- files: { certificate: string | null; signed: string | null };
- id: string;
- metadata: Record<string, unknown> | null;
- object: "envelope";
- pageCount: number;
- sentAt: string | null;
- signatureLevel: string;
- signers: ApiSigner[];
- status: EnvelopeStatus;
- title: string;
- voidedAt: string | null;
-};
-
-function isoTime(seconds: number | null | undefined): string | null {
- return typeof seconds === "number"
- ? new Date(seconds * 1000).toISOString()
- : null;
-}
+export {
+ apiListQuerySchema,
+ decodeCursor,
+ encodeCursor,
+ getApiEnvelope,
+ listApiEnvelopeEvents,
+ listApiEnvelopes,
+ toApiEnvelope,
+ type ApiEnvelope,
+ type ApiSigner,
+} from "./envelope-view.ts";
+import { getApiEnvelope, type ApiEnvelope } from "./envelope-view.ts";
const refSchema = z
.string()
@@ -349,327 +313,3 @@ export async function markEnvelopeAsApiMade(
[apiKeyId, metadata, envelopeId],
);
}
-
-type EnvelopeRow = {
- apiMetadata: Record<string, unknown> | null;
- completedAt: number | null;
- createdAt: number;
- declinedAt: number | null;
- evidenceKey: string | null;
- expiresAt: number | null;
- id: string;
- pageCount: number;
- sentAt: number | null;
- signatureLevel: string | null;
- signedPdfKey: string | null;
- status: EnvelopeStatus;
- title: string;
- voidedAt: number | null;
-};
-
-type SignerRow = {
- apiRef: string | null;
- declinedAt: number | null;
- declineReason: string | null;
- email: string;
- envelopeId: string;
- id: string;
- name: string;
- role: "cc" | "signer";
- signedAt: number | null;
- signOrder: number;
- status: SignerStatus;
- viewedAt: number | null;
-};
-
-const ENVELOPE_COLUMNS = `
- e.id,
- e.title,
- e.status,
- e.page_count AS "pageCount",
- e.signed_pdf_key AS "signedPdfKey",
- e.evidence_key AS "evidenceKey",
- e.sent_at AS "sentAt",
- e.completed_at AS "completedAt",
- e.declined_at AS "declinedAt",
- e.voided_at AS "voidedAt",
- e.expires_at AS "expiresAt",
- e.signature_level AS "signatureLevel",
- e.api_metadata AS "apiMetadata",
- e.created_at AS "createdAt"
-`;
-
-async function readSigners(
- envelopeIds: string[],
- database: DbExecutor,
-): Promise<Map<string, SignerRow[]>> {
- const bySignerEnvelope = new Map<string, SignerRow[]>();
-
- if (envelopeIds.length === 0) {
- return bySignerEnvelope;
- }
-
- const rows = await queryMany<SignerRow>(
- database,
- `
- SELECT
- s.id,
- s.envelope_id AS "envelopeId",
- s.name,
- s.email,
- s.role,
- s.sign_order AS "signOrder",
- s.status,
- s.signed_at AS "signedAt",
- s.declined_at AS "declinedAt",
- s.decline_reason AS "declineReason",
- s.api_ref AS "apiRef",
- (
- SELECT min(a.created_at)
- FROM audit_events a
- WHERE a.envelope_id = s.envelope_id
- AND a.event = 'viewed'
- AND a.metadata->>'signerId' = s.id
- ) AS "viewedAt"
- FROM signers s
- WHERE s.envelope_id = ANY($1)
- ORDER BY s.envelope_id, s.sign_order, s.id
- `,
- [envelopeIds],
- );
-
- for (const row of rows) {
- const list = bySignerEnvelope.get(row.envelopeId) ?? [];
-
- list.push(row);
- bySignerEnvelope.set(row.envelopeId, list);
- }
-
- return bySignerEnvelope;
-}
-
-export function toApiEnvelope(
- row: EnvelopeRow,
- signers: SignerRow[],
- now: number = Math.floor(Date.now() / 1000),
-): ApiEnvelope {
- const base = `/api/v1/envelopes/${encodeURIComponent(row.id)}/files`;
- const finished =
- row.status === "completed" ||
- row.status === "declined" ||
- row.status === "voided";
-
- return {
- completedAt: isoTime(row.completedAt),
- copyRecipients: signers
- .filter((signer) => signer.role === "cc")
- .map((signer) => ({
- email: signer.email,
- id: signer.id,
- name: signer.name,
- })),
- createdAt: isoTime(row.createdAt) ?? new Date(0).toISOString(),
- declinedAt: isoTime(row.declinedAt),
- expired:
- row.status === "sent" && row.expiresAt !== null && row.expiresAt <= now,
- expiresAt: isoTime(row.expiresAt),
- files: {
- certificate: finished ? `${base}/certificate` : null,
- signed: row.status === "completed" ? `${base}/signed` : null,
- },
- id: row.id,
- metadata: row.apiMetadata,
- object: "envelope",
- pageCount: row.pageCount,
- sentAt: isoTime(row.sentAt),
- signatureLevel: row.signatureLevel ?? "simple",
- signers: signers
- .filter((signer) => signer.role === "signer")
- .map((signer) => ({
- declinedAt: isoTime(signer.declinedAt),
- declineReason: signer.declineReason,
- email: signer.email,
- id: signer.id,
- name: signer.name,
- order: signer.signOrder,
- ref: signer.apiRef,
- signedAt: isoTime(signer.signedAt),
- status: signer.status,
- viewedAt: isoTime(signer.viewedAt),
- })),
- status: row.status,
- title: row.title,
- voidedAt: isoTime(row.voidedAt),
- };
-}
-
-/** One envelope the account can see, or null. */
-export async function getApiEnvelope(
- userId: string,
- envelopeId: string,
- database: DbExecutor = getDb(),
-): Promise<ApiEnvelope | null> {
- const row = await queryOne<EnvelopeRow>(
- database,
- `SELECT ${ENVELOPE_COLUMNS} FROM envelopes e WHERE e.id = $1 AND e.user_id = $2`,
- [envelopeId, userId],
- );
-
- if (!row) {
- return null;
- }
-
- const signers = await readSigners([row.id], database);
-
- return toApiEnvelope(row, signers.get(row.id) ?? []);
-}
-
-export function encodeCursor(createdAt: number, id: string): string {
- return Buffer.from(`${String(createdAt)}:${id}`, "utf8").toString(
- "base64url",
- );
-}
-
-export function decodeCursor(
- cursor: string,
-): { createdAt: number; id: string } | null {
- const decoded = Buffer.from(cursor, "base64url").toString("utf8");
- const separator = decoded.indexOf(":");
-
- if (separator <= 0) {
- return null;
- }
-
- const createdAt = Number(decoded.slice(0, separator));
- const id = decoded.slice(separator + 1);
-
- return Number.isSafeInteger(createdAt) && id.length > 0
- ? { createdAt, id }
- : null;
-}
-
-export const apiListQuerySchema = z.object({
- cursor: z.string().max(200).optional(),
- limit: z.coerce
- .number()
- .int()
- .min(1)
- .max(MAX_PAGE_SIZE)
- .default(DEFAULT_PAGE_SIZE),
- status: z
- .enum(["draft", "sent", "completed", "declined", "voided"])
- .optional(),
-});
-
-/** The account's envelopes, newest first, a page at a time. */
-export async function listApiEnvelopes(
- userId: string,
- query: z.infer<typeof apiListQuerySchema>,
- database: DbExecutor = getDb(),
-): Promise<{ data: ApiEnvelope[]; nextCursor: string | null }> {
- const values: unknown[] = [userId];
- const clauses = ["e.user_id = $1"];
-
- if (query.status) {
- values.push(query.status);
- clauses.push(`e.status = $${String(values.length)}`);
- }
-
- if (query.cursor) {
- const cursor = decodeCursor(query.cursor);
-
- if (!cursor) {
- throw new EnvelopeMutationError(
- "cursor: not a cursor this API gave out.",
- 400,
- );
- }
-
- values.push(cursor.createdAt, cursor.id);
- clauses.push(
- `(e.created_at, e.id) < ($${String(values.length - 1)}, $${String(values.length)})`,
- );
- }
-
- values.push(query.limit + 1);
-
- const rows = await queryMany<EnvelopeRow>(
- database,
- `
- SELECT ${ENVELOPE_COLUMNS}
- FROM envelopes e
- WHERE ${clauses.join(" AND ")}
- ORDER BY e.created_at DESC, e.id DESC
- LIMIT $${String(values.length)}
- `,
- values,
- );
- const page = rows.slice(0, query.limit);
- const signers = await readSigners(
- page.map((row) => row.id),
- database,
- );
- const last = page.at(-1);
-
- return {
- data: page.map((row) => toApiEnvelope(row, signers.get(row.id) ?? [])),
- nextCursor:
- rows.length > query.limit && last
- ? encodeCursor(last.createdAt, last.id)
- : null,
- };
-}
-
-type AuditRow = {
- actorEmail: string | null;
- actorType: string;
- createdAt: number;
- event: string;
- id: string;
- ipAddress: string | null;
- metadata: Record<string, unknown> | null;
-};
-
-/** The envelope's audit trail, oldest first, as the API returns it. */
-export async function listApiEnvelopeEvents(
- userId: string,
- envelopeId: string,
- database: DbExecutor = getDb(),
-) {
- const owner = await queryOne<{ id: string }>(
- database,
- `SELECT id FROM envelopes WHERE id = $1 AND user_id = $2`,
- [envelopeId, userId],
- );
-
- if (!owner) {
- return null;
- }
-
- const rows = await queryMany<AuditRow>(
- database,
- `
- SELECT
- id,
- event,
- actor_type AS "actorType",
- actor_email AS "actorEmail",
- ip_address AS "ipAddress",
- metadata,
- created_at AS "createdAt"
- FROM audit_events
- WHERE envelope_id = $1
- ORDER BY sequence ASC
- `,
- [envelopeId],
- );
-
- return rows.map((row) => ({
- actor: { email: row.actorEmail, type: row.actorType },
- at: isoTime(row.createdAt),
- event: row.event,
- id: row.id,
- ipAddress: row.ipAddress,
- metadata: row.metadata,
- }));
-}
diff --git a/src/lib/services/pdf-ltv.ts b/src/lib/services/pdf-ltv.ts
index b43fcea..f9295a9 100644
--- a/src/lib/services/pdf-ltv.ts
+++ b/src/lib/services/pdf-ltv.ts
@@ -6,7 +6,7 @@ import {
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { request as httpRequest, type IncomingMessage } from "node:http";
import { request as httpsRequest } from "node:https";
-import { isIP, type LookupFunction } from "node:net";
+import { type LookupFunction } from "node:net";
import {
algorithm,
@@ -23,6 +23,7 @@ import {
TAG,
type Tlv,
} from "./der.ts";
+import { isPrivateAddress } from "./private-address.ts";
import {
appendDocumentSecurityStore,
appendDocumentTimestamp,
@@ -367,54 +368,6 @@ export type ValidationFetch = (
},
) => Promise<Buffer>;
-function isPrivateAddress(host: string): boolean {
- const address = host.replace(/^\[|\]$/g, "").toLowerCase();
-
- if (address === "localhost" || address.endsWith(".localhost")) {
- return true;
- }
-
- const version = isIP(address);
-
- if (version === 4) {
- const [a, b] = address.split(".").map(Number) as [number, number];
-
- return (
- a === 0 ||
- a === 10 ||
- a === 127 ||
- (a === 100 && b >= 64 && b <= 127) ||
- (a === 169 && b === 254) ||
- (a === 172 && b >= 16 && b <= 31) ||
- (a === 192 && b === 168) ||
- (a === 198 && (b === 18 || b === 19)) ||
- // Multicast, reserved and broadcast.
- a >= 224
- );
- }
-
- if (version === 6) {
- // An IPv4 address mapped into IPv6, which URL writes in hex.
- const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
- const mapped = hex
- ? [parseInt(hex[1]!, 16), parseInt(hex[2]!, 16)]
- .flatMap((word) => [word >> 8, word & 0xff])
- .join(".")
- : /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(address)?.[1];
-
- return (
- address === "::" ||
- address === "::1" ||
- /^f[cd]/.test(address) ||
- /^fe[89ab]/.test(address) ||
- /^ff/.test(address) ||
- (mapped ? isPrivateAddress(mapped) : false)
- );
- }
-
- return false;
-}
-
type AddressLookup = (
hostname: string,
callback: (error: Error | null, addresses: LookupAddress[]) => void,
diff --git a/src/lib/services/private-address.ts b/src/lib/services/private-address.ts
new file mode 100644
index 0000000..abd2d13
--- /dev/null
+++ b/src/lib/services/private-address.ts
@@ -0,0 +1,56 @@
+import { isIP } from "node:net";
+
+// Addresses an outgoing request from the app must not reach on its own
+// accord: loopback, private networks, link-local (cloud metadata services
+// live there), carrier-grade NAT, benchmarking, multicast and reserved
+// ranges. Used for fetches whose address comes from outside, such as
+// revocation lookups named in a certificate and webhook endpoints.
+
+/** True when `host` (a name or an IP address, brackets allowed) is private. */
+export function isPrivateAddress(host: string): boolean {
+ const address = host.replace(/^\[|\]$/g, "").toLowerCase();
+
+ if (address === "localhost" || address.endsWith(".localhost")) {
+ return true;
+ }
+
+ const version = isIP(address);
+
+ if (version === 4) {
+ const [a, b] = address.split(".").map(Number) as [number, number];
+
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ // Multicast, reserved and broadcast.
+ a >= 224
+ );
+ }
+
+ if (version === 6) {
+ // An IPv4 address mapped into IPv6, which URL writes in hex.
+ const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
+ const mapped = hex
+ ? [parseInt(hex[1]!, 16), parseInt(hex[2]!, 16)]
+ .flatMap((word) => [word >> 8, word & 0xff])
+ .join(".")
+ : /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(address)?.[1];
+
+ return (
+ address === "::" ||
+ address === "::1" ||
+ /^f[cd]/.test(address) ||
+ /^fe[89ab]/.test(address) ||
+ /^ff/.test(address) ||
+ (mapped ? isPrivateAddress(mapped) : false)
+ );
+ }
+
+ return false;
+}