@firetail/finchly 0.0.8 → 0.0.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.
- package/CHANGELOG.md +15 -0
- package/README.md +87 -2
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/queue.d.ts +70 -0
- package/dist/queue.js +95 -0
- package/dist/secrets.d.ts +39 -0
- package/dist/secrets.js +97 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,21 @@ All notable changes to `@firetail/finchly`. Versions follow semver.
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.0.9 - 2026-11-12
|
|
8
|
+
|
|
9
|
+
- `createSecrets({ service })`: secrets kept with the platform for each
|
|
10
|
+
tenant. `secrets.forTenant(caller.tenantId)` gives `get`, `set`,
|
|
11
|
+
`delete` and `list`, and `encrypt` and `decrypt` under the tenant's key.
|
|
12
|
+
The manifest must set `permissions.secrets`.
|
|
13
|
+
- `createQueue({ service })`: the platform queue.
|
|
14
|
+
`queue.forTenant(caller.tenantId).publish(topic, bodies)` publishes for
|
|
15
|
+
a tenant; `queue.lease(topic)` hands out messages of every tenant, each
|
|
16
|
+
with `tenantId`, `ack()`, `retry()` and `deadLetter()`. The manifest
|
|
17
|
+
lists the topics in `permissions.queue`.
|
|
18
|
+
- New error codes: `secrets_not_granted`, `secrets_unavailable`,
|
|
19
|
+
`secrets_cannot_decrypt`, `queue_not_granted`, `queue_unavailable`.
|
|
20
|
+
- **Needs a platform that serves secrets and the queue.**
|
|
21
|
+
|
|
7
22
|
## 0.0.8 - 2026-11-12
|
|
8
23
|
|
|
9
24
|
- **Breaking:** the database is per tenant. `connectDatabase` no longer
|
package/README.md
CHANGED
|
@@ -234,6 +234,91 @@ To run a service on its own, without a platform, give the URL directly:
|
|
|
234
234
|
`connectDatabase({ url, slug })`. Each tenant's schema is then made the
|
|
235
235
|
first time it is used.
|
|
236
236
|
|
|
237
|
+
### Secrets
|
|
238
|
+
|
|
239
|
+
A service whose manifest sets `permissions.secrets` keeps secrets with the
|
|
240
|
+
platform, separately for each tenant:
|
|
241
|
+
|
|
242
|
+
```js
|
|
243
|
+
import { createSecrets } from "@firetail/finchly";
|
|
244
|
+
|
|
245
|
+
const secrets = createSecrets({ service });
|
|
246
|
+
|
|
247
|
+
// Per request: the secrets of the caller's tenant.
|
|
248
|
+
const mine = secrets.forTenant(caller.tenantId);
|
|
249
|
+
|
|
250
|
+
await mine.set("slack.token", token);
|
|
251
|
+
const value = await mine.get("slack.token"); // undefined if there is none
|
|
252
|
+
await mine.list(); // ["slack.token"]
|
|
253
|
+
await mine.delete("slack.token"); // true if there was one
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
- A name is 1 to 100 letters, digits, dots, dashes or underscores. A value
|
|
257
|
+
is text of at most 64 KiB. Do not log a value.
|
|
258
|
+
- A tenant's secrets are read with that tenant's id and no other. Take the
|
|
259
|
+
id from a verified identity, never from the request itself.
|
|
260
|
+
|
|
261
|
+
For values the service keeps in its own tables, the platform encrypts and
|
|
262
|
+
decrypts under the tenant's key:
|
|
263
|
+
|
|
264
|
+
```js
|
|
265
|
+
const sealed = await mine.encrypt(cardNumber, `card:${id}`);
|
|
266
|
+
const opened = await mine.decrypt(sealed, `card:${id}`); // a Uint8Array
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
The context says what the value is. The same context must be given to
|
|
270
|
+
decrypt, so a value copied to another row does not open there. What was
|
|
271
|
+
encrypted for another tenant, another service or another context, or has
|
|
272
|
+
been changed, rejects with `secrets_cannot_decrypt`.
|
|
273
|
+
|
|
274
|
+
A manifest that does not ask for secrets gets `secrets_not_granted`. Any
|
|
275
|
+
other refusal is `secrets_unavailable`.
|
|
276
|
+
|
|
277
|
+
### The queue
|
|
278
|
+
|
|
279
|
+
A message belongs to a tenant. The manifest lists the topics the service
|
|
280
|
+
publishes to and consumes, in `permissions.queue.publish` and
|
|
281
|
+
`permissions.queue.consume`.
|
|
282
|
+
|
|
283
|
+
```js
|
|
284
|
+
import { createQueue } from "@firetail/finchly";
|
|
285
|
+
|
|
286
|
+
const queue = createQueue({ service });
|
|
287
|
+
|
|
288
|
+
// Per request: publish for the caller's tenant.
|
|
289
|
+
await queue.forTenant(caller.tenantId).publish("notifications", [{ to: caller.subject, text: "Done" }]);
|
|
290
|
+
|
|
291
|
+
// A worker: take messages of every tenant, and handle each in its own.
|
|
292
|
+
for (const message of await queue.lease("notifications", { max: 10, visibilitySeconds: 60 })) {
|
|
293
|
+
const db = database.forTenant(message.tenantId);
|
|
294
|
+
try {
|
|
295
|
+
await deliver(db, message.body);
|
|
296
|
+
await message.ack();
|
|
297
|
+
} catch {
|
|
298
|
+
await message.retry();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
- **Publishing** takes 1 to 100 bodies, each any JSON value of at most
|
|
304
|
+
256 KiB, and resolves with their ids. All are published or none.
|
|
305
|
+
`{ delaySeconds }` holds them back, up to 7 days.
|
|
306
|
+
- **Leasing** hands out messages for `visibilitySeconds` (default 60). A
|
|
307
|
+
message not answered for in that time is handed out again. An empty list
|
|
308
|
+
means there is nothing to do; ask again later. `{ tenantId }` takes one
|
|
309
|
+
tenant's messages only.
|
|
310
|
+
- **Each message says which tenant it is for.** Handle it in that tenant.
|
|
311
|
+
- **Answer for every message**: `ack()` when it is handled, `retry()` to
|
|
312
|
+
have it handed out again after a wait that doubles each time (or
|
|
313
|
+
`retry({ delaySeconds })`), `deadLetter(reason)` when it never will be
|
|
314
|
+
handled. Each resolves with `false` if the time ran out and the message
|
|
315
|
+
went to another consumer. A message handed out five times without being
|
|
316
|
+
handled is set aside.
|
|
317
|
+
- A message may be handed out more than once, so handling one twice must be
|
|
318
|
+
harmless.
|
|
319
|
+
- A topic the manifest does not list rejects with `queue_not_granted`. Any
|
|
320
|
+
other refusal is `queue_unavailable`.
|
|
321
|
+
|
|
237
322
|
### What every request carries
|
|
238
323
|
|
|
239
324
|
Every request this SDK makes to the platform says which SDK and which
|
|
@@ -274,8 +359,8 @@ not leak them.
|
|
|
274
359
|
| `service` | Call other services through the gateway, as the service or for a user | Done, for built-in services and for apps |
|
|
275
360
|
| `db` | PostgreSQL: queries, transactions, advisory locks, migrations | Done |
|
|
276
361
|
| `blobs` | Object storage with conditional writes | Planned |
|
|
277
|
-
| `queue` | Publish, lease, ack,
|
|
278
|
-
| `secrets` | Secrets and
|
|
362
|
+
| `queue` | Publish, lease, ack, retry, dead-letter | Done |
|
|
363
|
+
| `secrets` | Secrets, and encryption under the tenant's key | Done |
|
|
279
364
|
| `llm` | Model calls through the platform | Planned |
|
|
280
365
|
| `audit`, `usage`, `notify`, `schedule`, `connectors` | Clients for platform services | Planned |
|
|
281
366
|
| `ui` | Shared header, footer and theme | Planned |
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type FinchlyErrorCode = "config_invalid" | "manifest_invalid" | "manifest_unreadable" | "identity_invalid" | "gateway_unreachable" | "platform_api_unsupported" | "service_call_invalid" | "service_key_rejected" | "app_registration_refused" | "app_pending_approval" | "database_unavailable" | "database_not_granted" | "migration_invalid";
|
|
1
|
+
export type FinchlyErrorCode = "config_invalid" | "manifest_invalid" | "manifest_unreadable" | "identity_invalid" | "gateway_unreachable" | "platform_api_unsupported" | "service_call_invalid" | "service_key_rejected" | "app_registration_refused" | "app_pending_approval" | "database_unavailable" | "database_not_granted" | "migration_invalid" | "secrets_not_granted" | "secrets_unavailable" | "secrets_cannot_decrypt" | "queue_not_granted" | "queue_unavailable";
|
|
2
2
|
/**
|
|
3
3
|
* Every error this SDK throws on purpose. `code` is stable and safe to
|
|
4
4
|
* branch on; `problems` lists each thing that was wrong, so a caller can
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,10 @@ export { checkManifest, loadManifest } from "./manifest.js";
|
|
|
10
10
|
export type { Manifest, ManifestPermissions, PublicPath } from "./manifest.js";
|
|
11
11
|
export { MANIFEST_VERSION, PLATFORM_API_VERSION, SUPPORTED_PLATFORM_API_VERSIONS, } from "./platform-api.js";
|
|
12
12
|
export { PLATFORM_API_VERSION_HEADER, SDK_HEADER, SDK_REQUEST_HEADERS, SDK_VERSION_HEADER, } from "./request-headers.js";
|
|
13
|
+
export { createQueue } from "./queue.js";
|
|
14
|
+
export type { LeaseOptions, Message, PublishOptions, Queue, QueueOptions, TenantQueue } from "./queue.js";
|
|
15
|
+
export { createSecrets } from "./secrets.js";
|
|
16
|
+
export type { Secrets, SecretsOptions, TenantSecrets } from "./secrets.js";
|
|
13
17
|
export { createServiceClient, enrolmentFrom } from "./service.js";
|
|
14
18
|
export type { CallOptions, Enrolment, ServiceClient, ServiceClientOptions } from "./service.js";
|
|
15
19
|
export { SDK_NAME, SDK_VERSION } from "./version.js";
|
package/dist/index.js
CHANGED
|
@@ -5,5 +5,7 @@ export { IDENTITY_HEADER, createIdentityVerifier } from "./identity.js";
|
|
|
5
5
|
export { checkManifest, loadManifest } from "./manifest.js";
|
|
6
6
|
export { MANIFEST_VERSION, PLATFORM_API_VERSION, SUPPORTED_PLATFORM_API_VERSIONS, } from "./platform-api.js";
|
|
7
7
|
export { PLATFORM_API_VERSION_HEADER, SDK_HEADER, SDK_REQUEST_HEADERS, SDK_VERSION_HEADER, } from "./request-headers.js";
|
|
8
|
+
export { createQueue } from "./queue.js";
|
|
9
|
+
export { createSecrets } from "./secrets.js";
|
|
8
10
|
export { createServiceClient, enrolmentFrom } from "./service.js";
|
|
9
11
|
export { SDK_NAME, SDK_VERSION } from "./version.js";
|
package/dist/queue.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { ServiceClient } from "./service.js";
|
|
2
|
+
export interface PublishOptions {
|
|
3
|
+
/** Not handed out before this many seconds have passed. Up to 7 days. */
|
|
4
|
+
readonly delaySeconds?: number;
|
|
5
|
+
}
|
|
6
|
+
/** The queue, for one tenant: where messages are published. */
|
|
7
|
+
export interface TenantQueue {
|
|
8
|
+
readonly tenantId: string;
|
|
9
|
+
/**
|
|
10
|
+
* Publish messages to a topic, for this tenant. Each body is any JSON
|
|
11
|
+
* value of at most 256 KiB; 1 to 100 at a time. Resolves with their ids.
|
|
12
|
+
* All of them are published, or none.
|
|
13
|
+
*/
|
|
14
|
+
publish(topic: string, bodies: readonly unknown[], options?: PublishOptions): Promise<string[]>;
|
|
15
|
+
}
|
|
16
|
+
/** A message that was handed out. Answer for it with `ack`, `retry` or `deadLetter`. */
|
|
17
|
+
export interface Message {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
/** The tenant the message is for. Handle it in that tenant, and no other. */
|
|
20
|
+
readonly tenantId: string;
|
|
21
|
+
readonly body: unknown;
|
|
22
|
+
/** How many times it has been handed out, this time included. */
|
|
23
|
+
readonly attempts: number;
|
|
24
|
+
/** The service that published it. */
|
|
25
|
+
readonly publishedBy: string;
|
|
26
|
+
readonly publishedAt: Date;
|
|
27
|
+
/**
|
|
28
|
+
* It was handled: delete it. Resolves with false if this consumer no
|
|
29
|
+
* longer holds it, because the time ran out and it was handed to another.
|
|
30
|
+
*/
|
|
31
|
+
ack(): Promise<boolean>;
|
|
32
|
+
/**
|
|
33
|
+
* It was not handled: have it handed out again, after `delaySeconds`, or
|
|
34
|
+
* after a wait that doubles each time if that is left out.
|
|
35
|
+
*/
|
|
36
|
+
retry(options?: {
|
|
37
|
+
readonly delaySeconds?: number;
|
|
38
|
+
}): Promise<boolean>;
|
|
39
|
+
/** It never will be handled: set it aside. It is kept, and not handed out again. */
|
|
40
|
+
deadLetter(reason?: string): Promise<boolean>;
|
|
41
|
+
}
|
|
42
|
+
export interface LeaseOptions {
|
|
43
|
+
/** The most messages to take. 1 to 100, default 10. */
|
|
44
|
+
readonly max?: number;
|
|
45
|
+
/**
|
|
46
|
+
* How long this consumer has to answer before a message is handed to
|
|
47
|
+
* another. 1 second to 12 hours, default 60 seconds.
|
|
48
|
+
*/
|
|
49
|
+
readonly visibilitySeconds?: number;
|
|
50
|
+
/** Take one tenant's messages only. Default: every tenant that uses this service. */
|
|
51
|
+
readonly tenantId?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface Queue {
|
|
54
|
+
/**
|
|
55
|
+
* The queue for one tenant, to publish to: `caller.tenantId` of the
|
|
56
|
+
* request being handled. Take the id from a verified identity, never from
|
|
57
|
+
* the request itself.
|
|
58
|
+
*/
|
|
59
|
+
forTenant(tenantId: string): TenantQueue;
|
|
60
|
+
/**
|
|
61
|
+
* Take messages from a topic. Each comes with the tenant it is for. An
|
|
62
|
+
* empty list means there is nothing to do; ask again later.
|
|
63
|
+
*/
|
|
64
|
+
lease(topic: string, options?: LeaseOptions): Promise<Message[]>;
|
|
65
|
+
}
|
|
66
|
+
export interface QueueOptions {
|
|
67
|
+
/** The service's client. Every call goes through it. */
|
|
68
|
+
readonly service: Pick<ServiceClient, "call">;
|
|
69
|
+
}
|
|
70
|
+
export declare function createQueue(options: QueueOptions): Queue;
|
package/dist/queue.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// The platform queue. See spec/queue.md in the platform repository.
|
|
2
|
+
//
|
|
3
|
+
// A message belongs to a tenant. Publishing is done for one tenant, on a
|
|
4
|
+
// handle made with `forTenant`. Consuming is the service's own work: one
|
|
5
|
+
// running copy serves every tenant, so `lease` hands out messages of every
|
|
6
|
+
// tenant that uses the service, each with the tenant it is for.
|
|
7
|
+
//
|
|
8
|
+
// The manifest lists what may be published and consumed, in
|
|
9
|
+
// permissions.queue.
|
|
10
|
+
import { FinchlyError } from "./errors.js";
|
|
11
|
+
const TENANT_ID = /^t_[a-z2-7]{16}$/;
|
|
12
|
+
const TOPIC = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
|
|
13
|
+
const BASE = "/api/apps/self/queue";
|
|
14
|
+
async function failure(response, what, topic) {
|
|
15
|
+
const answer = (await response.json().catch(() => null));
|
|
16
|
+
const error = typeof answer?.error === "string" ? answer.error : undefined;
|
|
17
|
+
if (error === "not_granted") {
|
|
18
|
+
return new FinchlyError("queue_not_granted", `This service may not ${what}${topic ? ` ${topic}` : ""}`, [
|
|
19
|
+
`List the topic in permissions.queue.${what === "publish to" ? "publish" : "consume"} in the manifest`,
|
|
20
|
+
]);
|
|
21
|
+
}
|
|
22
|
+
return new FinchlyError("queue_unavailable", `The platform queue did not ${what === "publish to" ? "take the messages" : "answer"}`, [
|
|
23
|
+
`it answered ${response.status}${error ? ` ${error}` : ""}${typeof answer?.detail === "string" ? `: ${answer.detail}` : ""}`,
|
|
24
|
+
]);
|
|
25
|
+
}
|
|
26
|
+
function checkTopic(topic) {
|
|
27
|
+
if (typeof topic !== "string" || topic.length < 2 || topic.length > 60 || !TOPIC.test(topic)) {
|
|
28
|
+
throw new FinchlyError("queue_unavailable", "A topic is 2 to 60 lower-case letters, digits and dashes");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function checkTenant(tenantId, where) {
|
|
32
|
+
if (typeof tenantId !== "string" || !TENANT_ID.test(tenantId)) {
|
|
33
|
+
throw new FinchlyError("queue_unavailable", `${where} needs a tenant id, as in caller.tenantId`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function createQueue(options) {
|
|
37
|
+
const { service } = options;
|
|
38
|
+
const post = (path, body, tenantId) => service.call("core", `${BASE}${path}`, {
|
|
39
|
+
method: "POST",
|
|
40
|
+
headers: { "content-type": "application/json" },
|
|
41
|
+
body: JSON.stringify(body),
|
|
42
|
+
...(tenantId !== undefined ? { tenantId } : {}),
|
|
43
|
+
});
|
|
44
|
+
/** Answer for a message that was handed out. False if this consumer no longer holds it. */
|
|
45
|
+
async function answer(action, held, extra) {
|
|
46
|
+
const response = await post(`/${action}`, { ...held, ...extra });
|
|
47
|
+
if (response.status === 409) {
|
|
48
|
+
await response.body?.cancel();
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
if (response.status !== 204)
|
|
52
|
+
throw await failure(response, "consume");
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
forTenant(tenantId) {
|
|
57
|
+
checkTenant(tenantId, "forTenant");
|
|
58
|
+
return {
|
|
59
|
+
tenantId,
|
|
60
|
+
async publish(topic, bodies, publishOptions = {}) {
|
|
61
|
+
checkTopic(topic);
|
|
62
|
+
if (!Array.isArray(bodies) || bodies.length === 0) {
|
|
63
|
+
throw new FinchlyError("queue_unavailable", "publish takes a list of at least one message body");
|
|
64
|
+
}
|
|
65
|
+
const { delaySeconds } = publishOptions;
|
|
66
|
+
const messages = bodies.map((body) => ({ body: body === undefined ? null : body, ...(delaySeconds !== undefined ? { delaySeconds } : {}) }));
|
|
67
|
+
const response = await post(`/${topic}/messages`, { messages }, tenantId);
|
|
68
|
+
if (response.status !== 201)
|
|
69
|
+
throw await failure(response, "publish to", topic);
|
|
70
|
+
return (await response.json()).ids;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
async lease(topic, leaseOptions = {}) {
|
|
75
|
+
checkTopic(topic);
|
|
76
|
+
const { max, visibilitySeconds, tenantId } = leaseOptions;
|
|
77
|
+
if (tenantId !== undefined)
|
|
78
|
+
checkTenant(tenantId, "lease");
|
|
79
|
+
const response = await post(`/${topic}/lease`, { ...(max !== undefined ? { max } : {}), ...(visibilitySeconds !== undefined ? { visibilitySeconds } : {}) }, tenantId);
|
|
80
|
+
if (response.status !== 200)
|
|
81
|
+
throw await failure(response, "consume", topic);
|
|
82
|
+
const { messages } = (await response.json());
|
|
83
|
+
return messages.map(({ leaseToken, publishedAt, ...message }) => {
|
|
84
|
+
const held = { tenantId: message.tenantId, id: message.id, leaseToken };
|
|
85
|
+
return {
|
|
86
|
+
...message,
|
|
87
|
+
publishedAt: new Date(publishedAt),
|
|
88
|
+
ack: () => answer("ack", held, {}),
|
|
89
|
+
retry: (retryOptions = {}) => answer("nack", held, retryOptions.delaySeconds !== undefined ? { delaySeconds: retryOptions.delaySeconds } : {}),
|
|
90
|
+
deadLetter: (reason) => answer("dead-letter", held, reason !== undefined ? { reason } : {}),
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ServiceClient } from "./service.js";
|
|
2
|
+
/** A service's secrets in one tenant. */
|
|
3
|
+
export interface TenantSecrets {
|
|
4
|
+
readonly tenantId: string;
|
|
5
|
+
/** A secret's value, or undefined if there is none by that name. Do not log it. */
|
|
6
|
+
get(name: string): Promise<string | undefined>;
|
|
7
|
+
/** Keep a secret, replacing any there was. The value is text of at most 64 KiB. */
|
|
8
|
+
set(name: string, value: string): Promise<void>;
|
|
9
|
+
/** Forget a secret. Resolves with whether there was one. */
|
|
10
|
+
delete(name: string): Promise<boolean>;
|
|
11
|
+
/** The names of the secrets kept. Never the values. */
|
|
12
|
+
list(): Promise<string[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Have the platform encrypt something under the tenant's key, to keep in
|
|
15
|
+
* the service's own tables. `context` says what the value is, for example
|
|
16
|
+
* "payments:card:7"; the same context must be given to decrypt, so a
|
|
17
|
+
* value moved to another row does not open there.
|
|
18
|
+
*/
|
|
19
|
+
encrypt(plaintext: string | Uint8Array, context?: string): Promise<string>;
|
|
20
|
+
/**
|
|
21
|
+
* Open what `encrypt` gave. Rejects with `secrets_cannot_decrypt` if it
|
|
22
|
+
* was made for another tenant, another service or another context, or
|
|
23
|
+
* has been changed.
|
|
24
|
+
*/
|
|
25
|
+
decrypt(ciphertext: string, context?: string): Promise<Uint8Array>;
|
|
26
|
+
}
|
|
27
|
+
export interface Secrets {
|
|
28
|
+
/**
|
|
29
|
+
* The secrets of one tenant: `caller.tenantId` of the request being
|
|
30
|
+
* handled. Take the id from a verified identity, never from the request
|
|
31
|
+
* itself.
|
|
32
|
+
*/
|
|
33
|
+
forTenant(tenantId: string): TenantSecrets;
|
|
34
|
+
}
|
|
35
|
+
export interface SecretsOptions {
|
|
36
|
+
/** The service's client. Every call goes through it. */
|
|
37
|
+
readonly service: Pick<ServiceClient, "call">;
|
|
38
|
+
}
|
|
39
|
+
export declare function createSecrets(options: SecretsOptions): Secrets;
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Secrets a service keeps with the platform, for each tenant, and
|
|
2
|
+
// encryption under the tenant's key. See spec/secrets.md in the platform
|
|
3
|
+
// repository.
|
|
4
|
+
//
|
|
5
|
+
// The manifest must set permissions.secrets. Everything here is for one
|
|
6
|
+
// tenant: the handle that reads and writes is made with `forTenant`.
|
|
7
|
+
import { FinchlyError } from "./errors.js";
|
|
8
|
+
const TENANT_ID = /^t_[a-z2-7]{16}$/;
|
|
9
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
|
|
10
|
+
const BASE = "/api/apps/self";
|
|
11
|
+
async function failure(response, what) {
|
|
12
|
+
const answer = (await response.json().catch(() => null));
|
|
13
|
+
const error = typeof answer?.error === "string" ? answer.error : undefined;
|
|
14
|
+
if (error === "not_granted") {
|
|
15
|
+
return new FinchlyError("secrets_not_granted", "The platform keeps no secrets for this service", [
|
|
16
|
+
"Set permissions.secrets to true in the manifest",
|
|
17
|
+
]);
|
|
18
|
+
}
|
|
19
|
+
return new FinchlyError("secrets_unavailable", `The platform did not ${what}`, [
|
|
20
|
+
`it answered ${response.status}${error ? ` ${error}` : ""}`,
|
|
21
|
+
]);
|
|
22
|
+
}
|
|
23
|
+
export function createSecrets(options) {
|
|
24
|
+
const { service } = options;
|
|
25
|
+
return {
|
|
26
|
+
forTenant(tenantId) {
|
|
27
|
+
if (typeof tenantId !== "string" || !TENANT_ID.test(tenantId)) {
|
|
28
|
+
throw new FinchlyError("secrets_unavailable", "forTenant needs a tenant id, as in caller.tenantId");
|
|
29
|
+
}
|
|
30
|
+
const call = (path, method = "GET", body) => service.call("core", `${BASE}${path}`, {
|
|
31
|
+
tenantId,
|
|
32
|
+
method,
|
|
33
|
+
...(body !== undefined ? { headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {}),
|
|
34
|
+
});
|
|
35
|
+
const named = (name) => {
|
|
36
|
+
if (typeof name !== "string" || !NAME.test(name)) {
|
|
37
|
+
throw new FinchlyError("secrets_unavailable", "A secret's name is 1 to 100 letters, digits, dots, dashes or underscores");
|
|
38
|
+
}
|
|
39
|
+
return `/secrets/${name}`;
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
tenantId,
|
|
43
|
+
async get(name) {
|
|
44
|
+
const response = await call(named(name));
|
|
45
|
+
if (response.status === 404) {
|
|
46
|
+
await response.body?.cancel();
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
if (response.status !== 200)
|
|
50
|
+
throw await failure(response, "give the secret");
|
|
51
|
+
return (await response.json()).value;
|
|
52
|
+
},
|
|
53
|
+
async set(name, value) {
|
|
54
|
+
if (typeof value !== "string")
|
|
55
|
+
throw new FinchlyError("secrets_unavailable", "A secret's value is text");
|
|
56
|
+
const response = await call(named(name), "PUT", { value });
|
|
57
|
+
if (response.status !== 204)
|
|
58
|
+
throw await failure(response, "keep the secret");
|
|
59
|
+
},
|
|
60
|
+
async delete(name) {
|
|
61
|
+
const response = await call(named(name), "DELETE");
|
|
62
|
+
if (response.status === 404) {
|
|
63
|
+
await response.body?.cancel();
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
if (response.status !== 204)
|
|
67
|
+
throw await failure(response, "forget the secret");
|
|
68
|
+
return true;
|
|
69
|
+
},
|
|
70
|
+
async list() {
|
|
71
|
+
const response = await call("/secrets");
|
|
72
|
+
if (response.status !== 200)
|
|
73
|
+
throw await failure(response, "list the secrets");
|
|
74
|
+
return (await response.json()).names;
|
|
75
|
+
},
|
|
76
|
+
async encrypt(plaintext, context) {
|
|
77
|
+
const bytes = typeof plaintext === "string" ? Buffer.from(plaintext, "utf8") : Buffer.from(plaintext);
|
|
78
|
+
const response = await call("/encrypt", "POST", { plaintext: bytes.toString("base64"), ...(context !== undefined ? { context } : {}) });
|
|
79
|
+
if (response.status !== 200)
|
|
80
|
+
throw await failure(response, "encrypt");
|
|
81
|
+
return (await response.json()).ciphertext;
|
|
82
|
+
},
|
|
83
|
+
async decrypt(ciphertext, context) {
|
|
84
|
+
const response = await call("/decrypt", "POST", { ciphertext, ...(context !== undefined ? { context } : {}) });
|
|
85
|
+
if (response.status === 400) {
|
|
86
|
+
await response.body?.cancel();
|
|
87
|
+
// Another tenant's, another service's, another context's, or changed: the platform does not say which.
|
|
88
|
+
throw new FinchlyError("secrets_cannot_decrypt", "The platform could not decrypt this");
|
|
89
|
+
}
|
|
90
|
+
if (response.status !== 200)
|
|
91
|
+
throw await failure(response, "decrypt");
|
|
92
|
+
return Buffer.from((await response.json()).plaintext, "base64");
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|