@voyant-travel/apps 0.1.0 → 0.3.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.
@@ -1,231 +0,0 @@
1
- import { createAppCustomFieldDefinitionOwner, createCustomFieldsService, } from "@voyant-travel/custom-fields";
2
- import { ApiHttpError } from "@voyant-travel/hono";
3
- import { and, asc, eq, sql } from "drizzle-orm";
4
- import { assertActiveAppInstallationAccess } from "./access-boundary.js";
5
- import { APP_API_VERSION } from "./app-api-contracts.js";
6
- import { appAuditEvents, appGrants, appReleases, appWebhookSubscriptions } from "./schema.js";
7
- const DEFAULT_RATE_LIMIT = { installationLimit: 120, appLimit: 600, windowMs: 60_000 };
8
- const REMOTE_APP_NAMESPACE = /^\$app(?::[a-z][a-z0-9-]*)?$/;
9
- const PHYSICAL_APP_NAMESPACE = /^app--/;
10
- const buckets = new Map();
11
- export function createAppApiService(options = {}) {
12
- const now = () => options.now?.() ?? new Date();
13
- const customFields = options.customFieldTargets &&
14
- createCustomFieldsService(options.customFieldTargets, options.customFieldValueLifecycles ?? [], options.customFieldValueOperations ?? []);
15
- async function introspect(db, context) {
16
- const access = await requireAccess(db, context, ["app-installation:read"]);
17
- const grants = await db
18
- .select({
19
- scope: appGrants.scope,
20
- status: appGrants.status,
21
- optional: appGrants.optional,
22
- })
23
- .from(appGrants)
24
- .where(eq(appGrants.installationId, context.installationId))
25
- .orderBy(appGrants.scope);
26
- return {
27
- data: {
28
- installation: {
29
- id: access.installation.id,
30
- appId: access.installation.appId,
31
- status: access.installation.status,
32
- namespace: access.installation.namespace,
33
- deploymentId: access.installation.deploymentId,
34
- },
35
- release: {
36
- id: access.release.id,
37
- version: access.release.releaseVersion,
38
- apiCompatibility: access.release.apiCompatibility,
39
- },
40
- grants,
41
- },
42
- };
43
- }
44
- async function listEntities(db, context, entity, query) {
45
- await requireAccess(db, context, [`${entity}:read`]);
46
- const reader = options.entityReaders?.[entity];
47
- if (!reader)
48
- throw notSupported(`Entity "${entity}" is not supported by the App API.`);
49
- return { data: await reader.list(db, query) };
50
- }
51
- async function listFinanceDocuments(db, context, query) {
52
- await requireAccess(db, context, ["finance-documents:read"]);
53
- if (!options.finance)
54
- throw notSupported("Finance App API runtime is not configured.");
55
- return { data: await options.finance.listDocuments(db, query) };
56
- }
57
- async function executeFinanceAction(db, context, input) {
58
- await requireAccess(db, context, [`finance-actions:${input.action}`]);
59
- if (!options.finance)
60
- throw notSupported("Finance App API runtime is not configured.");
61
- if (!input.approvalId) {
62
- throw new ApiHttpError("Finance action requires action-ledger approval.", {
63
- status: 403,
64
- code: "app_api_finance_approval_required",
65
- });
66
- }
67
- return { data: await options.finance.executeAction(db, input) };
68
- }
69
- async function listCustomFieldDefinitions(db, context, query) {
70
- const access = await requireAccess(db, context, ["custom-field-definitions:read"]);
71
- return customFieldsRequired().listForOwner(db, owner(access), query);
72
- }
73
- async function createCustomFieldDefinition(db, context, namespace, input) {
74
- assertAppNamespaceAlias(namespace);
75
- const access = await requireAccess(db, context, ["custom-field-definitions:write"]);
76
- return { data: await customFieldsRequired().createForOwner(db, owner(access), input) };
77
- }
78
- async function updateCustomFieldDefinition(db, context, id, namespace, input) {
79
- assertAppNamespaceAlias(namespace);
80
- const access = await requireAccess(db, context, ["custom-field-definitions:write"]);
81
- const data = await customFieldsRequired().updateForOwner(db, owner(access), id, input);
82
- if (!data)
83
- throw notFound("Custom-field definition not found.");
84
- return { data };
85
- }
86
- async function listCustomFieldValues(db, context, query) {
87
- await requireAccess(db, context, [`custom-field-values:${query.entityType ?? "read"}`]);
88
- const access = await requireAccess(db, context, ["custom-field-values:read"]);
89
- return customFieldsRequired().values.listForOwner(db, owner(access), query);
90
- }
91
- async function upsertCustomFieldValue(db, context, definitionId, input) {
92
- await requireAccess(db, context, [
93
- "custom-field-values:write",
94
- `custom-field-values:${input.entityType}`,
95
- ]);
96
- const access = await requireAccess(db, context, []);
97
- return {
98
- data: await customFieldsRequired().values.upsertForOwner(db, owner(access), definitionId, input),
99
- };
100
- }
101
- async function listWebhookHealth(db, context) {
102
- await requireAccess(db, context, ["webhooks:read"]);
103
- const data = await db
104
- .select()
105
- .from(appWebhookSubscriptions)
106
- .where(eq(appWebhookSubscriptions.installationId, context.installationId))
107
- .orderBy(asc(appWebhookSubscriptions.eventType));
108
- return { data };
109
- }
110
- async function listAuditHistory(db, context, query) {
111
- await requireAccess(db, context, ["app-audit:read"]);
112
- const where = and(eq(appAuditEvents.appId, context.appId), eq(appAuditEvents.installationId, context.installationId));
113
- const [data, count] = await Promise.all([
114
- db.select().from(appAuditEvents).where(where).limit(query.limit).offset(query.offset),
115
- db.select({ count: sql `count(*)::int` }).from(appAuditEvents).where(where),
116
- ]);
117
- return { data, total: count[0]?.count ?? 0, limit: query.limit, offset: query.offset };
118
- }
119
- return {
120
- introspect,
121
- listEntities,
122
- listFinanceDocuments,
123
- executeFinanceAction,
124
- listCustomFieldDefinitions,
125
- createCustomFieldDefinition,
126
- updateCustomFieldDefinition,
127
- listCustomFieldValues,
128
- upsertCustomFieldValue,
129
- listWebhookHealth,
130
- listAuditHistory,
131
- requireAccess,
132
- enforceRateLimit,
133
- };
134
- async function requireAccess(db, context, requiredScopes) {
135
- enforceRateLimit(context);
136
- const installation = await assertActiveAppInstallationAccess(db, {
137
- installationId: context.installationId,
138
- requiredScopes,
139
- });
140
- if (installation.appId !== context.appId || installation.releaseId !== context.releaseId) {
141
- throw new ApiHttpError("App token does not match the active installation.", {
142
- status: 403,
143
- code: "app_api_token_installation_mismatch",
144
- });
145
- }
146
- const [release] = await db
147
- .select()
148
- .from(appReleases)
149
- .where(eq(appReleases.id, installation.releaseId))
150
- .limit(1);
151
- if (!release)
152
- throw notFound("Installed app release not found.");
153
- assertCompatibleVersion(context.apiVersion ?? APP_API_VERSION, release.apiCompatibility);
154
- return { installation, release };
155
- }
156
- function enforceRateLimit(context) {
157
- const policy = options.rateLimit ?? DEFAULT_RATE_LIMIT;
158
- hit(`installation:${context.installationId}`, policy.installationLimit, policy.windowMs);
159
- hit(`app:${context.appId}`, policy.appLimit, policy.windowMs);
160
- }
161
- function hit(key, limit, windowMs) {
162
- const timestamp = now().getTime();
163
- const bucket = buckets.get(key);
164
- if (!bucket || bucket.resetAt <= timestamp) {
165
- buckets.set(key, { count: 1, resetAt: timestamp + windowMs });
166
- return;
167
- }
168
- if (bucket.count >= limit) {
169
- throw new ApiHttpError("App API rate limit exceeded.", {
170
- status: 429,
171
- code: "app_api_rate_limited",
172
- details: { key, resetAt: new Date(bucket.resetAt).toISOString() },
173
- });
174
- }
175
- bucket.count += 1;
176
- }
177
- function owner(access) {
178
- return createAppCustomFieldDefinitionOwner({
179
- appId: access.installation.appId,
180
- namespace: access.installation.namespace,
181
- });
182
- }
183
- function customFieldsRequired() {
184
- if (!customFields)
185
- throw notSupported("Custom fields App API runtime is not configured.");
186
- return customFields;
187
- }
188
- }
189
- export function assertAppNamespaceAlias(namespace) {
190
- if (!namespace || namespace === "$app")
191
- return;
192
- if (PHYSICAL_APP_NAMESPACE.test(namespace) || !REMOTE_APP_NAMESPACE.test(namespace)) {
193
- throw new ApiHttpError("App APIs accept only the server-resolved $app namespace alias.", {
194
- status: 400,
195
- code: "app_api_invalid_custom_field_namespace",
196
- });
197
- }
198
- }
199
- export function assertCompatibleVersion(requested, range) {
200
- if (requested < range.min || requested > range.max) {
201
- throw new ApiHttpError("Requested App API version is outside the installed release range.", {
202
- status: 426,
203
- code: "app_api_version_out_of_range",
204
- details: { requested, supported: range },
205
- });
206
- }
207
- }
208
- export async function withAppApiDeadline(promise, timeoutMs = 5_000) {
209
- let timeout;
210
- try {
211
- return await Promise.race([
212
- promise,
213
- new Promise((_, reject) => {
214
- timeout = setTimeout(() => reject(new ApiHttpError("App API request deadline exceeded.", {
215
- status: 504,
216
- code: "app_api_deadline_exceeded",
217
- })), timeoutMs);
218
- }),
219
- ]);
220
- }
221
- finally {
222
- if (timeout)
223
- clearTimeout(timeout);
224
- }
225
- }
226
- function notSupported(message) {
227
- return new ApiHttpError(message, { status: 501, code: "app_api_not_configured" });
228
- }
229
- function notFound(message) {
230
- return new ApiHttpError(message, { status: 404, code: "not_found" });
231
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,105 +0,0 @@
1
- import { ApiHttpError } from "@voyant-travel/hono";
2
- import { describe, expect, it, vi } from "vitest";
3
- import { assertAppNamespaceAlias, assertCompatibleVersion, createAppApiService, } from "./app-api-service.js";
4
- import { appGrants, appInstallations, appReleases } from "./schema.js";
5
- function postgresStub(implementation) {
6
- const db = Object.create(null);
7
- Object.assign(db, implementation);
8
- return db;
9
- }
10
- function createAccessDb(options) {
11
- const installation = {
12
- id: "inst_1",
13
- appId: "app_1",
14
- deploymentId: "dep_1",
15
- releaseId: "rel_1",
16
- status: options.status ?? "active",
17
- namespace: "app--one",
18
- };
19
- const release = {
20
- id: "rel_1",
21
- appId: "app_1",
22
- releaseVersion: "1.0.0",
23
- apiCompatibility: options.releaseRange ?? { min: "2026-07-01", max: "2026-12-31" },
24
- };
25
- return postgresStub({
26
- select: () => ({
27
- from: (table) => ({
28
- where: () => {
29
- const rows = () => {
30
- if (table === appInstallations)
31
- return [installation];
32
- if (table === appReleases)
33
- return [release];
34
- if (table === appGrants)
35
- return (options.scopes ?? []).map((scope) => ({ scope }));
36
- return [];
37
- };
38
- return {
39
- // biome-ignore lint/suspicious/noThenProperty: test stub models Drizzle's awaitable query builder -- owner: apps.
40
- then: (resolve) => Promise.resolve(rows()).then(resolve),
41
- orderBy: async () => rows(),
42
- limit: async () => rows(),
43
- };
44
- },
45
- }),
46
- }),
47
- });
48
- }
49
- const context = {
50
- appId: "app_1",
51
- installationId: "inst_1",
52
- releaseId: "rel_1",
53
- tokenMode: "offline",
54
- scopes: [],
55
- apiVersion: "2026-07-01",
56
- };
57
- describe("App API service boundary", () => {
58
- it("rejects direct service calls when the installation is inactive", async () => {
59
- const service = createAppApiService();
60
- await expect(service.requireAccess(createAccessDb({ status: "paused", scopes: ["app-installation:read"] }), context, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_not_active" });
61
- });
62
- it("rejects direct service calls when required scopes are not granted", async () => {
63
- const service = createAppApiService();
64
- await expect(service.requireAccess(createAccessDb({ scopes: [] }), context, ["app-installation:read"])).rejects.toMatchObject({ status: 403, code: "app_installation_scope_missing" });
65
- });
66
- it("fails closed when the requested API version is outside the installed release range", async () => {
67
- const service = createAppApiService();
68
- await expect(service.requireAccess(createAccessDb({
69
- scopes: ["app-installation:read"],
70
- releaseRange: { min: "2026-08-01", max: "2026-12-31" },
71
- }), context, ["app-installation:read"])).rejects.toMatchObject({ status: 426, code: "app_api_version_out_of_range" });
72
- });
73
- it("requires action-ledger approval for finance actions even when OAuth scope is granted", async () => {
74
- const executeAction = vi.fn();
75
- const service = createAppApiService({
76
- finance: { listDocuments: vi.fn(), executeAction },
77
- });
78
- await expect(service.executeFinanceAction(createAccessDb({ scopes: ["finance-actions:issue"] }), context, {
79
- action: "issue",
80
- idempotencyKey: "idem_1",
81
- payload: {},
82
- })).rejects.toMatchObject({ status: 403, code: "app_api_finance_approval_required" });
83
- expect(executeAction).not.toHaveBeenCalled();
84
- });
85
- it("isolates rate limits per installation", async () => {
86
- const service = createAppApiService({
87
- rateLimit: { installationLimit: 1, appLimit: 10, windowMs: 60_000 },
88
- });
89
- const rateContext = { ...context, appId: "rate_app", installationId: "rate_inst_1" };
90
- service.enforceRateLimit(rateContext);
91
- expect(() => service.enforceRateLimit(rateContext)).toThrow(ApiHttpError);
92
- expect(() => service.enforceRateLimit({ ...rateContext, installationId: "rate_inst_2" })).not.toThrow();
93
- });
94
- it("accepts only the $app custom-field namespace alias from request data", () => {
95
- expect(() => assertAppNamespaceAlias(undefined)).not.toThrow();
96
- expect(() => assertAppNamespaceAlias("$app")).not.toThrow();
97
- expect(() => assertAppNamespaceAlias("$app:sync")).not.toThrow();
98
- expect(() => assertAppNamespaceAlias("app--foreign")).toThrow(ApiHttpError);
99
- expect(() => assertAppNamespaceAlias("custom")).toThrow(ApiHttpError);
100
- });
101
- it("compares App API compatibility ranges inclusively", () => {
102
- expect(() => assertCompatibleVersion("2026-07-01", { min: "2026-07-01", max: "2026-12-31" })).not.toThrow();
103
- expect(() => assertCompatibleVersion("2027-01-01", { min: "2026-07-01", max: "2026-12-31" })).toThrow(ApiHttpError);
104
- });
105
- });