@ductape/cli 0.4.5 → 0.4.9

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,8 @@
1
+ export declare function runCapabilitySearch(query: string, opts: {
2
+ product: string;
3
+ env?: string;
4
+ limit?: string;
5
+ marketplace?: boolean;
6
+ profile?: string;
7
+ json?: boolean;
8
+ }): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { searchCapabilities } from '../lib/capability-search.js';
2
+ import { requireWorkspaceContext } from '../lib/workspace-context.js';
3
+ import { printJson } from '../lib/output.js';
4
+ export async function runCapabilitySearch(query, opts) {
5
+ const ctx = requireWorkspaceContext({ profile: opts.profile });
6
+ printJson(await searchCapabilities(ctx, { product: opts.product, env: opts.env, query, limit: opts.limit ? Number(opts.limit) : undefined, marketplace: opts.marketplace }), Boolean(opts.json));
7
+ }
@@ -1,4 +1,5 @@
1
1
  type CloudTarget = 'connections' | 'resources' | 'tiers';
2
+ import { type IConnectionFlags } from '../lib/cloud-connection.js';
2
3
  export declare function runCloudPreflight(opts: {
3
4
  product?: string;
4
5
  file?: string;
@@ -12,5 +13,8 @@ export declare function runCloud(target: CloudTarget, verb: string, opts: {
12
13
  dbType?: string;
13
14
  tier?: string;
14
15
  json?: boolean;
16
+ connection?: IConnectionFlags;
17
+ purpose?: string;
18
+ dryRun?: boolean;
15
19
  }, extraArgs: string[]): Promise<void>;
16
20
  export {};
@@ -17,6 +17,7 @@ const CLOUD_SERVICE_CAPABILITIES = [
17
17
  { service: 'pubsub', provider: 'gcp', types: ['messageBroker'], actions: ['list', 'import', 'provision'] },
18
18
  { service: 'sns_sqs', provider: 'aws', types: ['messageBroker'], actions: ['list', 'import', 'provision'] },
19
19
  ];
20
+ import { buildConnectionBody, connectionGuide, maskConnectionBody } from '../lib/cloud-connection.js';
20
21
  export async function runCloudPreflight(opts) {
21
22
  const session = requireSession();
22
23
  const proxy = getSdkProxy(session);
@@ -78,6 +79,11 @@ export async function runCloudPreflight(opts) {
78
79
  }, Boolean(opts.json));
79
80
  }
80
81
  export async function runCloud(target, verb, opts, extraArgs) {
82
+ if (target === 'connections' && verb.toLowerCase() === 'guide') {
83
+ // Offline: prints the steps for connecting a provider, and contacts nothing.
84
+ printJson(connectionGuide(opts.connection?.provider ?? '', opts.purpose ?? 'resources'), Boolean(opts.json));
85
+ return;
86
+ }
81
87
  if (target === 'tiers') {
82
88
  const ctx = requireWorkspaceContext();
83
89
  const result = await listCloudTiers(ctx, {
@@ -88,9 +94,22 @@ export async function runCloud(target, verb, opts, extraArgs) {
88
94
  printJson(result, Boolean(opts.json));
89
95
  return;
90
96
  }
97
+ const isConnectionWrite = target === 'connections' && ['create', 'complete', 'update'].includes(verb.toLowerCase());
98
+ if (opts.dryRun && !isConnectionWrite)
99
+ throw new Error('--dry-run applies to cloud connections create, complete and update');
100
+ if (opts.dryRun) {
101
+ // Offline preview of exactly what would be sent. Secrets are masked and nothing is contacted.
102
+ const base = readJsonBody(opts.file);
103
+ const built = buildConnectionBody(verb, opts.connection ?? {}, base && typeof base === 'object' && !Array.isArray(base) ? base : {});
104
+ printJson({ dry_run: true, would: `cloud connections ${verb.toLowerCase()}${opts.id ?? extraArgs[0] ? ` ${opts.id ?? extraArgs[0]}` : ''}`, body: maskConnectionBody(built), contacted: 'nothing' }, Boolean(opts.json));
105
+ return;
106
+ }
91
107
  requireSession();
92
108
  const proxy = getSdkProxy();
93
109
  let body = readJsonBody(opts.file);
110
+ if (isConnectionWrite && opts.connection) {
111
+ body = buildConnectionBody(verb, opts.connection, body && typeof body === 'object' && !Array.isArray(body) ? body : {});
112
+ }
94
113
  if (opts.tier) {
95
114
  body = { ...(body && typeof body === 'object' && !Array.isArray(body) ? body : {}), tier: opts.tier };
96
115
  }
@@ -0,0 +1,17 @@
1
+ export interface IBuildOptions {
2
+ file?: string;
3
+ dir?: string;
4
+ builder?: string;
5
+ dockerfile?: string;
6
+ context?: string;
7
+ wait?: boolean;
8
+ waitMinutes?: string;
9
+ id?: string;
10
+ product?: string;
11
+ status?: string;
12
+ }
13
+ /**
14
+ * Builds source in the customer's own cloud account. The source is packed here, uploaded straight to a bucket in that
15
+ * account, and built there by the same cloud connection that will deploy it. Ductape holds only the checksum.
16
+ */
17
+ export declare function runDeployBuilds(operation: 'create' | 'status' | 'list', options: IBuildOptions): Promise<void>;
@@ -0,0 +1,99 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ApiClient } from '../lib/api-client.js';
4
+ import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
5
+ import { packSource, uploadSource } from '../lib/source-pack.js';
6
+ import { actorHeaders } from './deploy-remote.js';
7
+ const BASE = '/integrations/v1/deploy';
8
+ const TERMINAL = new Set(['succeeded', 'failed', 'expired']);
9
+ const note = (message) => process.stderr.write(`${message}\n`);
10
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11
+ function readBuildFile(file) {
12
+ if (!file)
13
+ throw new Error('--file is required: a JSON file with productTag, functionName, version, connectionTag, region, contract, config and verification');
14
+ const resolved = path.resolve(file);
15
+ try {
16
+ const parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
17
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
18
+ throw new Error('it must be a JSON object');
19
+ return parsed;
20
+ }
21
+ catch (error) {
22
+ throw new Error(`The build file ${resolved} could not be used: ${error instanceof Error ? error.message : String(error)}`);
23
+ }
24
+ }
25
+ /**
26
+ * Builds source in the customer's own cloud account. The source is packed here, uploaded straight to a bucket in that
27
+ * account, and built there by the same cloud connection that will deploy it. Ductape holds only the checksum.
28
+ */
29
+ export async function runDeployBuilds(operation, options) {
30
+ const ctx = requireWorkspaceContext();
31
+ const api = ApiClient.forProfile(ctx.profile, ctx.credentials);
32
+ const extra = {};
33
+ if (operation === 'list') {
34
+ if (options.product)
35
+ extra.productTag = options.product;
36
+ if (options.status)
37
+ extra.status = options.status;
38
+ }
39
+ const query = new URLSearchParams(workspaceAuthQuery(ctx, extra)).toString();
40
+ const call = (method, route, body) => api.request(method, `${BASE}${route}?${query}`, body, actorHeaders());
41
+ if (operation === 'list') {
42
+ console.log(JSON.stringify(await call('GET', '/builds'), null, 2));
43
+ return;
44
+ }
45
+ if (operation === 'status') {
46
+ if (!options.id)
47
+ throw new Error('A build id is required');
48
+ console.log(JSON.stringify(await call('GET', `/builds/${encodeURIComponent(options.id)}`), null, 2));
49
+ return;
50
+ }
51
+ const spec = readBuildFile(options.file);
52
+ const builder = (options.builder ?? spec.builder ?? 'dockerfile');
53
+ if (builder !== 'dockerfile' && builder !== 'buildpacks')
54
+ throw new Error('--builder must be "dockerfile" or "buildpacks"');
55
+ const dockerfile = (options.dockerfile ?? spec.dockerfile ?? 'Dockerfile');
56
+ const contextDir = (options.context ?? spec.contextDir ?? '.');
57
+ const dir = options.dir ?? '.';
58
+ note(`Packing ${path.resolve(dir)} ...`);
59
+ const packed = await packSource(dir, { dockerfile: builder === 'dockerfile' ? dockerfile : undefined });
60
+ let buildId;
61
+ try {
62
+ for (const warning of packed.warnings)
63
+ note(`Warning: ${warning}`);
64
+ note(`Packed ${(packed.bytes / 1024).toFixed(0)} KB (left out: ${packed.excluded.join(', ')})`);
65
+ const created = await call('POST', '/builds', {
66
+ ...spec, builder, dockerfile, contextDir, sourceSha256: packed.sha256, sourceBytes: packed.bytes,
67
+ });
68
+ buildId = created.id;
69
+ note(`Build ${buildId} created. Uploading straight to your own bucket ...`);
70
+ await uploadSource(created.upload, packed.file);
71
+ }
72
+ finally {
73
+ packed.cleanup();
74
+ }
75
+ note('Uploaded. Starting the build in your cloud account ...');
76
+ let build = await call('POST', `/builds/${buildId}/start`, {});
77
+ if (build.logUrl)
78
+ note(`Logs: ${build.logUrl}`);
79
+ if (options.wait) {
80
+ const deadline = Date.now() + Math.max(1, Number(options.waitMinutes) || 30) * 60_000;
81
+ let last = '';
82
+ while (!TERMINAL.has(build.status)) {
83
+ if (Date.now() > deadline)
84
+ throw new Error(`Still ${build.status} after waiting. Check later with: ductape deploy builds status ${buildId}`);
85
+ await sleep(5000);
86
+ build = await call('GET', `/builds/${buildId}`);
87
+ if (build.status !== last) {
88
+ note(`Build ${build.status} ...`);
89
+ last = build.status;
90
+ }
91
+ }
92
+ console.log(JSON.stringify(build, null, 2));
93
+ if (build.status !== 'succeeded')
94
+ process.exitCode = 1;
95
+ return;
96
+ }
97
+ console.log(JSON.stringify(build, null, 2));
98
+ note(`Follow it with: ductape deploy builds status ${buildId}`);
99
+ }
@@ -0,0 +1,16 @@
1
+ export type DeployRemoteOperation = 'releases.register' | 'plans.create' | 'plans.approve' | 'plans.apply' | 'deployments.list' | 'deployments.get' | 'deployments.journal' | 'functions.list' | 'versions.list' | 'versions.history' | 'versions.deprecate' | 'versions.undeprecate' | 'versions.retire';
2
+ export interface IDeployRemoteArgs {
3
+ file?: string;
4
+ id?: string;
5
+ product?: string;
6
+ function?: string;
7
+ version?: string;
8
+ env?: string;
9
+ reason?: string;
10
+ sunset?: string;
11
+ replacement?: string;
12
+ }
13
+ /** Calls made on behalf of an agent say so, so the control plane never lets them approve or retire. */
14
+ export declare function actorHeaders(): Record<string, string>;
15
+ /** Talks to the deploy control plane in the active workspace. Prints the result as JSON. */
16
+ export declare function runDeployRemote(operation: DeployRemoteOperation, args: IDeployRemoteArgs): Promise<void>;
@@ -0,0 +1,106 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ApiClient } from '../lib/api-client.js';
4
+ import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
5
+ const BASE = '/integrations/v1/deploy';
6
+ /** Calls made on behalf of an agent say so, so the control plane never lets them approve or retire. */
7
+ export function actorHeaders() {
8
+ return process.env.DUCTAPE_ACTOR === 'agent' ? { 'x-ductape-actor': 'agent' } : {};
9
+ }
10
+ function readJsonFile(file, what) {
11
+ if (!file)
12
+ throw new Error(`--file is required (a JSON file holding the ${what})`);
13
+ const resolved = path.resolve(file);
14
+ let raw;
15
+ try {
16
+ raw = fs.readFileSync(resolved, 'utf8');
17
+ }
18
+ catch (error) {
19
+ throw new Error(`Cannot read ${what} at ${resolved}: ${error instanceof Error ? error.message : String(error)}`);
20
+ }
21
+ try {
22
+ const parsed = JSON.parse(raw);
23
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
24
+ throw new Error('it must be a JSON object');
25
+ return parsed;
26
+ }
27
+ catch (error) {
28
+ throw new Error(`The ${what} at ${resolved} is not valid: ${error instanceof Error ? error.message : String(error)}`);
29
+ }
30
+ }
31
+ const need = (value, name) => {
32
+ if (!value)
33
+ throw new Error(`${name} is required`);
34
+ return encodeURIComponent(value);
35
+ };
36
+ /** Talks to the deploy control plane in the active workspace. Prints the result as JSON. */
37
+ export async function runDeployRemote(operation, args) {
38
+ const ctx = requireWorkspaceContext();
39
+ const api = ApiClient.forProfile(ctx.profile, ctx.credentials);
40
+ const extra = {};
41
+ if (operation === 'deployments.list') {
42
+ if (args.product)
43
+ extra.productTag = args.product;
44
+ if (args.env)
45
+ extra.env = args.env;
46
+ if (args.version)
47
+ extra.version = args.version;
48
+ }
49
+ if (operation === 'functions.list' && args.product)
50
+ extra.productTag = args.product;
51
+ const query = new URLSearchParams(workspaceAuthQuery(ctx, extra)).toString();
52
+ const call = (method, route, body) => api.request(method, `${BASE}${route}?${query}`, body, actorHeaders());
53
+ const fn = (suffix = '') => `/functions/${need(args.product, '--product')}/${need(args.function, '--function')}/versions${suffix}`;
54
+ const version = () => `/${need(args.version, '--version')}`;
55
+ let result;
56
+ switch (operation) {
57
+ case 'releases.register':
58
+ result = await call('POST', '/releases', readJsonFile(args.file, 'release'));
59
+ break;
60
+ case 'plans.create':
61
+ result = await call('POST', '/plans', readJsonFile(args.file, 'plan request'));
62
+ break;
63
+ case 'plans.approve':
64
+ result = await call('POST', `/plans/${need(args.id, 'the plan id')}/approve`, {});
65
+ break;
66
+ case 'plans.apply':
67
+ result = await call('POST', `/plans/${need(args.id, 'the plan id')}/apply`, {});
68
+ break;
69
+ case 'deployments.list':
70
+ result = await call('GET', '/deployments');
71
+ break;
72
+ case 'deployments.get':
73
+ result = await call('GET', `/deployments/${need(args.id, 'the deployment id')}`);
74
+ break;
75
+ case 'deployments.journal':
76
+ result = await call('GET', `/deployments/${need(args.id, 'the deployment id')}/journal`);
77
+ break;
78
+ case 'functions.list':
79
+ result = await call('GET', '/functions');
80
+ break;
81
+ case 'versions.list':
82
+ result = await call('GET', fn());
83
+ break;
84
+ case 'versions.history':
85
+ result = await call('GET', fn(`${version()}/history`));
86
+ break;
87
+ case 'versions.deprecate': {
88
+ if (!args.reason)
89
+ throw new Error('--reason is required');
90
+ result = await call('POST', fn(`${version()}/deprecate`), {
91
+ reason: args.reason,
92
+ ...(args.sunset ? { sunsetAt: args.sunset } : {}),
93
+ ...(args.replacement ? { replacementVersion: args.replacement } : {}),
94
+ });
95
+ break;
96
+ }
97
+ case 'versions.undeprecate':
98
+ result = await call('POST', fn(`${version()}/undeprecate`), {});
99
+ break;
100
+ case 'versions.retire':
101
+ result = await call('POST', fn(`${version()}/retire`), {});
102
+ break;
103
+ default: throw new Error(`Unknown deploy operation ${operation}`);
104
+ }
105
+ console.log(JSON.stringify(result, null, 2));
106
+ }
@@ -0,0 +1,11 @@
1
+ export interface IDeployOptions {
2
+ spec?: string;
3
+ image?: string;
4
+ contract?: string;
5
+ config?: string;
6
+ }
7
+ /**
8
+ * Offline deploy planning. Nothing here contacts a cloud provider or Ductape: it shows what a plan would do,
9
+ * whether the placement is allowed, and whether an apply would be authorised, so a plan can be reviewed first.
10
+ */
11
+ export declare function runDeploy(operation: 'plan' | 'release-hash', options: IDeployOptions): Promise<void>;
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ /** The deploy rules live in the SDK so every client plans identically. The CLI uses the project's installed copy. */
5
+ function loadDeployCore() {
6
+ const require = createRequire(path.join(process.cwd(), 'package.json'));
7
+ try {
8
+ return require('@ductape/sdk/dist/deploy/index.js');
9
+ }
10
+ catch (error) {
11
+ const detail = error instanceof Error ? error.message : String(error);
12
+ throw new Error(`Could not load deploy support from @ductape/sdk. Install a @ductape/sdk version that includes it in this project. (${detail})`);
13
+ }
14
+ }
15
+ function readJson(file, label) {
16
+ const resolved = path.resolve(file);
17
+ let raw;
18
+ try {
19
+ raw = fs.readFileSync(resolved, 'utf8');
20
+ }
21
+ catch (error) {
22
+ throw new Error(`Cannot read ${label} at ${resolved}: ${error instanceof Error ? error.message : String(error)}`);
23
+ }
24
+ try {
25
+ return JSON.parse(raw);
26
+ }
27
+ catch (error) {
28
+ throw new Error(`${label} at ${resolved} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
29
+ }
30
+ }
31
+ /**
32
+ * Offline deploy planning. Nothing here contacts a cloud provider or Ductape: it shows what a plan would do,
33
+ * whether the placement is allowed, and whether an apply would be authorised, so a plan can be reviewed first.
34
+ */
35
+ export async function runDeploy(operation, options) {
36
+ const core = loadDeployCore();
37
+ if (operation === 'release-hash') {
38
+ if (!options.image)
39
+ throw new Error('--image is required (sha256:<64 hex>)');
40
+ if (!options.contract)
41
+ throw new Error('--contract is required (path to the function contract JSON)');
42
+ const config = options.config ? readJson(options.config, 'config') : {};
43
+ const releaseHash = core.computeReleaseHash({
44
+ imageDigest: options.image,
45
+ contract: readJson(options.contract, 'contract'),
46
+ config,
47
+ });
48
+ console.log(JSON.stringify({ releaseHash }, null, 2));
49
+ return;
50
+ }
51
+ if (!options.spec)
52
+ throw new Error('--spec is required (path to a deploy plan spec JSON)');
53
+ const spec = readJson(options.spec, 'spec');
54
+ if (!spec || typeof spec !== 'object' || !spec.desired || !spec.observed) {
55
+ throw new Error('The spec must contain "desired" and "observed"; "observed" is what the provider reports ({ "exists": false } when nothing is there)');
56
+ }
57
+ const plan = core.planDeployment(spec.desired, spec.observed);
58
+ const placement = spec.requirements
59
+ ? core.validatePlacement(spec.requirements, spec.desired.target?.kind, spec.providerLimits)
60
+ : undefined;
61
+ const authorization = spec.policy
62
+ ? core.authorizeApply({
63
+ policy: spec.policy,
64
+ planHash: plan.planHash,
65
+ applier: spec.applier ?? { kind: 'human' },
66
+ approval: spec.approval,
67
+ })
68
+ : undefined;
69
+ const ok = plan.ok && !(placement && placement.length) && authorization?.allowed !== false;
70
+ console.log(JSON.stringify({ ok, plan, ...(placement ? { placement } : {}), ...(authorization ? { authorization } : {}) }, null, 2));
71
+ if (!ok)
72
+ process.exitCode = 1;
73
+ }
@@ -1,4 +1,4 @@
1
- import { getMarketplaceApp, listMarketplaceCategories, searchMarketplaceApps, } from '../lib/platform-api.js';
1
+ import { getMarketplaceApp, listMarketplaceCategories, discoverMarketplaceApps, } from '../lib/platform-api.js';
2
2
  import { printJson } from '../lib/output.js';
3
3
  import { requireWorkspaceContext } from '../lib/workspace-context.js';
4
4
  export async function runMarketplace(verb, opts, args) {
@@ -7,7 +7,7 @@ export async function runMarketplace(verb, opts, args) {
7
7
  switch (verb.toLowerCase()) {
8
8
  case 'search':
9
9
  case 'list':
10
- result = await searchMarketplaceApps(ctx, {
10
+ result = await discoverMarketplaceApps(ctx, {
11
11
  query: opts.query ?? (args.join(' ') || undefined),
12
12
  category: opts.category,
13
13
  limit: opts.limit ? Number(opts.limit) : undefined,
@@ -53,6 +53,12 @@ export function validateMigrationAssurance(file) {
53
53
  const blockers = [];
54
54
  requireNamedRequirements(blockers, 'session_flows', value.session_flows, requiredSession);
55
55
  requireNamedRequirements(blockers, 'feature_resilience', value.feature_resilience, requiredFeature);
56
+ requireNamedRequirements(blockers, 'request_rate_limits', value.request_rate_limits, ['otp', 'login', 'search', 'barcode', 'checkout', 'qr-verification', 'exports']);
57
+ for (const row of value.request_rate_limits ?? []) {
58
+ if (row.primitive !== 'rateLimit' || !row.entryPoints?.length || !row.trustedKeySources?.length) {
59
+ blockers.push(`request_rate_limits.${row.requirement}: keyed rateLimit enforcement, entry points and trusted sources required; provider quotas are not abuse protection`);
60
+ }
61
+ }
56
62
  requireEvidenceArray(blockers, 'third_party_calls', value.third_party_calls);
57
63
  for (const [index, call] of (value.third_party_calls ?? []).entries()) {
58
64
  for (const field of [
@@ -21,6 +21,7 @@ export declare function runProductAppActions(verb: string, opts: {
21
21
  product?: string;
22
22
  app?: string;
23
23
  action?: string;
24
+ env?: string;
24
25
  json?: boolean;
25
26
  }): Promise<void>;
26
27
  export declare function runProductComponents(verb: string, opts: {
@@ -117,7 +117,7 @@ export async function runProductAppActions(verb, opts) {
117
117
  if (verb === 'get') {
118
118
  if (!opts.action)
119
119
  throw new Error('Provide --action <action_tag>');
120
- printJson(await getProductAppAction(ctx, opts.product, opts.app, opts.action), Boolean(opts.json));
120
+ printJson(await getProductAppAction(ctx, opts.product, opts.app, opts.action, opts.env), Boolean(opts.json));
121
121
  return;
122
122
  }
123
123
  throw new Error('Supported verbs: list | get');
@@ -0,0 +1,7 @@
1
+ export declare function runRateLimits(operation: string, tag: string | undefined, options: {
2
+ dir: string;
3
+ env: string;
4
+ workspace?: string;
5
+ product?: string;
6
+ coverage?: string;
7
+ }): Promise<void>;
@@ -0,0 +1,80 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { randomUUID, createHash } from 'node:crypto';
5
+ export async function runRateLimits(operation, tag, options) {
6
+ const require = createRequire(path.join(process.cwd(), 'package.json'));
7
+ const { RateLimitService } = require('@ductape/sdk/dist/resilience/rate-limit.service.js');
8
+ const service = new RateLimitService(undefined, { workspace: options.workspace, product: options.product });
9
+ const directory = path.resolve(options.dir);
10
+ const files = fs.readdirSync(directory).filter(file => file.endsWith('.json')).sort();
11
+ if (!files.length)
12
+ throw new Error('No rate-limit JSON definitions found');
13
+ for (const file of files)
14
+ service.define(JSON.parse(fs.readFileSync(path.join(directory, file), 'utf8')));
15
+ if (operation === 'validate' || operation === 'list') {
16
+ console.log(JSON.stringify({ valid: true, definitions: service.list() }, null, 2));
17
+ return;
18
+ }
19
+ if (operation === 'inspect') {
20
+ const definition = service.list().find((d) => d.tag === tag);
21
+ if (!definition)
22
+ throw new Error('Unknown policy tag');
23
+ console.log(JSON.stringify(definition, null, 2));
24
+ return;
25
+ }
26
+ if (operation === 'audit') {
27
+ if (!options.coverage)
28
+ throw new Error('--coverage is required; endpoint coverage cannot be inferred from definitions');
29
+ const coverage = JSON.parse(fs.readFileSync(options.coverage, 'utf8'));
30
+ const required = ['otp', 'login', 'search', 'barcode', 'checkout', 'qr-verification', 'exports'];
31
+ const tags = new Set(service.list().map((d) => d.tag));
32
+ const issues = required.filter(surface => {
33
+ const row = coverage[surface];
34
+ return !row || row.primitive !== 'rateLimit' || !tags.has(row.tag) || !row.tests?.length ||
35
+ !row.entryPoints?.length || !row.trustedKeySources?.length;
36
+ });
37
+ console.log(JSON.stringify({ valid: !issues.length, missingEvidence: issues, evidenceOnly: true }, null, 2));
38
+ if (issues.length)
39
+ process.exitCode = 1;
40
+ return;
41
+ }
42
+ if (!options.workspace || !options.product)
43
+ throw new Error('--workspace and --product are required');
44
+ if (!process.env.DUCTAPE_REDIS_URL)
45
+ throw new Error('DUCTAPE_REDIS_URL is required');
46
+ const sdkRequire = createRequire(require.resolve('@ductape/sdk'));
47
+ const Redis = sdkRequire('ioredis');
48
+ const redis = new Redis(process.env.DUCTAPE_REDIS_URL, { maxRetriesPerRequest: 1, enableOfflineQueue: false, lazyConnect: true });
49
+ let syntheticKeys = [];
50
+ try {
51
+ await redis.connect();
52
+ service.setRedis(redis);
53
+ if (operation === 'sync') {
54
+ await service.sync(options.env);
55
+ console.log(JSON.stringify({ synced: true, env: options.env, definitions: service.list().map((d) => d.tag) }));
56
+ }
57
+ else {
58
+ const definition = service.list().find((d) => d.tag === tag);
59
+ if (!definition)
60
+ throw new Error('Unknown policy tag');
61
+ // Test in a separate scope: never consume a real actor's allowance.
62
+ const product = `${options.product}:synthetic:${randomUUID()}`;
63
+ service.setContext({ workspace: options.workspace, product });
64
+ const values = Object.fromEntries(definition.key.map((key) => [key, 'synthetic']));
65
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
66
+ const prefix = `ductape:rate-limit:{${hash([options.workspace, product, options.env, tag])}}`;
67
+ syntheticKeys = [`${prefix}:definition`, `${prefix}:${hash([...definition.key].sort().map(key => [key, 'synthetic']))}`];
68
+ console.log(JSON.stringify(await service.run({ tag, env: options.env, values })));
69
+ }
70
+ }
71
+ finally {
72
+ try {
73
+ if (syntheticKeys.length && redis.status === 'ready')
74
+ await redis.del(...syntheticKeys);
75
+ }
76
+ finally {
77
+ redis.disconnect();
78
+ }
79
+ }
80
+ }
@@ -1,4 +1,4 @@
1
- import { buildCrudParams, CONNECT_IDENTIFIER_FIELD, listComponentsFromProduct, listResourceTypes, proxyMethodForVerb, resolveResourceType, } from '../lib/resources.js';
1
+ import { buildCrudParams, CONNECT_IDENTIFIER_FIELD, listComponentsFromProduct, proxyMethodForModule, listResourceTypes, proxyMethodForVerb, resolveResourceType, } from '../lib/resources.js';
2
2
  import { resolveResourceSchema } from '../lib/forms/index.js';
3
3
  import { isInteractive, promptTag } from '../lib/forms/prompt.js';
4
4
  import { toInteractiveOpts } from '../lib/interactive-opts.js';
@@ -311,11 +311,11 @@ export async function runResourceCrud(typeName, verb, opts, extraArgs) {
311
311
  // body) destructures product's string as `options` and fails with "No database connection
312
312
  // established", not a useful error about the definition update. The definition updater is a
313
313
  // separate method, databases.updateDatabase(product, database, data).
314
- const proxyMethod = (module === 'models' || module === 'feature') && method === 'list'
314
+ const proxyMethod = proxyMethodForModule(module, (module === 'models' || module === 'feature') && method === 'list'
315
315
  ? 'fetchAll'
316
316
  : module === 'databases' && method === 'update'
317
317
  ? 'updateDatabase'
318
- : method;
318
+ : method);
319
319
  const interactive = toInteractiveOpts(opts);
320
320
  let tag = opts.tag ?? extraArgs[0];
321
321
  if (!tag && ['get', 'update', 'delete'].includes(crud) && isInteractive(interactive)) {