Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ycmjason committed Oct 8, 2024
0 parents commit 02b8dd0
Show file tree
Hide file tree
Showing 21 changed files with 1,321 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Publish
on:
push:
branches:
- main

jobs:
publish:
runs-on: ubuntu-latest

permissions:
contents: read
id-token: write

steps:
- uses: actions/checkout@v4

- name: Publish package
run: npx jsr publish
Empty file added .gitignore
Empty file.
15 changes: 15 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"prettier.enable": false,
"deno.enable": true,
"deno.lint": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"editor.codeActionsOnSave": {
"source.fixAll": "always",
"source.organizeImports": "always"
},
"files.associations": {
"*.css": "tailwindcss"
},
"files.insertFinalNewline": true
}
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
MIT License

Copyright (c) 2024 fishball.app

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @fishball/acme

A zero-dependencies acme-client written from scratch.
13 changes: 13 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "@fishball/acme-client",
"version": "0.1.0",
"exports": "./src/mod.ts",
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"useUnknownInCatchVariables": true,
"noFallthroughCasesInSwitch": true
},
"imports": {},
"license": "MIT"
}
41 changes: 41 additions & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

117 changes: 117 additions & 0 deletions examples/acme-cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { AcmeClient } from "../src/AcmeClient.ts";
import { Dns01ChallengeUtils } from "../src/Dns01ChallengeUtils.ts";

export const DOMAIN = "dynm.link";
const EMAIL = "[email protected]";

console.log("Initializing acme client... (this fetches the directory)");
const acmeClient = await AcmeClient.init("lets-encrypt-staging");

console.log("Creating account...");
const acmeAccount = await acmeClient.createAccount({ email: EMAIL });

console.log(`Creating order for "${DOMAIN}"...`);
const acmeOrder = await acmeClient.createOrder({
domains: [DOMAIN],
account: acmeAccount,
});

console.log(`Digesting authorization...`);
const [authorization] = await acmeOrder.getAuthorizations();

if (authorization === undefined) {
throw new Error("cannot find authorization");
}

const dns01Challenge = authorization.findChallenge("dns-01") ?? (() => {
throw new Error("DNS-01 challenge not found");
})();

const expectedRecord = {
domain: `_acme-challenge.${DOMAIN}.`,
content: await dns01Challenge.digestToken(),
};

console.log(`Please update your DNS record as follows:`);
console.table([
{
type: "TXT",
name: expectedRecord.domain,
content: expectedRecord.content,
},
]);

alert("After updating the DNS records, press enter to continue...");

console.log("Polling DNS to verify txt is updated...");
await Dns01ChallengeUtils.pollDnsTxtRecord({
domain: expectedRecord.domain,
pollUntil: expectedRecord.content,
onBeforeEachAttempt: () => {
console.log(`Looking up DNS records for ${expectedRecord.domain}...`);
},
onAfterFailAttempt: (records) => {
console.log("Attempt failed. Found these instead:");
console.log(`{ ${[...new Set(records.flat())].join(", ")} }`, "\n");
console.log("Please ensure you have updated the DNS record as follows:");
console.table([
{
type: "TXT",
name: expectedRecord.domain,
content: expectedRecord.content,
},
]);

console.log("Retrying later...");
},
});

console.log("Records found!");

console.log("Submitting challenge...");
await dns01Challenge.submit();

console.log('Polling order status until "ready"...');
await acmeOrder.pollOrderStatus(
{
pollUntil: "ready",
onBeforeAttempt: () => console.log("Fetching order..."),
onAfterFailAttempt: (o) => {
console.log(`Received status ${o.status}. Retrying later...`);
},
},
);

console.log("Order is ready. Finalizing...");
console.log("Submiting CSR");
// use the CryptoKeyPair if you need to?
const _csrKeyPair = await acmeOrder.finalize();

console.log("CSR submitted! Polling order till certificate is ready...");

await acmeOrder
.pollOrderStatus(
{
pollUntil: "valid",
onBeforeAttempt: () => console.log("polling order status..."),
onAfterFailAttempt: (order) => {
console.log(`Received status ${order.status}. Retrying later...`);
},
},
);

console.log("Order finalized. Downloading certificate...");

if (acmeOrder.orderResponse.status !== "valid") {
throw new Error(
`Expected order status to be valid. Got ${acmeOrder.orderResponse.status} instead.`,
);
}

if (acmeOrder.orderResponse.certificate === undefined) {
throw new Error("order is finalized but certificate is 'undefined'");
}

const certificate = await acmeOrder.getCertificate();
console.log("\nCertificate is ready:");
console.log(certificate);
17 changes: 17 additions & 0 deletions src/AcmeAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { AcmeClient } from "./AcmeClient.ts";

export class AcmeAccount {
client: AcmeClient;
keyPair: CryptoKeyPair;
url: string;

constructor({ client, keyPair, url }: {
client: AcmeClient;
keyPair: CryptoKeyPair;
url: string;
}) {
this.client = client;
this.keyPair = keyPair;
this.url = url;
}
}
51 changes: 51 additions & 0 deletions src/AcmeAuthorization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
AcmeChallenge,
type AcmeChallengeType,
type RawAcmeChallengeObject,
} from "./AcmeChallenge.ts";
import type { AcmeOrder } from "./AcmeOrder.ts";

export type RawAcmeAuthorizationResponse = {
status:
| "pending"
| "valid"
| "invalid"
| "deactivated"
| "expired"
| "revoked"; // the status of the authorization
expires?: string; // the expiry date of the authorization, optional if not applicable
identifier: {
type: "dns"; // identifier type, usually DNS
value: string; // the domain name
};
challenges: RawAcmeChallengeObject[];
wildcard?: boolean; // optional, true if the identifier is a wildcard domain
};

export class AcmeAuthorization {
authorizationResponse: RawAcmeAuthorizationResponse;
order: AcmeOrder;

constructor(
{ order, authorizationResponse }: {
order: AcmeOrder;
authorizationResponse: RawAcmeAuthorizationResponse;
},
) {
this.order = order;
this.authorizationResponse = authorizationResponse;
}

findChallenge(type: AcmeChallengeType): AcmeChallenge | undefined {
const challengeObject = this.authorizationResponse.challenges.find((
challenge,
) => challenge.type === type);

if (challengeObject === undefined) return undefined;

return new AcmeChallenge({
authorization: this,
challengeObject,
});
}
}
Loading

0 comments on commit 02b8dd0

Please sign in to comment.