GitHubivarvong
ply
main
1// SSH signatures for commits (PROTOCOL.sshsig, as `ssh-keygen -Y sign -n git` / `git commit -S` with gpg.format=ssh
2// produce them), with Ed25519 through WebCrypto — available in Workers and node ≥ 20 — and no dependency.
3//
4// The signed message is the commit object exactly as it would be stored *without* the gpgsig header; the gpgsig header
5// is then inserted after `committer` (where git puts it), its continuation lines prefixed by a space. Pure except
6// crypto.subtle.sign; verified by `git verify-commit` with an allowed-signers file in test/sign.test.js.
7import { callbackFailed, fail } from './errors.js';
8import type { ErrorOf } from './errors.js';
9import type { Result } from './result.js';
10import { err } from './result.js';
11import { te, bufferSource, concat, decodeBytes, encodeBytes } from './bytes.js';
12import { COMMIT_HEADER_COMMITTER, COMMIT_HEADER_ENCODING } from './format.js';
13import { atOr } from './absent.js';
15const u32 = (n: number): Uint8Array => Uint8Array.from([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
16const sshString = (b: string | Uint8Array): Uint8Array => { const bytes: Uint8Array = typeof b === 'string' ? te.encode(b) : b; return concat([u32(bytes.length), bytes]); };
17const b64 = (bytes: Uint8Array): string => btoa(String.fromCodePoint(...bytes));
18const MAGIC = te.encode('SSHSIG');
19const KEY_TYPE = 'ssh-ed25519';
21// Public key in OpenSSH wire form and in authorized_keys form (`ssh-ed25519 AAAA…`), from the raw 32-byte key.
22export type SshPublicKey = { readonly wire: Uint8Array; readonly line: string };
23export const sshPublicKey = (raw32: Uint8Array): SshPublicKey => { const wire: Uint8Array = concat([sshString(KEY_TYPE), sshString(raw32)]); return { wire, line: `${KEY_TYPE} ${b64(wire)}` }; };
25export function armor(blob: Uint8Array): string {
26 const s = b64(blob);
27 const lines: string[] = []; for (let i = 0; i < s.length; i += 70) lines.push(s.slice(i, i + 70));
28 return `-----BEGIN SSH SIGNATURE-----\n${lines.join('\n')}\n-----END SSH SIGNATURE-----\n`;
29}
31// A signer from a WebCrypto Ed25519 key pair. `publicKeyRaw` is the 32-byte raw public key (exportKey('raw')).
32export type Signer = {
33 readonly kind: 'ssh-ed25519';
34 readonly publicKeyLine: string;
35 // namespace: 'git' when none is given (ssh-keygen -Y sign -n git)
36 sign(message: Uint8Array, ...namespace: [] | [string]): Promise<string>;
37};
38// WebCrypto's key, named through the one thing every supported lib declares: the global `crypto` and the key its
39// `subtle.sign` takes. The type names `CryptoKey` and `CryptoKeyPair` are DOM-lib names a Node consumer with lib ES2022
40// + @types/node does not have, and the global `CryptoKey` value exists only from @types/node 24 (20 and 22 declare
41// `crypto` alone), so neither can appear in the declarations. test/dist-types.test.js compiles them on each.
42type WebCryptoKey = Parameters<typeof crypto.subtle.sign>[1];
43type WebCryptoKeyPair = { privateKey: WebCryptoKey; publicKey: WebCryptoKey };
44export type SignerKey = { readonly privateKey: WebCryptoKey; readonly publicKeyRaw: Uint8Array };
46export function ed25519Signer({ privateKey, publicKeyRaw }: SignerKey): Signer {
47 const pub = sshPublicKey(publicKeyRaw);
48 return {
49 kind: KEY_TYPE, publicKeyLine: pub.line,
50 async sign(message: Uint8Array, ...given: [] | [string]): Promise<string> {
51 const [namespace = 'git'] = given;
52 const h = new Uint8Array(await crypto.subtle.digest('SHA-512', bufferSource(message)));
53 const toSign: Uint8Array<ArrayBuffer> = concat([MAGIC, sshString(namespace), sshString(''), sshString('sha512'), sshString(h)]);
54 const sig = new Uint8Array(await crypto.subtle.sign('Ed25519', privateKey, toSign));
55 const blob: Uint8Array = concat([MAGIC, u32(1), sshString(pub.wire), sshString(namespace), sshString(''), sshString('sha512'), sshString(concat([sshString(KEY_TYPE), sshString(sig)]))]);
56 return armor(blob);
57 },
58 };
59}
62// Pure: splice a gpgsig header into an encoded commit. commit_tree_extended writes encoding, then gpgsig.
63// The signature goes after encoding when that header is present, otherwise immediately after committer.
64export function withGpgsig(commitBytes: Uint8Array, signatureText: string): Result<Uint8Array<ArrayBuffer>, ErrorOf<'bad_request'>> {
65 // decodeBytes/encodeBytes: a Latin-1 message or ident goes back out as its own bytes, and so is what was signed (#43)
66 const text: string = decodeBytes(commitBytes);
67 const nl = text.indexOf('\n\n');
68 // The header lines end at the blank line or, in a commit with no body section, at its final newline. Everything
69 // from there on goes back out as it came in: the object without its gpgsig header is the object that was signed.
70 const noBodyEnd = text.endsWith('\n') ? text.length - 1 : text.length;
71 const headEnd = nl < 0 ? noBodyEnd : nl;
72 const headers = text.slice(0, headEnd).split('\n');
73 let i = headers.findIndex(l => l.startsWith(`${COMMIT_HEADER_COMMITTER} `));
74 if (i < 0) return fail('bad_request', 'commit has no committer line');
75 if (atOr(headers, i + 1, '').startsWith(`${COMMIT_HEADER_ENCODING} `)) i++;
76 // the gpgsig header: the armored signature, its continuation lines prefixed by a space
77 headers.splice(i + 1, 0, `gpgsig ${signatureText.replace(/\n$/u, '').split('\n').join('\n ')}`);
78 return encodeBytes(headers.join('\n') + text.slice(headEnd), 'commit');
79}
81// Sign an encoded (unsigned) commit: the signed commit bytes. The message signed is the unsigned commit. The signer is
82// the caller's: what it throws or rejects with (or a signature that is not a string) is an Err naming 'signer' with the
83// thrown value as `cause`, never a throw. Callers sign while building the commit, before the push request exists.
84export async function signCommit(commitBytes: Uint8Array, signer: Signer, namespace = 'git'): Promise<Result<Uint8Array<ArrayBuffer>, ErrorOf<'bad_request'>>> {
85 let signature: unknown;
86 try { signature = await signer.sign(commitBytes, namespace); } catch (e) { return err(callbackFailed('signer', e)); }
87 if (typeof signature !== 'string') return fail('bad_request', 'caller-supplied signer returned a signature that is not a string', { what: 'signer', got: typeof signature });
88 return withGpgsig(commitBytes, signature);
89}
91// Convenience for node/tests: a fresh Ed25519 key pair as a signer.
92export type GeneratedSigner = { readonly signer: Signer; readonly keyPair: WebCryptoKeyPair; readonly publicKeyRaw: Uint8Array };
93export async function generateSigner(): Promise<GeneratedSigner> {
94 const kp = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
95 const publicKeyRaw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey));
96 return { signer: ed25519Signer({ privateKey: kp.privateKey, publicKeyRaw }), keyPair: kp, publicKeyRaw };
97}
Diagnostics6 git calls · 219 ms
CallStatusSizeTime0219 ms
discover200191 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=191 git.server.agent=git/github-9922ec520325-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=191 git.pkt.payload.max=36
ls-refs20012 KiB87 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=86 git.response.bytes=11990 git.response.cache=EXPIRED git.response.duration_ms=87 git.protocol.version=2 git.pkt.frames=152 git.pkt.data=151 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=11990 git.pkt.payload.max=122 git.ls_refs.count=151 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 102004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=4347 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4347 git.pkt.payload.max=4247 git.sideband.band1.bytes=4247 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=10 git.pack.bytes=4247 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400 git.pack.full=10Open pack map
fetchtree:0200919 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=919 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=919 git.pkt.payload.max=892 git.sideband.band1.bytes=892 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=892 git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76eOpen pack map
fetchtree:02002.4 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=2507 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=8f720d29ff85ce682ffdad9c393b04a3834c3203 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2507 git.pkt.payload.max=2480 git.sideband.band1.bytes=2480 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=2480 git.pack.trailer=723b6bf1d4d6021fe5eb940c622b9ff00ee4a381Open pack map
fetch2002.7 KiB123 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=123 git.response.bytes=2756 git.response.cache=MISS git.response.duration_ms=123 git.fetch.wants=6baf3e9c4d1712cedac080bdb5c13f454e540ccf git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2756 git.pkt.payload.max=2729 git.sideband.band1.bytes=2729 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://github.com/ivarvong/ply
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e2caf21e694b67
- Request
- 3797278a…
- Protocol
- v2 · sha1
- Agent
- git/github-9922ec520325-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format