@gadicc/loom 1.35.2 → 1.36.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.
Files changed (107) hide show
  1. package/README.md +56 -0
  2. package/THIRD_PARTY_NOTICES.md +12 -9
  3. package/esm/src/cli/externalSkills.d.ts.map +1 -1
  4. package/esm/src/cli/externalSkills.js +25 -20
  5. package/esm/src/cli/mod.d.ts +72 -1
  6. package/esm/src/cli/mod.d.ts.map +1 -1
  7. package/esm/src/cli/mod.js +771 -36
  8. package/esm/src/cli/projectSkills.d.ts +10 -3
  9. package/esm/src/cli/projectSkills.d.ts.map +1 -1
  10. package/esm/src/cli/projectSkills.js +173 -49
  11. package/esm/src/cli/vercelBuildEnv.d.ts +28 -0
  12. package/esm/src/cli/vercelBuildEnv.d.ts.map +1 -1
  13. package/esm/src/cli/vercelBuildEnv.js +120 -30
  14. package/esm/src/mail/postal.d.ts.map +1 -1
  15. package/esm/src/mail/postal.js +2 -1
  16. package/esm/src/next/secrets/mod.d.ts +108 -0
  17. package/esm/src/next/secrets/mod.d.ts.map +1 -0
  18. package/esm/src/next/secrets/mod.js +176 -0
  19. package/esm/src/secrets/encoding.d.ts +32 -0
  20. package/esm/src/secrets/encoding.d.ts.map +1 -0
  21. package/esm/src/secrets/encoding.js +87 -0
  22. package/esm/src/secrets/errors.d.ts +45 -0
  23. package/esm/src/secrets/errors.d.ts.map +1 -0
  24. package/esm/src/secrets/errors.js +39 -0
  25. package/esm/src/secrets/fingerprint.d.ts +43 -0
  26. package/esm/src/secrets/fingerprint.d.ts.map +1 -0
  27. package/esm/src/secrets/fingerprint.js +87 -0
  28. package/esm/src/secrets/frame.d.ts +34 -0
  29. package/esm/src/secrets/frame.d.ts.map +1 -0
  30. package/esm/src/secrets/frame.js +86 -0
  31. package/esm/src/secrets/keyring.d.ts +62 -0
  32. package/esm/src/secrets/keyring.d.ts.map +1 -0
  33. package/esm/src/secrets/keyring.js +160 -0
  34. package/esm/src/secrets/legacy.d.ts +60 -0
  35. package/esm/src/secrets/legacy.d.ts.map +1 -0
  36. package/esm/src/secrets/legacy.js +147 -0
  37. package/esm/src/secrets/maintenance.d.ts +173 -0
  38. package/esm/src/secrets/maintenance.d.ts.map +1 -0
  39. package/esm/src/secrets/maintenance.js +315 -0
  40. package/esm/src/secrets/mod.d.ts +6 -0
  41. package/esm/src/secrets/mod.d.ts.map +1 -0
  42. package/esm/src/secrets/mod.js +5 -0
  43. package/esm/src/secrets/secrets.d.ts +192 -0
  44. package/esm/src/secrets/secrets.d.ts.map +1 -0
  45. package/esm/src/secrets/secrets.js +528 -0
  46. package/package.json +50 -2
  47. package/script/src/cli/externalSkills.d.ts.map +1 -1
  48. package/script/src/cli/externalSkills.js +25 -20
  49. package/script/src/cli/mod.d.ts +72 -1
  50. package/script/src/cli/mod.d.ts.map +1 -1
  51. package/script/src/cli/mod.js +772 -33
  52. package/script/src/cli/projectSkills.d.ts +10 -3
  53. package/script/src/cli/projectSkills.d.ts.map +1 -1
  54. package/script/src/cli/projectSkills.js +173 -49
  55. package/script/src/cli/vercelBuildEnv.d.ts +28 -0
  56. package/script/src/cli/vercelBuildEnv.d.ts.map +1 -1
  57. package/script/src/cli/vercelBuildEnv.js +121 -30
  58. package/script/src/mail/postal.d.ts.map +1 -1
  59. package/script/src/mail/postal.js +2 -1
  60. package/script/src/next/secrets/mod.d.ts +108 -0
  61. package/script/src/next/secrets/mod.d.ts.map +1 -0
  62. package/script/src/next/secrets/mod.js +218 -0
  63. package/script/src/secrets/encoding.d.ts +32 -0
  64. package/script/src/secrets/encoding.d.ts.map +1 -0
  65. package/script/src/secrets/encoding.js +95 -0
  66. package/script/src/secrets/errors.d.ts +45 -0
  67. package/script/src/secrets/errors.d.ts.map +1 -0
  68. package/script/src/secrets/errors.js +45 -0
  69. package/script/src/secrets/fingerprint.d.ts +43 -0
  70. package/script/src/secrets/fingerprint.d.ts.map +1 -0
  71. package/script/src/secrets/fingerprint.js +92 -0
  72. package/script/src/secrets/frame.d.ts +34 -0
  73. package/script/src/secrets/frame.d.ts.map +1 -0
  74. package/script/src/secrets/frame.js +91 -0
  75. package/script/src/secrets/keyring.d.ts +62 -0
  76. package/script/src/secrets/keyring.d.ts.map +1 -0
  77. package/script/src/secrets/keyring.js +202 -0
  78. package/script/src/secrets/legacy.d.ts +60 -0
  79. package/script/src/secrets/legacy.d.ts.map +1 -0
  80. package/script/src/secrets/legacy.js +186 -0
  81. package/script/src/secrets/maintenance.d.ts +173 -0
  82. package/script/src/secrets/maintenance.d.ts.map +1 -0
  83. package/script/src/secrets/maintenance.js +323 -0
  84. package/script/src/secrets/mod.d.ts +6 -0
  85. package/script/src/secrets/mod.d.ts.map +1 -0
  86. package/script/src/secrets/mod.js +24 -0
  87. package/script/src/secrets/secrets.d.ts +192 -0
  88. package/script/src/secrets/secrets.d.ts.map +1 -0
  89. package/script/src/secrets/secrets.js +532 -0
  90. package/skills/loom/SKILL.md +74 -222
  91. package/skills/loom/references/dependency-upgrades.md +26 -0
  92. package/skills/loom/references/local-development.md +157 -0
  93. package/skills/loom/references/release-safety.md +118 -0
  94. package/skills/loom/references/release-trusted-sources.md +55 -0
  95. package/skills/loom/references/tools-and-skills.md +83 -0
  96. package/skills/loom-api-keys/SKILL.md +1 -1
  97. package/skills/loom-auth/SKILL.md +7 -60
  98. package/skills/loom-auth/references/secrets-and-rotation.md +61 -0
  99. package/skills/loom-db/SKILL.md +4 -79
  100. package/skills/loom-files/SKILL.md +4 -2
  101. package/skills/loom-files/references/provider-configuration.md +142 -0
  102. package/skills/loom-jobs/SKILL.md +9 -8
  103. package/skills/loom-lingui/SKILL.md +5 -3
  104. package/skills/loom-secrets/SKILL.md +252 -0
  105. package/skills/loom-torvalds-review/SKILL.md +9 -6
  106. package/skills/loom-torvalds-review/references/context-profiles.md +2 -1
  107. package/skills/upgrade-deps/SKILL.md +15 -7
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Why a sealed value could not be opened.
3
+ *
4
+ * For operator logs and metrics only. Forwarding it to an end user tells a
5
+ * caller who submits tokens which key ids exist and whether a guess reached
6
+ * the cipher.
7
+ */
8
+ export type SecretFailureReason =
9
+ /** Not a string this module could have produced, or the wrong kind. */
10
+ "malformed"
11
+ /** The key version named in the string is not configured. */
12
+ | "unknown-key"
13
+ /** The key version is configured but its value cannot be used. */
14
+ | "key-unavailable"
15
+ /** The key's fingerprint is not the one recorded for that version. */
16
+ | "key-mismatch"
17
+ /** Wrong key, wrong purpose, wrong binding, or altered ciphertext. */
18
+ | "authentication"
19
+ /** The value carried an expiry that has passed. */
20
+ | "expired";
21
+ /**
22
+ * Thrown by `open` for every failure. The message is fixed so that nothing
23
+ * about the cause, the ciphertext or the binding can leak through it.
24
+ */
25
+ export declare class SecretUnreadableError extends Error {
26
+ /** See {@link SecretFailureReason}. Not for end users. */
27
+ readonly reason: SecretFailureReason;
28
+ constructor(reason: SecretFailureReason);
29
+ }
30
+ /**
31
+ * A key is missing or unusable. The message names the variable or key version
32
+ * and the problem, never the value.
33
+ */
34
+ export declare class SecretsKeyError extends Error {
35
+ constructor(message: string);
36
+ }
37
+ /**
38
+ * A configured key is not the key that was recorded for its version: its
39
+ * fingerprint differs. Usually a paste mistake, or a version number reused
40
+ * for a new key.
41
+ */
42
+ export declare class SecretsKeyMismatchError extends SecretsKeyError {
43
+ constructor(message: string);
44
+ }
45
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB;AAC7B,uEAAuE;AACrE,WAAW;AACb,6DAA6D;GAC3D,aAAa;AACf,kEAAkE;GAChE,iBAAiB;AACnB,sEAAsE;GACpE,cAAc;AAChB,sEAAsE;GACpE,gBAAgB;AAClB,mDAAmD;GACjD,SAAS,CAAC;AAEd;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,EAAE,mBAAmB,CAAC;gBAEzB,MAAM,EAAE,mBAAmB;CAKxC;AAED;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,KAAK;gBAC5B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM;CAI5B"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Thrown by `open` for every failure. The message is fixed so that nothing
3
+ * about the cause, the ciphertext or the binding can leak through it.
4
+ */
5
+ export class SecretUnreadableError extends Error {
6
+ constructor(reason) {
7
+ super("Secret could not be read.");
8
+ /** See {@link SecretFailureReason}. Not for end users. */
9
+ Object.defineProperty(this, "reason", {
10
+ enumerable: true,
11
+ configurable: true,
12
+ writable: true,
13
+ value: void 0
14
+ });
15
+ this.name = "SecretUnreadableError";
16
+ this.reason = reason;
17
+ }
18
+ }
19
+ /**
20
+ * A key is missing or unusable. The message names the variable or key version
21
+ * and the problem, never the value.
22
+ */
23
+ export class SecretsKeyError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "SecretsKeyError";
27
+ }
28
+ }
29
+ /**
30
+ * A configured key is not the key that was recorded for its version: its
31
+ * fingerprint differs. Usually a paste mistake, or a version number reused
32
+ * for a new key.
33
+ */
34
+ export class SecretsKeyMismatchError extends SecretsKeyError {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "SecretsKeyMismatchError";
38
+ }
39
+ }
@@ -0,0 +1,43 @@
1
+ /** What a key version is for, as recorded beside its fingerprint. */
2
+ export type SecretKeyState =
3
+ /** Encrypts new values and decrypts. Exactly one key is active. */
4
+ "active"
5
+ /** Decrypts only: an older key, or a new one not yet switched to. */
6
+ | "decrypt-only"
7
+ /** No longer needed. Its variable is expected to be gone. */
8
+ | "retired";
9
+ /**
10
+ * One key the app expects to find, with the fingerprint recorded when the key
11
+ * was generated. The list for an environment is committed with the app (in
12
+ * `loom.json`), so a deployed key that differs from the copy in the password
13
+ * manager is detected instead of trusted.
14
+ */
15
+ export interface ExpectedSecretKey {
16
+ id: number;
17
+ /** 16 lowercase hex characters from {@link secretKeyFingerprint}. */
18
+ fingerprint: string;
19
+ state: SecretKeyState;
20
+ }
21
+ /** Whether a string has the shape of a key fingerprint. */
22
+ export declare function isSecretKeyFingerprint(value: unknown): value is string;
23
+ /**
24
+ * A short public identifier of a key: the first 8 bytes of an HKDF output that
25
+ * is used for nothing else.
26
+ *
27
+ * A write-only variable cannot be read back, so this is how an operator proves
28
+ * that the key in the deployment is the key in the password manager: compute
29
+ * it from the saved copy, and compare with what the running app reports. It is
30
+ * safe to commit and to log. It is not a key id and never appears in a sealed
31
+ * string.
32
+ */
33
+ export declare function secretKeyFingerprint(key: Uint8Array): Promise<string>;
34
+ /**
35
+ * Validates an expected-key list, for example one read from `loom.json`, and
36
+ * returns a copy. Throws a `TypeError` naming the entry that is wrong.
37
+ *
38
+ * The list must have exactly one `active` key. No version and no fingerprint
39
+ * may appear twice: one fingerprint under two versions means one key was
40
+ * entered twice.
41
+ */
42
+ export declare function parseExpectedSecretKeys(value: unknown): ExpectedSecretKey[];
43
+ //# sourceMappingURL=fingerprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprint.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/fingerprint.ts"],"names":[],"mappings":"AAOA,qEAAqE;AACrE,MAAM,MAAM,cAAc;AACxB,mEAAmE;AACjE,QAAQ;AACV,qEAAqE;GACnE,cAAc;AAChB,6DAA6D;GAC3D,SAAS,CAAC;AAEd;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,qEAAqE;IACrE,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,cAAc,CAAC;CACvB;AAED,2DAA2D;AAC3D,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEtE;AAED;;;;;;;;;GASG;AACH,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CA0B3E;AAQD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,EAAE,CA6C3E"}
@@ -0,0 +1,87 @@
1
+ import { pae } from "./encoding.js";
2
+ import { SecretsKeyError } from "./errors.js";
3
+ import { isSecretKeyId, SECRETS_KEY_BYTES } from "./keyring.js";
4
+ const FINGERPRINT_BITS = 64;
5
+ const FINGERPRINT_PATTERN = /^[0-9a-f]{16}$/;
6
+ /** Whether a string has the shape of a key fingerprint. */
7
+ export function isSecretKeyFingerprint(value) {
8
+ return typeof value === "string" && FINGERPRINT_PATTERN.test(value);
9
+ }
10
+ /**
11
+ * A short public identifier of a key: the first 8 bytes of an HKDF output that
12
+ * is used for nothing else.
13
+ *
14
+ * A write-only variable cannot be read back, so this is how an operator proves
15
+ * that the key in the deployment is the key in the password manager: compute
16
+ * it from the saved copy, and compare with what the running app reports. It is
17
+ * safe to commit and to log. It is not a key id and never appears in a sealed
18
+ * string.
19
+ */
20
+ export async function secretKeyFingerprint(key) {
21
+ if (!(key instanceof Uint8Array) || key.length !== SECRETS_KEY_BYTES) {
22
+ throw new SecretsKeyError(`A key must be exactly ${SECRETS_KEY_BYTES} bytes to be fingerprinted.`);
23
+ }
24
+ const base = await globalThis.crypto.subtle.importKey("raw", new Uint8Array(key), "HKDF", false, ["deriveBits"]);
25
+ const bits = await globalThis.crypto.subtle.deriveBits({
26
+ name: "HKDF",
27
+ hash: "SHA-256",
28
+ salt: new Uint8Array(0),
29
+ info: pae(["loom-secrets", "ls1", "fingerprint"]),
30
+ }, base, FINGERPRINT_BITS);
31
+ return [...new Uint8Array(bits)]
32
+ .map((byte) => byte.toString(16).padStart(2, "0"))
33
+ .join("");
34
+ }
35
+ const KEY_STATES = [
36
+ "active",
37
+ "decrypt-only",
38
+ "retired",
39
+ ];
40
+ /**
41
+ * Validates an expected-key list, for example one read from `loom.json`, and
42
+ * returns a copy. Throws a `TypeError` naming the entry that is wrong.
43
+ *
44
+ * The list must have exactly one `active` key. No version and no fingerprint
45
+ * may appear twice: one fingerprint under two versions means one key was
46
+ * entered twice.
47
+ */
48
+ export function parseExpectedSecretKeys(value) {
49
+ if (!Array.isArray(value)) {
50
+ throw new TypeError("The expected key list must be an array.");
51
+ }
52
+ const ids = new Set();
53
+ const fingerprints = new Set();
54
+ const keys = value.map((entry, index) => {
55
+ const candidate = entry;
56
+ const where = `Expected key ${index + 1}`;
57
+ if (candidate === null || typeof candidate !== "object") {
58
+ throw new TypeError(`${where} must be an object.`);
59
+ }
60
+ if (!isSecretKeyId(candidate.id)) {
61
+ throw new TypeError(`${where} needs a key version as its id.`);
62
+ }
63
+ if (!isSecretKeyFingerprint(candidate.fingerprint)) {
64
+ throw new TypeError(`${where} needs a fingerprint of 16 lowercase hex characters.`);
65
+ }
66
+ if (!KEY_STATES.includes(candidate.state)) {
67
+ throw new TypeError(`${where} needs a state of active, decrypt-only or retired.`);
68
+ }
69
+ if (ids.has(candidate.id)) {
70
+ throw new TypeError(`Key version ${candidate.id} is listed twice.`);
71
+ }
72
+ if (fingerprints.has(candidate.fingerprint)) {
73
+ throw new TypeError(`Key version ${candidate.id} has the same fingerprint as another version.`);
74
+ }
75
+ ids.add(candidate.id);
76
+ fingerprints.add(candidate.fingerprint);
77
+ return {
78
+ fingerprint: candidate.fingerprint,
79
+ id: candidate.id,
80
+ state: candidate.state,
81
+ };
82
+ });
83
+ if (keys.filter((key) => key.state === "active").length !== 1) {
84
+ throw new TypeError("Exactly one expected key must be active.");
85
+ }
86
+ return keys;
87
+ }
@@ -0,0 +1,34 @@
1
+ /** What a sealed payload holds, recorded in the frame so `open` can check it. */
2
+ export type SecretPayloadKind = "text" | "bytes" | "json";
3
+ /** A parsed plaintext frame. */
4
+ export interface SecretFrame {
5
+ kind: SecretPayloadKind;
6
+ /** Seconds since the Unix epoch after which the value must not be used. */
7
+ expiresAt: number | undefined;
8
+ payload: Uint8Array<ArrayBuffer>;
9
+ }
10
+ /** Plaintext is padded to a multiple of this many bytes. */
11
+ export declare const FRAME_BLOCK_BYTES = 32;
12
+ /**
13
+ * Builds the plaintext that is encrypted:
14
+ *
15
+ * ```
16
+ * header ‖ [expiry] ‖ payload ‖ 0x80 ‖ 0x00… (to a multiple of 32 bytes)
17
+ * ```
18
+ *
19
+ * The header byte holds the payload kind in its low two bits and sets 0x80
20
+ * when an 8-byte big-endian expiry follows. Padding hides the exact length of
21
+ * short values such as passwords; it is removed only after the ciphertext has
22
+ * authenticated, so it cannot act as a padding oracle.
23
+ */
24
+ export declare function encodeFrame(frame: {
25
+ kind: SecretPayloadKind;
26
+ expiresAt?: number | undefined;
27
+ payload: Uint8Array;
28
+ }): Uint8Array<ArrayBuffer>;
29
+ /**
30
+ * Parses an authenticated frame, or returns `null` when it is not one that
31
+ * {@link encodeFrame} could have produced.
32
+ */
33
+ export declare function decodeFrame(bytes: Uint8Array): SecretFrame | null;
34
+ //# sourceMappingURL=frame.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/frame.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAE1D,gCAAgC;AAChC,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,iBAAiB,CAAC;IACxB,2EAA2E;IAC3E,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;CAClC;AAED,4DAA4D;AAC5D,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAapC;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE;IACjC,IAAI,EAAE,iBAAiB,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,OAAO,EAAE,UAAU,CAAC;CACrB,GAAG,UAAU,CAAC,WAAW,CAAC,CAwB1B;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,WAAW,GAAG,IAAI,CA4CjE"}
@@ -0,0 +1,86 @@
1
+ /** Plaintext is padded to a multiple of this many bytes. */
2
+ export const FRAME_BLOCK_BYTES = 32;
3
+ const KIND_CODES = {
4
+ text: 0,
5
+ bytes: 1,
6
+ json: 2,
7
+ };
8
+ const KINDS = ["text", "bytes", "json"];
9
+ const KIND_MASK = 0x03;
10
+ const EXPIRY_FLAG = 0x80;
11
+ const PADDING_MARKER = 0x80;
12
+ const EXPIRY_BYTES = 8;
13
+ /**
14
+ * Builds the plaintext that is encrypted:
15
+ *
16
+ * ```
17
+ * header ‖ [expiry] ‖ payload ‖ 0x80 ‖ 0x00… (to a multiple of 32 bytes)
18
+ * ```
19
+ *
20
+ * The header byte holds the payload kind in its low two bits and sets 0x80
21
+ * when an 8-byte big-endian expiry follows. Padding hides the exact length of
22
+ * short values such as passwords; it is removed only after the ciphertext has
23
+ * authenticated, so it cannot act as a padding oracle.
24
+ */
25
+ export function encodeFrame(frame) {
26
+ const hasExpiry = frame.expiresAt !== undefined;
27
+ if (hasExpiry &&
28
+ (!Number.isSafeInteger(frame.expiresAt) || frame.expiresAt < 0)) {
29
+ throw new RangeError("Expiry must be a non-negative whole second.");
30
+ }
31
+ const headerBytes = 1 + (hasExpiry ? EXPIRY_BYTES : 0);
32
+ const length = Math.ceil((headerBytes + frame.payload.length + 1) / FRAME_BLOCK_BYTES) * FRAME_BLOCK_BYTES;
33
+ const output = new Uint8Array(length);
34
+ output[0] = KIND_CODES[frame.kind] | (hasExpiry ? EXPIRY_FLAG : 0);
35
+ if (hasExpiry) {
36
+ new DataView(output.buffer).setBigUint64(1, BigInt(frame.expiresAt), false);
37
+ }
38
+ output.set(frame.payload, headerBytes);
39
+ output[headerBytes + frame.payload.length] = PADDING_MARKER;
40
+ return output;
41
+ }
42
+ /**
43
+ * Parses an authenticated frame, or returns `null` when it is not one that
44
+ * {@link encodeFrame} could have produced.
45
+ */
46
+ export function decodeFrame(bytes) {
47
+ if (bytes.length === 0 || bytes.length % FRAME_BLOCK_BYTES !== 0) {
48
+ return null;
49
+ }
50
+ let markerIndex = bytes.length - 1;
51
+ while (markerIndex >= 0 && bytes[markerIndex] === 0) {
52
+ markerIndex -= 1;
53
+ }
54
+ if (markerIndex < 0 ||
55
+ bytes[markerIndex] !== PADDING_MARKER ||
56
+ bytes.length - markerIndex > FRAME_BLOCK_BYTES) {
57
+ return null;
58
+ }
59
+ const header = bytes[0];
60
+ if ((header & ~(KIND_MASK | EXPIRY_FLAG)) !== 0) {
61
+ return null;
62
+ }
63
+ const kind = KINDS[header & KIND_MASK];
64
+ if (kind === undefined) {
65
+ return null;
66
+ }
67
+ const hasExpiry = (header & EXPIRY_FLAG) !== 0;
68
+ const headerBytes = 1 + (hasExpiry ? EXPIRY_BYTES : 0);
69
+ if (markerIndex < headerBytes) {
70
+ return null;
71
+ }
72
+ let expiresAt;
73
+ if (hasExpiry) {
74
+ const seconds = new DataView(bytes.buffer, bytes.byteOffset, bytes.length)
75
+ .getBigUint64(1, false);
76
+ if (seconds > BigInt(Number.MAX_SAFE_INTEGER)) {
77
+ return null;
78
+ }
79
+ expiresAt = Number(seconds);
80
+ }
81
+ return {
82
+ kind,
83
+ expiresAt,
84
+ payload: bytes.slice(headerBytes, markerIndex),
85
+ };
86
+ }
@@ -0,0 +1,62 @@
1
+ /** Every key is exactly this many random bytes. */
2
+ export declare const SECRETS_KEY_BYTES = 32;
3
+ export declare const DEFAULT_SECRETS_KEY_ENV_PREFIX = "LOOM_SECRETS_KEY_";
4
+ export declare const DEFAULT_SECRETS_ACTIVE_KEY_ENV = "LOOM_SECRETS_ACTIVE_KEY";
5
+ type SecretsEnv = Record<string, string | undefined>;
6
+ /**
7
+ * Where keys come from. Asynchronous so that a provider can later unwrap a key
8
+ * through a KMS without changing any stored ciphertext.
9
+ */
10
+ export interface SecretKeyring {
11
+ /** The key version that encrypts. Throws {@link SecretsKeyError}. */
12
+ activeKeyId(): Promise<number>;
13
+ /**
14
+ * The raw key for a version, or `null` when that version is not configured.
15
+ * Throws {@link SecretsKeyError} when it is configured but unusable.
16
+ */
17
+ key(id: number): Promise<Uint8Array | null>;
18
+ }
19
+ /** Options for {@link envKeyring}. */
20
+ export interface EnvKeyringOptions {
21
+ /** Defaults to `process.env`, read at call time and never at import. */
22
+ env?: SecretsEnv;
23
+ /** Variable name prefix; the key version is appended. */
24
+ keyPrefix?: string;
25
+ /** Variable that names the key version that encrypts. */
26
+ activeKeyName?: string;
27
+ }
28
+ /** Whether a number can be a key version: an integer from 1 to 999999999. */
29
+ export declare function isSecretKeyId(id: unknown): id is number;
30
+ /** Parses the decimal key version used in variable names and sealed strings. */
31
+ export declare function parseSecretKeyId(text: string): number | null;
32
+ /**
33
+ * Trims a configured key value and rejects what is certainly not a key: an
34
+ * empty value, or a placeholder a platform or build put in its place. Shared
35
+ * with the legacy reader so both name these cases the same way.
36
+ */
37
+ export declare function trimKeyValue(value: string, name: string): string;
38
+ /**
39
+ * Decodes one configured key, accepting standard base64 or base64url.
40
+ *
41
+ * Surrounding whitespace is trimmed: a pasted trailing newline is the common
42
+ * mistake, and a write-only variable cannot be inspected to find it. Errors
43
+ * name the variable and the problem, never the value.
44
+ */
45
+ export declare function decodeSecretKey(value: string, name: string): Uint8Array;
46
+ /**
47
+ * Reads keys from environment variables: one variable per key version
48
+ * (`LOOM_SECRETS_KEY_<n>`) and a required pointer
49
+ * (`LOOM_SECRETS_ACTIVE_KEY`) naming the version that encrypts.
50
+ *
51
+ * A version is always read by name. Nothing is enumerated and nothing is read
52
+ * until a key is needed, so a build that never seals or opens needs no key,
53
+ * and one unusable variable does not affect the others.
54
+ */
55
+ export declare function envKeyring(options?: EnvKeyringOptions): SecretKeyring;
56
+ /**
57
+ * A fixed set of keys, for tests and for callers that load keys themselves.
58
+ * `activeKeyId` may be omitted only when exactly one key is given.
59
+ */
60
+ export declare function staticKeyring(keys: Readonly<Record<number, Uint8Array>>, activeKeyId?: number): SecretKeyring;
61
+ export {};
62
+ //# sourceMappingURL=keyring.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyring.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/keyring.ts"],"names":[],"mappings":"AAIA,mDAAmD;AACnD,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,8BAA8B,sBAAsB,CAAC;AAClE,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAexE,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAErD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/B;;;OAGG;IACH,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;CAC7C;AAED,sCAAsC;AACtC,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,yDAAyD;IACzD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yDAAyD;IACzD,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,6EAA6E;AAC7E,wBAAgB,aAAa,CAAC,EAAE,EAAE,OAAO,GAAG,EAAE,IAAI,MAAM,CAGvD;AAED,gFAAgF;AAChF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE5D;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAiBhE;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CA4BvE;AAMD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,OAAO,GAAE,iBAAsB,GAAG,aAAa,CAkDzE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,EAC1C,WAAW,CAAC,EAAE,MAAM,GACnB,aAAa,CA8Bf"}
@@ -0,0 +1,160 @@
1
+ import * as dntShim from "../../_dnt.shims.js";
2
+ import { fromBase64Url } from "./encoding.js";
3
+ import { SecretsKeyError } from "./errors.js";
4
+ /** Every key is exactly this many random bytes. */
5
+ export const SECRETS_KEY_BYTES = 32;
6
+ export const DEFAULT_SECRETS_KEY_ENV_PREFIX = "LOOM_SECRETS_KEY_";
7
+ export const DEFAULT_SECRETS_ACTIVE_KEY_ENV = "LOOM_SECRETS_ACTIVE_KEY";
8
+ const KEY_ID_PATTERN = /^[1-9][0-9]{0,8}$/;
9
+ const ASCII_WHITESPACE_ENDS = /^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g;
10
+ // What platforms substitute for a value they will not reveal. Matched exactly:
11
+ // anything else that is not a key already fails the base64 check below.
12
+ const REDACTION_PLACEHOLDERS = new Set([
13
+ "[redacted]",
14
+ "[sensitive]",
15
+ "vercel sensitive value",
16
+ ]);
17
+ // Written by `loom` release tooling in place of an unreadable Secret during a
18
+ // local production build (see src/cli/vercelBuildEnv.ts).
19
+ const BUILD_PLACEHOLDER_PREFIX = "loom-build-only-";
20
+ /** Whether a number can be a key version: an integer from 1 to 999999999. */
21
+ export function isSecretKeyId(id) {
22
+ return typeof id === "number" && Number.isInteger(id) &&
23
+ KEY_ID_PATTERN.test(String(id));
24
+ }
25
+ /** Parses the decimal key version used in variable names and sealed strings. */
26
+ export function parseSecretKeyId(text) {
27
+ return KEY_ID_PATTERN.test(text) ? Number(text) : null;
28
+ }
29
+ /**
30
+ * Trims a configured key value and rejects what is certainly not a key: an
31
+ * empty value, or a placeholder a platform or build put in its place. Shared
32
+ * with the legacy reader so both name these cases the same way.
33
+ */
34
+ export function trimKeyValue(value, name) {
35
+ const trimmed = value.replace(ASCII_WHITESPACE_ENDS, "");
36
+ if (trimmed === "") {
37
+ throw new SecretsKeyError(`${name} is empty.`);
38
+ }
39
+ const lowered = trimmed.toLowerCase();
40
+ if (REDACTION_PLACEHOLDERS.has(lowered)) {
41
+ throw new SecretsKeyError(`${name} is a redaction placeholder; the real value is not available to this process.`);
42
+ }
43
+ if (lowered.startsWith(BUILD_PLACEHOLDER_PREFIX)) {
44
+ throw new SecretsKeyError(`${name} is a build-only placeholder; secrets cannot be used during this build.`);
45
+ }
46
+ return trimmed;
47
+ }
48
+ /**
49
+ * Decodes one configured key, accepting standard base64 or base64url.
50
+ *
51
+ * Surrounding whitespace is trimmed: a pasted trailing newline is the common
52
+ * mistake, and a write-only variable cannot be inspected to find it. Errors
53
+ * name the variable and the problem, never the value.
54
+ */
55
+ export function decodeSecretKey(value, name) {
56
+ const trimmed = trimKeyValue(value, name);
57
+ const invalid = new SecretsKeyError(`${name} must be base64 or base64url of ${SECRETS_KEY_BYTES} random bytes.`);
58
+ const unpadded = trimmed.replace(/=+$/, "");
59
+ const padding = trimmed.length - unpadded.length;
60
+ const usesStandard = /[+/]/.test(unpadded);
61
+ if (usesStandard && /[-_]/.test(unpadded)) {
62
+ throw invalid;
63
+ }
64
+ // Padding is optional, but when present it must be the right amount.
65
+ if (padding !== 0 && padding !== (4 - (unpadded.length % 4)) % 4) {
66
+ throw invalid;
67
+ }
68
+ const bytes = fromBase64Url(unpadded.replaceAll("+", "-").replaceAll("/", "_"));
69
+ if (!bytes) {
70
+ throw invalid;
71
+ }
72
+ if (bytes.length !== SECRETS_KEY_BYTES) {
73
+ throw new SecretsKeyError(`${name} must decode to exactly ${SECRETS_KEY_BYTES} bytes; received ${bytes.length}.`);
74
+ }
75
+ return bytes;
76
+ }
77
+ function processEnv() {
78
+ return dntShim.dntGlobalThis.process?.env ?? {};
79
+ }
80
+ /**
81
+ * Reads keys from environment variables: one variable per key version
82
+ * (`LOOM_SECRETS_KEY_<n>`) and a required pointer
83
+ * (`LOOM_SECRETS_ACTIVE_KEY`) naming the version that encrypts.
84
+ *
85
+ * A version is always read by name. Nothing is enumerated and nothing is read
86
+ * until a key is needed, so a build that never seals or opens needs no key,
87
+ * and one unusable variable does not affect the others.
88
+ */
89
+ export function envKeyring(options = {}) {
90
+ const keyPrefix = options.keyPrefix ?? DEFAULT_SECRETS_KEY_ENV_PREFIX;
91
+ const activeKeyName = options.activeKeyName ??
92
+ DEFAULT_SECRETS_ACTIVE_KEY_ENV;
93
+ const env = () => options.env ?? processEnv();
94
+ // Reading the environment can itself throw, for example under Deno without
95
+ // permission for that variable. Either way the caller gets a rejection.
96
+ function read(name) {
97
+ try {
98
+ return env()[name];
99
+ }
100
+ catch {
101
+ throw new SecretsKeyError(`${name} could not be read from the environment.`);
102
+ }
103
+ }
104
+ return {
105
+ activeKeyId() {
106
+ try {
107
+ const raw = read(activeKeyName);
108
+ const id = raw === undefined
109
+ ? null
110
+ : parseSecretKeyId(raw.replace(ASCII_WHITESPACE_ENDS, ""));
111
+ if (id === null) {
112
+ throw new SecretsKeyError(`${activeKeyName} must name the key version that encrypts, for example 1.`);
113
+ }
114
+ return Promise.resolve(id);
115
+ }
116
+ catch (error) {
117
+ return Promise.reject(error);
118
+ }
119
+ },
120
+ key(id) {
121
+ if (!isSecretKeyId(id)) {
122
+ return Promise.resolve(null);
123
+ }
124
+ const name = `${keyPrefix}${id}`;
125
+ try {
126
+ const raw = read(name);
127
+ return Promise.resolve(raw === undefined ? null : decodeSecretKey(raw, name));
128
+ }
129
+ catch (error) {
130
+ return Promise.reject(error);
131
+ }
132
+ },
133
+ };
134
+ }
135
+ /**
136
+ * A fixed set of keys, for tests and for callers that load keys themselves.
137
+ * `activeKeyId` may be omitted only when exactly one key is given.
138
+ */
139
+ export function staticKeyring(keys, activeKeyId) {
140
+ const ids = Object.keys(keys).map(Number);
141
+ const active = activeKeyId ?? (ids.length === 1 ? ids[0] : undefined);
142
+ return {
143
+ activeKeyId() {
144
+ if (active === undefined || !isSecretKeyId(active) || !keys[active]) {
145
+ return Promise.reject(new SecretsKeyError("staticKeyring needs an active key version that is one of its keys."));
146
+ }
147
+ return Promise.resolve(active);
148
+ },
149
+ key(id) {
150
+ const key = isSecretKeyId(id) ? keys[id] : undefined;
151
+ if (!key) {
152
+ return Promise.resolve(null);
153
+ }
154
+ if (key.length !== SECRETS_KEY_BYTES) {
155
+ return Promise.reject(new SecretsKeyError(`Key version ${id} must be exactly ${SECRETS_KEY_BYTES} bytes; received ${key.length}.`));
156
+ }
157
+ return Promise.resolve(new Uint8Array(key));
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,60 @@
1
+ import "../../_dnt.polyfills.js";
2
+ import { type SecretFailureReason } from "./errors.js";
3
+ export { type SecretFailureReason, SecretsKeyError, SecretUnreadableError, } from "./errors.js";
4
+ type LegacyEnv = Record<string, string | undefined>;
5
+ /**
6
+ * A value in the format porty3 wrote before Loom's sealed strings: AES-GCM
7
+ * ciphertext and IV as standard base64, with no associated data.
8
+ */
9
+ export interface LegacySecretParts {
10
+ /** Base64 ciphertext with the 16-byte authentication tag appended. */
11
+ value: string;
12
+ /** Base64 initialisation vector. Existing rows use 16 bytes. */
13
+ iv: string;
14
+ /** Which `CRYPTO_KEY_<n>` encrypted it. Rows that predate the field are 0. */
15
+ keyVersion?: number;
16
+ }
17
+ /** The reasons a legacy value can fail for; it has no expiry or fingerprint. */
18
+ export type LegacyFailureReason = Extract<SecretFailureReason, "malformed" | "unknown-key" | "key-unavailable" | "authentication">;
19
+ /** Reported to `onFailure` for every legacy value that could not be opened. */
20
+ export interface LegacyFailureEvent {
21
+ /** `null` when the parts themselves were malformed. */
22
+ keyVersion: number | null;
23
+ reason: LegacyFailureReason;
24
+ }
25
+ /** Options for {@link createLegacyPartsReader}. */
26
+ export interface LegacyPartsReaderOptions {
27
+ /** Defaults to `process.env`, read when a key is first needed. */
28
+ env?: LegacyEnv;
29
+ /** Variable name prefix; the key version is appended. */
30
+ keyPrefix?: string;
31
+ /** Receives no plaintext or ciphertext. Whatever it throws is ignored. */
32
+ onFailure?: (event: LegacyFailureEvent) => unknown;
33
+ }
34
+ /** Read-only access to values in the legacy format. */
35
+ export interface LegacyPartsReader {
36
+ /** Throws {@link SecretUnreadableError} on any failure. */
37
+ open(parts: LegacySecretParts): Promise<string>;
38
+ /** Like `open`, but `null` when the value cannot be read. */
39
+ tryOpen(parts: LegacySecretParts): Promise<string | null>;
40
+ /**
41
+ * Checks that a key version is configured and usable, without opening
42
+ * anything. Throws {@link SecretsKeyError} naming the variable and the
43
+ * problem. `open` reports the same problem only as `key-unavailable`, so
44
+ * this is how an operator finds out why. Defaults to version 0.
45
+ */
46
+ assertKey(keyVersion?: number): Promise<void>;
47
+ }
48
+ /**
49
+ * Opens values in porty3's original format, so that rows written before the
50
+ * move to sealed strings stay readable for as long as they exist.
51
+ *
52
+ * There is deliberately no way to write this format here. It has no key
53
+ * version of its own, no associated data and therefore no binding: a value
54
+ * opens wherever it is placed. New data belongs in a sealed string.
55
+ *
56
+ * Each key is read by name and decoded the first time it is needed, so an
57
+ * unusable `CRYPTO_KEY_1` does not stop version 0 from working.
58
+ */
59
+ export declare function createLegacyPartsReader(options?: LegacyPartsReaderOptions): LegacyPartsReader;
60
+ //# sourceMappingURL=legacy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/legacy.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,CAAC;AAEjC,OAAO,EACL,KAAK,mBAAmB,EAGzB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,KAAK,mBAAmB,EACxB,eAAe,EACf,qBAAqB,GACtB,MAAM,aAAa,CAAC;AAarB,KAAK,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAEpD;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,sEAAsE;IACtE,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,EAAE,EAAE,MAAM,CAAC;IACX,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,gFAAgF;AAChF,MAAM,MAAM,mBAAmB,GAAG,OAAO,CACvC,mBAAmB,EACnB,WAAW,GAAG,aAAa,GAAG,iBAAiB,GAAG,gBAAgB,CACnE,CAAC;AAEF,+EAA+E;AAC/E,MAAM,WAAW,kBAAkB;IACjC,uDAAuD;IACvD,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,MAAM,EAAE,mBAAmB,CAAC;CAC7B;AAED,mDAAmD;AACnD,MAAM,WAAW,wBAAwB;IACvC,kEAAkE;IAClE,GAAG,CAAC,EAAE,SAAS,CAAC;IAChB,yDAAyD;IACzD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC;CACpD;AAED,uDAAuD;AACvD,MAAM,WAAW,iBAAiB;IAChC,2DAA2D;IAC3D,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAChD,6DAA6D;IAC7D,OAAO,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC1D;;;;;OAKG;IACH,SAAS,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C;AAsCD;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE,wBAA6B,GACrC,iBAAiB,CAkHnB"}